qrcode.vue 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1092 +1,1178 @@
1
1
  /*!
2
- * qrcode.vue v3.4.0
3
- * A Vue.js component to generate QRCode.
4
- * © 2017-2023 @scopewu(https://github.com/scopewu)
2
+ * qrcode.vue v3.5.0
3
+ * A Vue.js component to generate QRCode. Both support Vue 2 and Vue 3
4
+ * © 2017-PRESENT @scopewu(https://github.com/scopewu)
5
5
  * MIT License.
6
6
  */
7
7
  (function (global, factory) {
8
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue')) :
9
- typeof define === 'function' && define.amd ? define(['vue'], factory) :
10
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.QrcodeVue = factory(global.Vue));
11
- })(this, (function (vue) { 'use strict';
8
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) :
9
+ typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) :
10
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.QrcodeVue = {}, global.Vue));
11
+ })(this, (function (exports, vue) { 'use strict';
12
12
 
13
- /******************************************************************************
14
- Copyright (c) Microsoft Corporation.
13
+ /******************************************************************************
14
+ Copyright (c) Microsoft Corporation.
15
15
 
16
- Permission to use, copy, modify, and/or distribute this software for any
17
- purpose with or without fee is hereby granted.
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted.
18
18
 
19
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
- PERFORMANCE OF THIS SOFTWARE.
26
- ***************************************************************************** */
19
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
+ PERFORMANCE OF THIS SOFTWARE.
26
+ ***************************************************************************** */
27
+ /* global Reflect, Promise, SuppressedError, Symbol */
27
28
 
28
- var __assign = function() {
29
- __assign = Object.assign || function __assign(t) {
30
- for (var s, i = 1, n = arguments.length; i < n; i++) {
31
- s = arguments[i];
32
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
33
- }
34
- return t;
35
- };
36
- return __assign.apply(this, arguments);
37
- };
29
+
30
+ var __assign = function() {
31
+ __assign = Object.assign || function __assign(t) {
32
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
33
+ s = arguments[i];
34
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
35
+ }
36
+ return t;
37
+ };
38
+ return __assign.apply(this, arguments);
39
+ };
40
+
41
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
42
+ var e = new Error(message);
43
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
44
+ };
38
45
 
46
+ /*
47
+ * QR Code generator library (TypeScript)
48
+ *
49
+ * Copyright (c) Project Nayuki. (MIT License)
50
+ * https://www.nayuki.io/page/qr-code-generator-library
51
+ *
52
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
53
+ * this software and associated documentation files (the "Software"), to deal in
54
+ * the Software without restriction, including without limitation the rights to
55
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
56
+ * the Software, and to permit persons to whom the Software is furnished to do so,
57
+ * subject to the following conditions:
58
+ * - The above copyright notice and this permission notice shall be included in
59
+ * all copies or substantial portions of the Software.
60
+ * - The Software is provided "as is", without warranty of any kind, express or
61
+ * implied, including but not limited to the warranties of merchantability,
62
+ * fitness for a particular purpose and noninfringement. In no event shall the
63
+ * authors or copyright holders be liable for any claim, damages or other
64
+ * liability, whether in an action of contract, tort or otherwise, arising from,
65
+ * out of or in connection with the Software or the use or other dealings in the
66
+ * Software.
67
+ */
68
+ var qrcodegen;
69
+ (function (qrcodegen) {
70
+ /*---- QR Code symbol class ----*/
39
71
  /*
40
- * QR Code generator library (TypeScript)
72
+ * A QR Code symbol, which is a type of two-dimension barcode.
73
+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
74
+ * Instances of this class represent an immutable square grid of dark and light cells.
75
+ * The class provides static factory functions to create a QR Code from text or binary data.
76
+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
77
+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
41
78
  *
42
- * Copyright (c) Project Nayuki. (MIT License)
43
- * https://www.nayuki.io/page/qr-code-generator-library
44
- *
45
- * Permission is hereby granted, free of charge, to any person obtaining a copy of
46
- * this software and associated documentation files (the "Software"), to deal in
47
- * the Software without restriction, including without limitation the rights to
48
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
49
- * the Software, and to permit persons to whom the Software is furnished to do so,
50
- * subject to the following conditions:
51
- * - The above copyright notice and this permission notice shall be included in
52
- * all copies or substantial portions of the Software.
53
- * - The Software is provided "as is", without warranty of any kind, express or
54
- * implied, including but not limited to the warranties of merchantability,
55
- * fitness for a particular purpose and noninfringement. In no event shall the
56
- * authors or copyright holders be liable for any claim, damages or other
57
- * liability, whether in an action of contract, tort or otherwise, arising from,
58
- * out of or in connection with the Software or the use or other dealings in the
59
- * Software.
79
+ * Ways to create a QR Code object:
80
+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
81
+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
82
+ * - Low level: Custom-make the array of data codeword bytes (including
83
+ * segment headers and final padding, excluding error correction codewords),
84
+ * supply the appropriate version number, and call the QrCode() constructor.
85
+ * (Note that all ways require supplying the desired error correction level.)
60
86
  */
61
- var qrcodegen;
62
- (function (qrcodegen) {
63
- /*---- QR Code symbol class ----*/
64
- /*
65
- * A QR Code symbol, which is a type of two-dimension barcode.
66
- * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
67
- * Instances of this class represent an immutable square grid of dark and light cells.
68
- * The class provides static factory functions to create a QR Code from text or binary data.
69
- * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
70
- * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
71
- *
72
- * Ways to create a QR Code object:
73
- * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
74
- * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
75
- * - Low level: Custom-make the array of data codeword bytes (including
76
- * segment headers and final padding, excluding error correction codewords),
77
- * supply the appropriate version number, and call the QrCode() constructor.
78
- * (Note that all ways require supplying the desired error correction level.)
79
- */
80
- var QrCode = /** @class */ (function () {
81
- /*-- Constructor (low level) and fields --*/
82
- // Creates a new QR Code with the given version number,
83
- // error correction level, data codeword bytes, and mask number.
84
- // This is a low-level API that most users should not use directly.
85
- // A mid-level API is the encodeSegments() function.
86
- function QrCode(
87
- // The version number of this QR Code, which is between 1 and 40 (inclusive).
88
- // This determines the size of this barcode.
89
- version,
90
- // The error correction level used in this QR Code.
91
- errorCorrectionLevel, dataCodewords, msk) {
92
- this.version = version;
93
- this.errorCorrectionLevel = errorCorrectionLevel;
94
- // The modules of this QR Code (false = light, true = dark).
95
- // Immutable after constructor finishes. Accessed through getModule().
96
- this.modules = [];
97
- // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
98
- this.isFunction = [];
99
- // Check scalar arguments
100
- if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
101
- throw new RangeError("Version value out of range");
102
- if (msk < -1 || msk > 7)
103
- throw new RangeError("Mask value out of range");
104
- this.size = version * 4 + 17;
105
- // Initialize both grids to be size*size arrays of Boolean false
106
- var row = [];
107
- for (var i = 0; i < this.size; i++)
108
- row.push(false);
109
- for (var i = 0; i < this.size; i++) {
110
- this.modules.push(row.slice()); // Initially all light
111
- this.isFunction.push(row.slice());
112
- }
113
- // Compute ECC, draw modules
114
- this.drawFunctionPatterns();
115
- var allCodewords = this.addEccAndInterleave(dataCodewords);
116
- this.drawCodewords(allCodewords);
117
- // Do masking
118
- if (msk == -1) { // Automatically choose best mask
119
- var minPenalty = 1000000000;
120
- for (var i = 0; i < 8; i++) {
121
- this.applyMask(i);
122
- this.drawFormatBits(i);
123
- var penalty = this.getPenaltyScore();
124
- if (penalty < minPenalty) {
125
- msk = i;
126
- minPenalty = penalty;
127
- }
128
- this.applyMask(i); // Undoes the mask due to XOR
129
- }
130
- }
131
- assert(0 <= msk && msk <= 7);
132
- this.mask = msk;
133
- this.applyMask(msk); // Apply the final choice of mask
134
- this.drawFormatBits(msk); // Overwrite old format bits
135
- this.isFunction = [];
87
+ var QrCode = /** @class */ (function () {
88
+ /*-- Constructor (low level) and fields --*/
89
+ // Creates a new QR Code with the given version number,
90
+ // error correction level, data codeword bytes, and mask number.
91
+ // This is a low-level API that most users should not use directly.
92
+ // A mid-level API is the encodeSegments() function.
93
+ function QrCode(
94
+ // The version number of this QR Code, which is between 1 and 40 (inclusive).
95
+ // This determines the size of this barcode.
96
+ version,
97
+ // The error correction level used in this QR Code.
98
+ errorCorrectionLevel, dataCodewords, msk) {
99
+ this.version = version;
100
+ this.errorCorrectionLevel = errorCorrectionLevel;
101
+ // The modules of this QR Code (false = light, true = dark).
102
+ // Immutable after constructor finishes. Accessed through getModule().
103
+ this.modules = [];
104
+ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
105
+ this.isFunction = [];
106
+ // Check scalar arguments
107
+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
108
+ throw new RangeError("Version value out of range");
109
+ if (msk < -1 || msk > 7)
110
+ throw new RangeError("Mask value out of range");
111
+ this.size = version * 4 + 17;
112
+ // Initialize both grids to be size*size arrays of Boolean false
113
+ var row = [];
114
+ for (var i = 0; i < this.size; i++)
115
+ row.push(false);
116
+ for (var i = 0; i < this.size; i++) {
117
+ this.modules.push(row.slice()); // Initially all light
118
+ this.isFunction.push(row.slice());
136
119
  }
137
- /*-- Static factory functions (high level) --*/
138
- // Returns a QR Code representing the given Unicode text string at the given error correction level.
139
- // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
140
- // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
141
- // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
142
- // ecl argument if it can be done without increasing the version.
143
- QrCode.encodeText = function (text, ecl) {
144
- var segs = qrcodegen.QrSegment.makeSegments(text);
145
- return QrCode.encodeSegments(segs, ecl);
146
- };
147
- // Returns a QR Code representing the given binary data at the given error correction level.
148
- // This function always encodes using the binary segment mode, not any text mode. The maximum number of
149
- // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
150
- // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
151
- QrCode.encodeBinary = function (data, ecl) {
152
- var seg = qrcodegen.QrSegment.makeBytes(data);
153
- return QrCode.encodeSegments([seg], ecl);
154
- };
155
- /*-- Static factory functions (mid level) --*/
156
- // Returns a QR Code representing the given segments with the given encoding parameters.
157
- // The smallest possible QR Code version within the given range is automatically
158
- // chosen for the output. Iff boostEcl is true, then the ECC level of the result
159
- // may be higher than the ecl argument if it can be done without increasing the
160
- // version. The mask number is either between 0 to 7 (inclusive) to force that
161
- // mask, or -1 to automatically choose an appropriate mask (which may be slow).
162
- // This function allows the user to create a custom sequence of segments that switches
163
- // between modes (such as alphanumeric and byte) to encode text in less space.
164
- // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
165
- QrCode.encodeSegments = function (segs, ecl, minVersion, maxVersion, mask, boostEcl) {
166
- if (minVersion === void 0) { minVersion = 1; }
167
- if (maxVersion === void 0) { maxVersion = 40; }
168
- if (mask === void 0) { mask = -1; }
169
- if (boostEcl === void 0) { boostEcl = true; }
170
- if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
171
- || mask < -1 || mask > 7)
172
- throw new RangeError("Invalid value");
173
- // Find the minimal version number to use
174
- var version;
175
- var dataUsedBits;
176
- for (version = minVersion;; version++) {
177
- var dataCapacityBits_1 = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
178
- var usedBits = QrSegment.getTotalBits(segs, version);
179
- if (usedBits <= dataCapacityBits_1) {
180
- dataUsedBits = usedBits;
181
- break; // This version number is found to be suitable
182
- }
183
- if (version >= maxVersion) // All versions in the range could not fit the given data
184
- throw new RangeError("Data too long");
185
- }
186
- // Increase the error correction level while the data still fits in the current version number
187
- for (var _i = 0, _a = [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]; _i < _a.length; _i++) { // From low to high
188
- var newEcl = _a[_i];
189
- if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
190
- ecl = newEcl;
191
- }
192
- // Concatenate all segments to create the data bit string
193
- var bb = [];
194
- for (var _b = 0, segs_1 = segs; _b < segs_1.length; _b++) {
195
- var seg = segs_1[_b];
196
- appendBits(seg.mode.modeBits, 4, bb);
197
- appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
198
- for (var _c = 0, _d = seg.getData(); _c < _d.length; _c++) {
199
- var b = _d[_c];
200
- bb.push(b);
201
- }
202
- }
203
- assert(bb.length == dataUsedBits);
204
- // Add terminator and pad up to a byte if applicable
205
- var dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
206
- assert(bb.length <= dataCapacityBits);
207
- appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
208
- appendBits(0, (8 - bb.length % 8) % 8, bb);
209
- assert(bb.length % 8 == 0);
210
- // Pad with alternating bytes until data capacity is reached
211
- for (var padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
212
- appendBits(padByte, 8, bb);
213
- // Pack bits into bytes in big endian
214
- var dataCodewords = [];
215
- while (dataCodewords.length * 8 < bb.length)
216
- dataCodewords.push(0);
217
- bb.forEach(function (b, i) {
218
- return dataCodewords[i >>> 3] |= b << (7 - (i & 7));
219
- });
220
- // Create the QR Code object
221
- return new QrCode(version, ecl, dataCodewords, mask);
222
- };
223
- /*-- Accessor methods --*/
224
- // Returns the color of the module (pixel) at the given coordinates, which is false
225
- // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
226
- // If the given coordinates are out of bounds, then false (light) is returned.
227
- QrCode.prototype.getModule = function (x, y) {
228
- return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
229
- };
230
- QrCode.prototype.getModules = function () {
231
- return this.modules;
232
- };
233
- /*-- Private helper methods for constructor: Drawing function modules --*/
234
- // Reads this object's version field, and draws and marks all function modules.
235
- QrCode.prototype.drawFunctionPatterns = function () {
236
- // Draw horizontal and vertical timing patterns
237
- for (var i = 0; i < this.size; i++) {
238
- this.setFunctionModule(6, i, i % 2 == 0);
239
- this.setFunctionModule(i, 6, i % 2 == 0);
240
- }
241
- // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
242
- this.drawFinderPattern(3, 3);
243
- this.drawFinderPattern(this.size - 4, 3);
244
- this.drawFinderPattern(3, this.size - 4);
245
- // Draw numerous alignment patterns
246
- var alignPatPos = this.getAlignmentPatternPositions();
247
- var numAlign = alignPatPos.length;
248
- for (var i = 0; i < numAlign; i++) {
249
- for (var j = 0; j < numAlign; j++) {
250
- // Don't draw on the three finder corners
251
- if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
252
- this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
253
- }
254
- }
255
- // Draw configuration data
256
- this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
257
- this.drawVersion();
258
- };
259
- // Draws two copies of the format bits (with its own error correction code)
260
- // based on the given mask and this object's error correction level field.
261
- QrCode.prototype.drawFormatBits = function (mask) {
262
- // Calculate error correction code and pack bits
263
- var data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
264
- var rem = data;
265
- for (var i = 0; i < 10; i++)
266
- rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
267
- var bits = (data << 10 | rem) ^ 0x5412; // uint15
268
- assert(bits >>> 15 == 0);
269
- // Draw first copy
270
- for (var i = 0; i <= 5; i++)
271
- this.setFunctionModule(8, i, getBit(bits, i));
272
- this.setFunctionModule(8, 7, getBit(bits, 6));
273
- this.setFunctionModule(8, 8, getBit(bits, 7));
274
- this.setFunctionModule(7, 8, getBit(bits, 8));
275
- for (var i = 9; i < 15; i++)
276
- this.setFunctionModule(14 - i, 8, getBit(bits, i));
277
- // Draw second copy
278
- for (var i = 0; i < 8; i++)
279
- this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
280
- for (var i = 8; i < 15; i++)
281
- this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
282
- this.setFunctionModule(8, this.size - 8, true); // Always dark
283
- };
284
- // Draws two copies of the version bits (with its own error correction code),
285
- // based on this object's version field, iff 7 <= version <= 40.
286
- QrCode.prototype.drawVersion = function () {
287
- if (this.version < 7)
288
- return;
289
- // Calculate error correction code and pack bits
290
- var rem = this.version; // version is uint6, in the range [7, 40]
291
- for (var i = 0; i < 12; i++)
292
- rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
293
- var bits = this.version << 12 | rem; // uint18
294
- assert(bits >>> 18 == 0);
295
- // Draw two copies
296
- for (var i = 0; i < 18; i++) {
297
- var color = getBit(bits, i);
298
- var a = this.size - 11 + i % 3;
299
- var b = Math.floor(i / 3);
300
- this.setFunctionModule(a, b, color);
301
- this.setFunctionModule(b, a, color);
302
- }
303
- };
304
- // Draws a 9*9 finder pattern including the border separator,
305
- // with the center module at (x, y). Modules can be out of bounds.
306
- QrCode.prototype.drawFinderPattern = function (x, y) {
307
- for (var dy = -4; dy <= 4; dy++) {
308
- for (var dx = -4; dx <= 4; dx++) {
309
- var dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
310
- var xx = x + dx;
311
- var yy = y + dy;
312
- if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
313
- this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
120
+ // Compute ECC, draw modules
121
+ this.drawFunctionPatterns();
122
+ var allCodewords = this.addEccAndInterleave(dataCodewords);
123
+ this.drawCodewords(allCodewords);
124
+ // Do masking
125
+ if (msk == -1) { // Automatically choose best mask
126
+ var minPenalty = 1000000000;
127
+ for (var i = 0; i < 8; i++) {
128
+ this.applyMask(i);
129
+ this.drawFormatBits(i);
130
+ var penalty = this.getPenaltyScore();
131
+ if (penalty < minPenalty) {
132
+ msk = i;
133
+ minPenalty = penalty;
314
134
  }
135
+ this.applyMask(i); // Undoes the mask due to XOR
315
136
  }
316
- };
317
- // Draws a 5*5 alignment pattern, with the center module
318
- // at (x, y). All modules must be in bounds.
319
- QrCode.prototype.drawAlignmentPattern = function (x, y) {
320
- for (var dy = -2; dy <= 2; dy++) {
321
- for (var dx = -2; dx <= 2; dx++)
322
- this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
137
+ }
138
+ assert(0 <= msk && msk <= 7);
139
+ this.mask = msk;
140
+ this.applyMask(msk); // Apply the final choice of mask
141
+ this.drawFormatBits(msk); // Overwrite old format bits
142
+ this.isFunction = [];
143
+ }
144
+ /*-- Static factory functions (high level) --*/
145
+ // Returns a QR Code representing the given Unicode text string at the given error correction level.
146
+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
147
+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
148
+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
149
+ // ecl argument if it can be done without increasing the version.
150
+ QrCode.encodeText = function (text, ecl) {
151
+ var segs = qrcodegen.QrSegment.makeSegments(text);
152
+ return QrCode.encodeSegments(segs, ecl);
153
+ };
154
+ // Returns a QR Code representing the given binary data at the given error correction level.
155
+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of
156
+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
157
+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
158
+ QrCode.encodeBinary = function (data, ecl) {
159
+ var seg = qrcodegen.QrSegment.makeBytes(data);
160
+ return QrCode.encodeSegments([seg], ecl);
161
+ };
162
+ /*-- Static factory functions (mid level) --*/
163
+ // Returns a QR Code representing the given segments with the given encoding parameters.
164
+ // The smallest possible QR Code version within the given range is automatically
165
+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result
166
+ // may be higher than the ecl argument if it can be done without increasing the
167
+ // version. The mask number is either between 0 to 7 (inclusive) to force that
168
+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).
169
+ // This function allows the user to create a custom sequence of segments that switches
170
+ // between modes (such as alphanumeric and byte) to encode text in less space.
171
+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
172
+ QrCode.encodeSegments = function (segs, ecl, minVersion, maxVersion, mask, boostEcl) {
173
+ if (minVersion === void 0) { minVersion = 1; }
174
+ if (maxVersion === void 0) { maxVersion = 40; }
175
+ if (mask === void 0) { mask = -1; }
176
+ if (boostEcl === void 0) { boostEcl = true; }
177
+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
178
+ || mask < -1 || mask > 7)
179
+ throw new RangeError("Invalid value");
180
+ // Find the minimal version number to use
181
+ var version;
182
+ var dataUsedBits;
183
+ for (version = minVersion;; version++) {
184
+ var dataCapacityBits_1 = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
185
+ var usedBits = QrSegment.getTotalBits(segs, version);
186
+ if (usedBits <= dataCapacityBits_1) {
187
+ dataUsedBits = usedBits;
188
+ break; // This version number is found to be suitable
323
189
  }
324
- };
325
- // Sets the color of a module and marks it as a function module.
326
- // Only used by the constructor. Coordinates must be in bounds.
327
- QrCode.prototype.setFunctionModule = function (x, y, isDark) {
328
- this.modules[y][x] = isDark;
329
- this.isFunction[y][x] = true;
330
- };
331
- /*-- Private helper methods for constructor: Codewords and masking --*/
332
- // Returns a new byte string representing the given data with the appropriate error correction
333
- // codewords appended to it, based on this object's version and error correction level.
334
- QrCode.prototype.addEccAndInterleave = function (data) {
335
- var ver = this.version;
336
- var ecl = this.errorCorrectionLevel;
337
- if (data.length != QrCode.getNumDataCodewords(ver, ecl))
338
- throw new RangeError("Invalid argument");
339
- // Calculate parameter numbers
340
- var numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
341
- var blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
342
- var rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
343
- var numShortBlocks = numBlocks - rawCodewords % numBlocks;
344
- var shortBlockLen = Math.floor(rawCodewords / numBlocks);
345
- // Split data into blocks and append ECC to each block
346
- var blocks = [];
347
- var rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
348
- for (var i = 0, k = 0; i < numBlocks; i++) {
349
- var dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
350
- k += dat.length;
351
- var ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
352
- if (i < numShortBlocks)
353
- dat.push(0);
354
- blocks.push(dat.concat(ecc));
190
+ if (version >= maxVersion) // All versions in the range could not fit the given data
191
+ throw new RangeError("Data too long");
192
+ }
193
+ // Increase the error correction level while the data still fits in the current version number
194
+ for (var _i = 0, _a = [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]; _i < _a.length; _i++) { // From low to high
195
+ var newEcl = _a[_i];
196
+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
197
+ ecl = newEcl;
198
+ }
199
+ // Concatenate all segments to create the data bit string
200
+ var bb = [];
201
+ for (var _b = 0, segs_1 = segs; _b < segs_1.length; _b++) {
202
+ var seg = segs_1[_b];
203
+ appendBits(seg.mode.modeBits, 4, bb);
204
+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
205
+ for (var _c = 0, _d = seg.getData(); _c < _d.length; _c++) {
206
+ var b = _d[_c];
207
+ bb.push(b);
355
208
  }
356
- // Interleave (not concatenate) the bytes from every block into a single sequence
357
- var result = [];
358
- var _loop_1 = function (i) {
359
- blocks.forEach(function (block, j) {
360
- // Skip the padding byte in short blocks
361
- if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
362
- result.push(block[i]);
363
- });
364
- };
365
- for (var i = 0; i < blocks[0].length; i++) {
366
- _loop_1(i);
209
+ }
210
+ assert(bb.length == dataUsedBits);
211
+ // Add terminator and pad up to a byte if applicable
212
+ var dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
213
+ assert(bb.length <= dataCapacityBits);
214
+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
215
+ appendBits(0, (8 - bb.length % 8) % 8, bb);
216
+ assert(bb.length % 8 == 0);
217
+ // Pad with alternating bytes until data capacity is reached
218
+ for (var padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
219
+ appendBits(padByte, 8, bb);
220
+ // Pack bits into bytes in big endian
221
+ var dataCodewords = [];
222
+ while (dataCodewords.length * 8 < bb.length)
223
+ dataCodewords.push(0);
224
+ bb.forEach(function (b, i) {
225
+ return dataCodewords[i >>> 3] |= b << (7 - (i & 7));
226
+ });
227
+ // Create the QR Code object
228
+ return new QrCode(version, ecl, dataCodewords, mask);
229
+ };
230
+ /*-- Accessor methods --*/
231
+ // Returns the color of the module (pixel) at the given coordinates, which is false
232
+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
233
+ // If the given coordinates are out of bounds, then false (light) is returned.
234
+ QrCode.prototype.getModule = function (x, y) {
235
+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
236
+ };
237
+ QrCode.prototype.getModules = function () {
238
+ return this.modules;
239
+ };
240
+ /*-- Private helper methods for constructor: Drawing function modules --*/
241
+ // Reads this object's version field, and draws and marks all function modules.
242
+ QrCode.prototype.drawFunctionPatterns = function () {
243
+ // Draw horizontal and vertical timing patterns
244
+ for (var i = 0; i < this.size; i++) {
245
+ this.setFunctionModule(6, i, i % 2 == 0);
246
+ this.setFunctionModule(i, 6, i % 2 == 0);
247
+ }
248
+ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
249
+ this.drawFinderPattern(3, 3);
250
+ this.drawFinderPattern(this.size - 4, 3);
251
+ this.drawFinderPattern(3, this.size - 4);
252
+ // Draw numerous alignment patterns
253
+ var alignPatPos = this.getAlignmentPatternPositions();
254
+ var numAlign = alignPatPos.length;
255
+ for (var i = 0; i < numAlign; i++) {
256
+ for (var j = 0; j < numAlign; j++) {
257
+ // Don't draw on the three finder corners
258
+ if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
259
+ this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
367
260
  }
368
- assert(result.length == rawCodewords);
369
- return result;
370
- };
371
- // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
372
- // data area of this QR Code. Function modules need to be marked off before this is called.
373
- QrCode.prototype.drawCodewords = function (data) {
374
- if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
375
- throw new RangeError("Invalid argument");
376
- var i = 0; // Bit index into the data
377
- // Do the funny zigzag scan
378
- for (var right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
379
- if (right == 6)
380
- right = 5;
381
- for (var vert = 0; vert < this.size; vert++) { // Vertical counter
382
- for (var j = 0; j < 2; j++) {
383
- var x = right - j; // Actual x coordinate
384
- var upward = ((right + 1) & 2) == 0;
385
- var y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
386
- if (!this.isFunction[y][x] && i < data.length * 8) {
387
- this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
388
- i++;
389
- }
390
- // If this QR Code has any remainder bits (0 to 7), they were assigned as
391
- // 0/false/light by the constructor and are left unchanged by this method
392
- }
393
- }
261
+ }
262
+ // Draw configuration data
263
+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
264
+ this.drawVersion();
265
+ };
266
+ // Draws two copies of the format bits (with its own error correction code)
267
+ // based on the given mask and this object's error correction level field.
268
+ QrCode.prototype.drawFormatBits = function (mask) {
269
+ // Calculate error correction code and pack bits
270
+ var data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
271
+ var rem = data;
272
+ for (var i = 0; i < 10; i++)
273
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
274
+ var bits = (data << 10 | rem) ^ 0x5412; // uint15
275
+ assert(bits >>> 15 == 0);
276
+ // Draw first copy
277
+ for (var i = 0; i <= 5; i++)
278
+ this.setFunctionModule(8, i, getBit(bits, i));
279
+ this.setFunctionModule(8, 7, getBit(bits, 6));
280
+ this.setFunctionModule(8, 8, getBit(bits, 7));
281
+ this.setFunctionModule(7, 8, getBit(bits, 8));
282
+ for (var i = 9; i < 15; i++)
283
+ this.setFunctionModule(14 - i, 8, getBit(bits, i));
284
+ // Draw second copy
285
+ for (var i = 0; i < 8; i++)
286
+ this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
287
+ for (var i = 8; i < 15; i++)
288
+ this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
289
+ this.setFunctionModule(8, this.size - 8, true); // Always dark
290
+ };
291
+ // Draws two copies of the version bits (with its own error correction code),
292
+ // based on this object's version field, iff 7 <= version <= 40.
293
+ QrCode.prototype.drawVersion = function () {
294
+ if (this.version < 7)
295
+ return;
296
+ // Calculate error correction code and pack bits
297
+ var rem = this.version; // version is uint6, in the range [7, 40]
298
+ for (var i = 0; i < 12; i++)
299
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
300
+ var bits = this.version << 12 | rem; // uint18
301
+ assert(bits >>> 18 == 0);
302
+ // Draw two copies
303
+ for (var i = 0; i < 18; i++) {
304
+ var color = getBit(bits, i);
305
+ var a = this.size - 11 + i % 3;
306
+ var b = Math.floor(i / 3);
307
+ this.setFunctionModule(a, b, color);
308
+ this.setFunctionModule(b, a, color);
309
+ }
310
+ };
311
+ // Draws a 9*9 finder pattern including the border separator,
312
+ // with the center module at (x, y). Modules can be out of bounds.
313
+ QrCode.prototype.drawFinderPattern = function (x, y) {
314
+ for (var dy = -4; dy <= 4; dy++) {
315
+ for (var dx = -4; dx <= 4; dx++) {
316
+ var dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
317
+ var xx = x + dx;
318
+ var yy = y + dy;
319
+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
320
+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
394
321
  }
395
- assert(i == data.length * 8);
322
+ }
323
+ };
324
+ // Draws a 5*5 alignment pattern, with the center module
325
+ // at (x, y). All modules must be in bounds.
326
+ QrCode.prototype.drawAlignmentPattern = function (x, y) {
327
+ for (var dy = -2; dy <= 2; dy++) {
328
+ for (var dx = -2; dx <= 2; dx++)
329
+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
330
+ }
331
+ };
332
+ // Sets the color of a module and marks it as a function module.
333
+ // Only used by the constructor. Coordinates must be in bounds.
334
+ QrCode.prototype.setFunctionModule = function (x, y, isDark) {
335
+ this.modules[y][x] = isDark;
336
+ this.isFunction[y][x] = true;
337
+ };
338
+ /*-- Private helper methods for constructor: Codewords and masking --*/
339
+ // Returns a new byte string representing the given data with the appropriate error correction
340
+ // codewords appended to it, based on this object's version and error correction level.
341
+ QrCode.prototype.addEccAndInterleave = function (data) {
342
+ var ver = this.version;
343
+ var ecl = this.errorCorrectionLevel;
344
+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))
345
+ throw new RangeError("Invalid argument");
346
+ // Calculate parameter numbers
347
+ var numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
348
+ var blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
349
+ var rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
350
+ var numShortBlocks = numBlocks - rawCodewords % numBlocks;
351
+ var shortBlockLen = Math.floor(rawCodewords / numBlocks);
352
+ // Split data into blocks and append ECC to each block
353
+ var blocks = [];
354
+ var rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
355
+ for (var i = 0, k = 0; i < numBlocks; i++) {
356
+ var dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
357
+ k += dat.length;
358
+ var ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
359
+ if (i < numShortBlocks)
360
+ dat.push(0);
361
+ blocks.push(dat.concat(ecc));
362
+ }
363
+ // Interleave (not concatenate) the bytes from every block into a single sequence
364
+ var result = [];
365
+ var _loop_1 = function (i) {
366
+ blocks.forEach(function (block, j) {
367
+ // Skip the padding byte in short blocks
368
+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
369
+ result.push(block[i]);
370
+ });
396
371
  };
397
- // XORs the codeword modules in this QR Code with the given mask pattern.
398
- // The function modules must be marked and the codeword bits must be drawn
399
- // before masking. Due to the arithmetic of XOR, calling applyMask() with
400
- // the same mask value a second time will undo the mask. A final well-formed
401
- // QR Code needs exactly one (not zero, two, etc.) mask applied.
402
- QrCode.prototype.applyMask = function (mask) {
403
- if (mask < 0 || mask > 7)
404
- throw new RangeError("Mask value out of range");
405
- for (var y = 0; y < this.size; y++) {
406
- for (var x = 0; x < this.size; x++) {
407
- var invert = void 0;
408
- switch (mask) {
409
- case 0:
410
- invert = (x + y) % 2 == 0;
411
- break;
412
- case 1:
413
- invert = y % 2 == 0;
414
- break;
415
- case 2:
416
- invert = x % 3 == 0;
417
- break;
418
- case 3:
419
- invert = (x + y) % 3 == 0;
420
- break;
421
- case 4:
422
- invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
423
- break;
424
- case 5:
425
- invert = x * y % 2 + x * y % 3 == 0;
426
- break;
427
- case 6:
428
- invert = (x * y % 2 + x * y % 3) % 2 == 0;
429
- break;
430
- case 7:
431
- invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
432
- break;
433
- default: throw new Error("Unreachable");
372
+ for (var i = 0; i < blocks[0].length; i++) {
373
+ _loop_1(i);
374
+ }
375
+ assert(result.length == rawCodewords);
376
+ return result;
377
+ };
378
+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
379
+ // data area of this QR Code. Function modules need to be marked off before this is called.
380
+ QrCode.prototype.drawCodewords = function (data) {
381
+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
382
+ throw new RangeError("Invalid argument");
383
+ var i = 0; // Bit index into the data
384
+ // Do the funny zigzag scan
385
+ for (var right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
386
+ if (right == 6)
387
+ right = 5;
388
+ for (var vert = 0; vert < this.size; vert++) { // Vertical counter
389
+ for (var j = 0; j < 2; j++) {
390
+ var x = right - j; // Actual x coordinate
391
+ var upward = ((right + 1) & 2) == 0;
392
+ var y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
393
+ if (!this.isFunction[y][x] && i < data.length * 8) {
394
+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
395
+ i++;
434
396
  }
435
- if (!this.isFunction[y][x] && invert)
436
- this.modules[y][x] = !this.modules[y][x];
397
+ // If this QR Code has any remainder bits (0 to 7), they were assigned as
398
+ // 0/false/light by the constructor and are left unchanged by this method
437
399
  }
438
400
  }
439
- };
440
- // Calculates and returns the penalty score based on state of this QR Code's current modules.
441
- // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
442
- QrCode.prototype.getPenaltyScore = function () {
443
- var result = 0;
444
- // Adjacent modules in row having same color, and finder-like patterns
445
- for (var y = 0; y < this.size; y++) {
446
- var runColor = false;
447
- var runX = 0;
448
- var runHistory = [0, 0, 0, 0, 0, 0, 0];
449
- for (var x = 0; x < this.size; x++) {
450
- if (this.modules[y][x] == runColor) {
451
- runX++;
452
- if (runX == 5)
453
- result += QrCode.PENALTY_N1;
454
- else if (runX > 5)
455
- result++;
456
- }
457
- else {
458
- this.finderPenaltyAddHistory(runX, runHistory);
459
- if (!runColor)
460
- result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
461
- runColor = this.modules[y][x];
462
- runX = 1;
463
- }
401
+ }
402
+ assert(i == data.length * 8);
403
+ };
404
+ // XORs the codeword modules in this QR Code with the given mask pattern.
405
+ // The function modules must be marked and the codeword bits must be drawn
406
+ // before masking. Due to the arithmetic of XOR, calling applyMask() with
407
+ // the same mask value a second time will undo the mask. A final well-formed
408
+ // QR Code needs exactly one (not zero, two, etc.) mask applied.
409
+ QrCode.prototype.applyMask = function (mask) {
410
+ if (mask < 0 || mask > 7)
411
+ throw new RangeError("Mask value out of range");
412
+ for (var y = 0; y < this.size; y++) {
413
+ for (var x = 0; x < this.size; x++) {
414
+ var invert = void 0;
415
+ switch (mask) {
416
+ case 0:
417
+ invert = (x + y) % 2 == 0;
418
+ break;
419
+ case 1:
420
+ invert = y % 2 == 0;
421
+ break;
422
+ case 2:
423
+ invert = x % 3 == 0;
424
+ break;
425
+ case 3:
426
+ invert = (x + y) % 3 == 0;
427
+ break;
428
+ case 4:
429
+ invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
430
+ break;
431
+ case 5:
432
+ invert = x * y % 2 + x * y % 3 == 0;
433
+ break;
434
+ case 6:
435
+ invert = (x * y % 2 + x * y % 3) % 2 == 0;
436
+ break;
437
+ case 7:
438
+ invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
439
+ break;
440
+ default: throw new Error("Unreachable");
464
441
  }
465
- result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
442
+ if (!this.isFunction[y][x] && invert)
443
+ this.modules[y][x] = !this.modules[y][x];
466
444
  }
467
- // Adjacent modules in column having same color, and finder-like patterns
445
+ }
446
+ };
447
+ // Calculates and returns the penalty score based on state of this QR Code's current modules.
448
+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
449
+ QrCode.prototype.getPenaltyScore = function () {
450
+ var result = 0;
451
+ // Adjacent modules in row having same color, and finder-like patterns
452
+ for (var y = 0; y < this.size; y++) {
453
+ var runColor = false;
454
+ var runX = 0;
455
+ var runHistory = [0, 0, 0, 0, 0, 0, 0];
468
456
  for (var x = 0; x < this.size; x++) {
469
- var runColor = false;
470
- var runY = 0;
471
- var runHistory = [0, 0, 0, 0, 0, 0, 0];
472
- for (var y = 0; y < this.size; y++) {
473
- if (this.modules[y][x] == runColor) {
474
- runY++;
475
- if (runY == 5)
476
- result += QrCode.PENALTY_N1;
477
- else if (runY > 5)
478
- result++;
479
- }
480
- else {
481
- this.finderPenaltyAddHistory(runY, runHistory);
482
- if (!runColor)
483
- result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
484
- runColor = this.modules[y][x];
485
- runY = 1;
486
- }
457
+ if (this.modules[y][x] == runColor) {
458
+ runX++;
459
+ if (runX == 5)
460
+ result += QrCode.PENALTY_N1;
461
+ else if (runX > 5)
462
+ result++;
487
463
  }
488
- result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
489
- }
490
- // 2*2 blocks of modules having same color
491
- for (var y = 0; y < this.size - 1; y++) {
492
- for (var x = 0; x < this.size - 1; x++) {
493
- var color = this.modules[y][x];
494
- if (color == this.modules[y][x + 1] &&
495
- color == this.modules[y + 1][x] &&
496
- color == this.modules[y + 1][x + 1])
497
- result += QrCode.PENALTY_N2;
464
+ else {
465
+ this.finderPenaltyAddHistory(runX, runHistory);
466
+ if (!runColor)
467
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
468
+ runColor = this.modules[y][x];
469
+ runX = 1;
498
470
  }
499
471
  }
500
- // Balance of dark and light modules
501
- var dark = 0;
502
- for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
503
- var row = _a[_i];
504
- dark = row.reduce(function (sum, color) { return sum + (color ? 1 : 0); }, dark);
505
- }
506
- var total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
507
- // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
508
- var k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
509
- assert(0 <= k && k <= 9);
510
- result += k * QrCode.PENALTY_N4;
511
- assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
512
- return result;
513
- };
514
- /*-- Private helper functions --*/
515
- // Returns an ascending list of positions of alignment patterns for this version number.
516
- // Each position is in the range [0,177), and are used on both the x and y axes.
517
- // This could be implemented as lookup table of 40 variable-length lists of integers.
518
- QrCode.prototype.getAlignmentPatternPositions = function () {
519
- if (this.version == 1)
520
- return [];
521
- else {
522
- var numAlign = Math.floor(this.version / 7) + 2;
523
- var step = (this.version == 32) ? 26 :
524
- Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
525
- var result = [6];
526
- for (var pos = this.size - 7; result.length < numAlign; pos -= step)
527
- result.splice(1, 0, pos);
528
- return result;
529
- }
530
- };
531
- // Returns the number of data bits that can be stored in a QR Code of the given version number, after
532
- // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
533
- // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
534
- QrCode.getNumRawDataModules = function (ver) {
535
- if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
536
- throw new RangeError("Version number out of range");
537
- var result = (16 * ver + 128) * ver + 64;
538
- if (ver >= 2) {
539
- var numAlign = Math.floor(ver / 7) + 2;
540
- result -= (25 * numAlign - 10) * numAlign - 55;
541
- if (ver >= 7)
542
- result -= 36;
543
- }
544
- assert(208 <= result && result <= 29648);
545
- return result;
546
- };
547
- // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
548
- // QR Code of the given version number and error correction level, with remainder bits discarded.
549
- // This stateless pure function could be implemented as a (40*4)-cell lookup table.
550
- QrCode.getNumDataCodewords = function (ver, ecl) {
551
- return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
552
- QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
553
- QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
554
- };
555
- // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
556
- // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
557
- QrCode.reedSolomonComputeDivisor = function (degree) {
558
- if (degree < 1 || degree > 255)
559
- throw new RangeError("Degree out of range");
560
- // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
561
- // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
562
- var result = [];
563
- for (var i = 0; i < degree - 1; i++)
564
- result.push(0);
565
- result.push(1); // Start off with the monomial x^0
566
- // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
567
- // and drop the highest monomial term which is always 1x^degree.
568
- // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
569
- var root = 1;
570
- for (var i = 0; i < degree; i++) {
571
- // Multiply the current product by (x - r^i)
572
- for (var j = 0; j < result.length; j++) {
573
- result[j] = QrCode.reedSolomonMultiply(result[j], root);
574
- if (j + 1 < result.length)
575
- result[j] ^= result[j + 1];
472
+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
473
+ }
474
+ // Adjacent modules in column having same color, and finder-like patterns
475
+ for (var x = 0; x < this.size; x++) {
476
+ var runColor = false;
477
+ var runY = 0;
478
+ var runHistory = [0, 0, 0, 0, 0, 0, 0];
479
+ for (var y = 0; y < this.size; y++) {
480
+ if (this.modules[y][x] == runColor) {
481
+ runY++;
482
+ if (runY == 5)
483
+ result += QrCode.PENALTY_N1;
484
+ else if (runY > 5)
485
+ result++;
486
+ }
487
+ else {
488
+ this.finderPenaltyAddHistory(runY, runHistory);
489
+ if (!runColor)
490
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
491
+ runColor = this.modules[y][x];
492
+ runY = 1;
576
493
  }
577
- root = QrCode.reedSolomonMultiply(root, 0x02);
578
494
  }
579
- return result;
580
- };
581
- // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
582
- QrCode.reedSolomonComputeRemainder = function (data, divisor) {
583
- var result = divisor.map(function (_) { return 0; });
584
- var _loop_2 = function (b) {
585
- var factor = b ^ result.shift();
586
- result.push(0);
587
- divisor.forEach(function (coef, i) {
588
- return result[i] ^= QrCode.reedSolomonMultiply(coef, factor);
589
- });
590
- };
591
- for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
592
- var b = data_1[_i];
593
- _loop_2(b);
495
+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
496
+ }
497
+ // 2*2 blocks of modules having same color
498
+ for (var y = 0; y < this.size - 1; y++) {
499
+ for (var x = 0; x < this.size - 1; x++) {
500
+ var color = this.modules[y][x];
501
+ if (color == this.modules[y][x + 1] &&
502
+ color == this.modules[y + 1][x] &&
503
+ color == this.modules[y + 1][x + 1])
504
+ result += QrCode.PENALTY_N2;
594
505
  }
506
+ }
507
+ // Balance of dark and light modules
508
+ var dark = 0;
509
+ for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
510
+ var row = _a[_i];
511
+ dark = row.reduce(function (sum, color) { return sum + (color ? 1 : 0); }, dark);
512
+ }
513
+ var total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
514
+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
515
+ var k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
516
+ assert(0 <= k && k <= 9);
517
+ result += k * QrCode.PENALTY_N4;
518
+ assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
519
+ return result;
520
+ };
521
+ /*-- Private helper functions --*/
522
+ // Returns an ascending list of positions of alignment patterns for this version number.
523
+ // Each position is in the range [0,177), and are used on both the x and y axes.
524
+ // This could be implemented as lookup table of 40 variable-length lists of integers.
525
+ QrCode.prototype.getAlignmentPatternPositions = function () {
526
+ if (this.version == 1)
527
+ return [];
528
+ else {
529
+ var numAlign = Math.floor(this.version / 7) + 2;
530
+ var step = Math.floor((this.version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4)) * 2;
531
+ var result = [6];
532
+ for (var pos = this.size - 7; result.length < numAlign; pos -= step)
533
+ result.splice(1, 0, pos);
595
534
  return result;
596
- };
597
- // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
598
- // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
599
- QrCode.reedSolomonMultiply = function (x, y) {
600
- if (x >>> 8 != 0 || y >>> 8 != 0)
601
- throw new RangeError("Byte out of range");
602
- // Russian peasant multiplication
603
- var z = 0;
604
- for (var i = 7; i >= 0; i--) {
605
- z = (z << 1) ^ ((z >>> 7) * 0x11D);
606
- z ^= ((y >>> i) & 1) * x;
535
+ }
536
+ };
537
+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after
538
+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
539
+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
540
+ QrCode.getNumRawDataModules = function (ver) {
541
+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
542
+ throw new RangeError("Version number out of range");
543
+ var result = (16 * ver + 128) * ver + 64;
544
+ if (ver >= 2) {
545
+ var numAlign = Math.floor(ver / 7) + 2;
546
+ result -= (25 * numAlign - 10) * numAlign - 55;
547
+ if (ver >= 7)
548
+ result -= 36;
549
+ }
550
+ assert(208 <= result && result <= 29648);
551
+ return result;
552
+ };
553
+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
554
+ // QR Code of the given version number and error correction level, with remainder bits discarded.
555
+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.
556
+ QrCode.getNumDataCodewords = function (ver, ecl) {
557
+ return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
558
+ QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
559
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
560
+ };
561
+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
562
+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
563
+ QrCode.reedSolomonComputeDivisor = function (degree) {
564
+ if (degree < 1 || degree > 255)
565
+ throw new RangeError("Degree out of range");
566
+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
567
+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
568
+ var result = [];
569
+ for (var i = 0; i < degree - 1; i++)
570
+ result.push(0);
571
+ result.push(1); // Start off with the monomial x^0
572
+ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
573
+ // and drop the highest monomial term which is always 1x^degree.
574
+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
575
+ var root = 1;
576
+ for (var i = 0; i < degree; i++) {
577
+ // Multiply the current product by (x - r^i)
578
+ for (var j = 0; j < result.length; j++) {
579
+ result[j] = QrCode.reedSolomonMultiply(result[j], root);
580
+ if (j + 1 < result.length)
581
+ result[j] ^= result[j + 1];
607
582
  }
608
- assert(z >>> 8 == 0);
609
- return z;
610
- };
611
- // Can only be called immediately after a light run is added, and
612
- // returns either 0, 1, or 2. A helper function for getPenaltyScore().
613
- QrCode.prototype.finderPenaltyCountPatterns = function (runHistory) {
614
- var n = runHistory[1];
615
- assert(n <= this.size * 3);
616
- var core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
617
- return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
618
- + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
583
+ root = QrCode.reedSolomonMultiply(root, 0x02);
584
+ }
585
+ return result;
586
+ };
587
+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
588
+ QrCode.reedSolomonComputeRemainder = function (data, divisor) {
589
+ var result = divisor.map(function (_) { return 0; });
590
+ var _loop_2 = function (b) {
591
+ var factor = b ^ result.shift();
592
+ result.push(0);
593
+ divisor.forEach(function (coef, i) {
594
+ return result[i] ^= QrCode.reedSolomonMultiply(coef, factor);
595
+ });
619
596
  };
620
- // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
621
- QrCode.prototype.finderPenaltyTerminateAndCount = function (currentRunColor, currentRunLength, runHistory) {
622
- if (currentRunColor) { // Terminate dark run
623
- this.finderPenaltyAddHistory(currentRunLength, runHistory);
624
- currentRunLength = 0;
625
- }
626
- currentRunLength += this.size; // Add light border to final run
597
+ for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
598
+ var b = data_1[_i];
599
+ _loop_2(b);
600
+ }
601
+ return result;
602
+ };
603
+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
604
+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
605
+ QrCode.reedSolomonMultiply = function (x, y) {
606
+ if (x >>> 8 != 0 || y >>> 8 != 0)
607
+ throw new RangeError("Byte out of range");
608
+ // Russian peasant multiplication
609
+ var z = 0;
610
+ for (var i = 7; i >= 0; i--) {
611
+ z = (z << 1) ^ ((z >>> 7) * 0x11D);
612
+ z ^= ((y >>> i) & 1) * x;
613
+ }
614
+ assert(z >>> 8 == 0);
615
+ return z;
616
+ };
617
+ // Can only be called immediately after a light run is added, and
618
+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().
619
+ QrCode.prototype.finderPenaltyCountPatterns = function (runHistory) {
620
+ var n = runHistory[1];
621
+ assert(n <= this.size * 3);
622
+ var core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
623
+ return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
624
+ + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
625
+ };
626
+ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
627
+ QrCode.prototype.finderPenaltyTerminateAndCount = function (currentRunColor, currentRunLength, runHistory) {
628
+ if (currentRunColor) { // Terminate dark run
627
629
  this.finderPenaltyAddHistory(currentRunLength, runHistory);
628
- return this.finderPenaltyCountPatterns(runHistory);
629
- };
630
- // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
631
- QrCode.prototype.finderPenaltyAddHistory = function (currentRunLength, runHistory) {
632
- if (runHistory[0] == 0)
633
- currentRunLength += this.size; // Add light border to initial run
634
- runHistory.pop();
635
- runHistory.unshift(currentRunLength);
636
- };
637
- /*-- Constants and tables --*/
638
- // The minimum version number supported in the QR Code Model 2 standard.
639
- QrCode.MIN_VERSION = 1;
640
- // The maximum version number supported in the QR Code Model 2 standard.
641
- QrCode.MAX_VERSION = 40;
642
- // For use in getPenaltyScore(), when evaluating which mask is best.
643
- QrCode.PENALTY_N1 = 3;
644
- QrCode.PENALTY_N2 = 3;
645
- QrCode.PENALTY_N3 = 40;
646
- QrCode.PENALTY_N4 = 10;
647
- QrCode.ECC_CODEWORDS_PER_BLOCK = [
648
- // Version: (note that index 0 is for padding, and is set to an illegal value)
649
- //0, 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 Error correction level
650
- [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
651
- [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
652
- [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
653
- [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
654
- ];
655
- QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
656
- // Version: (note that index 0 is for padding, and is set to an illegal value)
657
- //0, 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 Error correction level
658
- [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
659
- [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
660
- [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
661
- [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
662
- ];
663
- return QrCode;
664
- }());
665
- qrcodegen.QrCode = QrCode;
666
- // Appends the given number of low-order bits of the given value
667
- // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
668
- function appendBits(val, len, bb) {
669
- if (len < 0 || len > 31 || val >>> len != 0)
670
- throw new RangeError("Value out of range");
671
- for (var i = len - 1; i >= 0; i--) // Append bit by bit
672
- bb.push((val >>> i) & 1);
673
- }
674
- // Returns true iff the i'th bit of x is set to 1.
675
- function getBit(x, i) {
676
- return ((x >>> i) & 1) != 0;
677
- }
678
- // Throws an exception if the given condition is false.
679
- function assert(cond) {
680
- if (!cond)
681
- throw new Error("Assertion error");
630
+ currentRunLength = 0;
631
+ }
632
+ currentRunLength += this.size; // Add light border to final run
633
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
634
+ return this.finderPenaltyCountPatterns(runHistory);
635
+ };
636
+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
637
+ QrCode.prototype.finderPenaltyAddHistory = function (currentRunLength, runHistory) {
638
+ if (runHistory[0] == 0)
639
+ currentRunLength += this.size; // Add light border to initial run
640
+ runHistory.pop();
641
+ runHistory.unshift(currentRunLength);
642
+ };
643
+ /*-- Constants and tables --*/
644
+ // The minimum version number supported in the QR Code Model 2 standard.
645
+ QrCode.MIN_VERSION = 1;
646
+ // The maximum version number supported in the QR Code Model 2 standard.
647
+ QrCode.MAX_VERSION = 40;
648
+ // For use in getPenaltyScore(), when evaluating which mask is best.
649
+ QrCode.PENALTY_N1 = 3;
650
+ QrCode.PENALTY_N2 = 3;
651
+ QrCode.PENALTY_N3 = 40;
652
+ QrCode.PENALTY_N4 = 10;
653
+ QrCode.ECC_CODEWORDS_PER_BLOCK = [
654
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
655
+ //0, 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 Error correction level
656
+ [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low
657
+ [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium
658
+ [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile
659
+ [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
660
+ ];
661
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
662
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
663
+ //0, 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 Error correction level
664
+ [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low
665
+ [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium
666
+ [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile
667
+ [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
668
+ ];
669
+ return QrCode;
670
+ }());
671
+ qrcodegen.QrCode = QrCode;
672
+ // Appends the given number of low-order bits of the given value
673
+ // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
674
+ function appendBits(val, len, bb) {
675
+ if (len < 0 || len > 31 || val >>> len != 0)
676
+ throw new RangeError("Value out of range");
677
+ for (var i = len - 1; i >= 0; i--) // Append bit by bit
678
+ bb.push((val >>> i) & 1);
679
+ }
680
+ // Returns true iff the i'th bit of x is set to 1.
681
+ function getBit(x, i) {
682
+ return ((x >>> i) & 1) != 0;
683
+ }
684
+ // Throws an exception if the given condition is false.
685
+ function assert(cond) {
686
+ if (!cond)
687
+ throw new Error("Assertion error");
688
+ }
689
+ /*---- Data segment class ----*/
690
+ /*
691
+ * A segment of character/binary/control data in a QR Code symbol.
692
+ * Instances of this class are immutable.
693
+ * The mid-level way to create a segment is to take the payload data
694
+ * and call a static factory function such as QrSegment.makeNumeric().
695
+ * The low-level way to create a segment is to custom-make the bit buffer
696
+ * and call the QrSegment() constructor with appropriate values.
697
+ * This segment class imposes no length restrictions, but QR Codes have restrictions.
698
+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
699
+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.
700
+ */
701
+ var QrSegment = /** @class */ (function () {
702
+ /*-- Constructor (low level) and fields --*/
703
+ // Creates a new QR Code segment with the given attributes and data.
704
+ // The character count (numChars) must agree with the mode and the bit buffer length,
705
+ // but the constraint isn't checked. The given bit buffer is cloned and stored.
706
+ function QrSegment(
707
+ // The mode indicator of this segment.
708
+ mode,
709
+ // The length of this segment's unencoded data. Measured in characters for
710
+ // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
711
+ // Always zero or positive. Not the same as the data's bit length.
712
+ numChars,
713
+ // The data bits of this segment. Accessed through getData().
714
+ bitData) {
715
+ this.mode = mode;
716
+ this.numChars = numChars;
717
+ this.bitData = bitData;
718
+ if (numChars < 0)
719
+ throw new RangeError("Invalid argument");
720
+ this.bitData = bitData.slice(); // Make defensive copy
682
721
  }
683
- /*---- Data segment class ----*/
722
+ /*-- Static factory functions (mid level) --*/
723
+ // Returns a segment representing the given binary data encoded in
724
+ // byte mode. All input byte arrays are acceptable. Any text string
725
+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.
726
+ QrSegment.makeBytes = function (data) {
727
+ var bb = [];
728
+ for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
729
+ var b = data_2[_i];
730
+ appendBits(b, 8, bb);
731
+ }
732
+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
733
+ };
734
+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.
735
+ QrSegment.makeNumeric = function (digits) {
736
+ if (!QrSegment.isNumeric(digits))
737
+ throw new RangeError("String contains non-numeric characters");
738
+ var bb = [];
739
+ for (var i = 0; i < digits.length;) { // Consume up to 3 digits per iteration
740
+ var n = Math.min(digits.length - i, 3);
741
+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
742
+ i += n;
743
+ }
744
+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
745
+ };
746
+ // Returns a segment representing the given text string encoded in alphanumeric mode.
747
+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
748
+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
749
+ QrSegment.makeAlphanumeric = function (text) {
750
+ if (!QrSegment.isAlphanumeric(text))
751
+ throw new RangeError("String contains unencodable characters in alphanumeric mode");
752
+ var bb = [];
753
+ var i;
754
+ for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
755
+ var temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
756
+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
757
+ appendBits(temp, 11, bb);
758
+ }
759
+ if (i < text.length) // 1 character remaining
760
+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
761
+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
762
+ };
763
+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
764
+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.
765
+ QrSegment.makeSegments = function (text) {
766
+ // Select the most efficient segment encoding automatically
767
+ if (text == "")
768
+ return [];
769
+ else if (QrSegment.isNumeric(text))
770
+ return [QrSegment.makeNumeric(text)];
771
+ else if (QrSegment.isAlphanumeric(text))
772
+ return [QrSegment.makeAlphanumeric(text)];
773
+ else
774
+ return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
775
+ };
776
+ // Returns a segment representing an Extended Channel Interpretation
777
+ // (ECI) designator with the given assignment value.
778
+ QrSegment.makeEci = function (assignVal) {
779
+ var bb = [];
780
+ if (assignVal < 0)
781
+ throw new RangeError("ECI assignment value out of range");
782
+ else if (assignVal < (1 << 7))
783
+ appendBits(assignVal, 8, bb);
784
+ else if (assignVal < (1 << 14)) {
785
+ appendBits(2, 2, bb);
786
+ appendBits(assignVal, 14, bb);
787
+ }
788
+ else if (assignVal < 1000000) {
789
+ appendBits(6, 3, bb);
790
+ appendBits(assignVal, 21, bb);
791
+ }
792
+ else
793
+ throw new RangeError("ECI assignment value out of range");
794
+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);
795
+ };
796
+ // Tests whether the given string can be encoded as a segment in numeric mode.
797
+ // A string is encodable iff each character is in the range 0 to 9.
798
+ QrSegment.isNumeric = function (text) {
799
+ return QrSegment.NUMERIC_REGEX.test(text);
800
+ };
801
+ // Tests whether the given string can be encoded as a segment in alphanumeric mode.
802
+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z
803
+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
804
+ QrSegment.isAlphanumeric = function (text) {
805
+ return QrSegment.ALPHANUMERIC_REGEX.test(text);
806
+ };
807
+ /*-- Methods --*/
808
+ // Returns a new copy of the data bits of this segment.
809
+ QrSegment.prototype.getData = function () {
810
+ return this.bitData.slice(); // Make defensive copy
811
+ };
812
+ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
813
+ // the given version. The result is infinity if a segment has too many characters to fit its length field.
814
+ QrSegment.getTotalBits = function (segs, version) {
815
+ var result = 0;
816
+ for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {
817
+ var seg = segs_2[_i];
818
+ var ccbits = seg.mode.numCharCountBits(version);
819
+ if (seg.numChars >= (1 << ccbits))
820
+ return Infinity; // The segment's length doesn't fit the field's bit width
821
+ result += 4 + ccbits + seg.bitData.length;
822
+ }
823
+ return result;
824
+ };
825
+ // Returns a new array of bytes representing the given string encoded in UTF-8.
826
+ QrSegment.toUtf8ByteArray = function (str) {
827
+ str = encodeURI(str);
828
+ var result = [];
829
+ for (var i = 0; i < str.length; i++) {
830
+ if (str.charAt(i) != "%")
831
+ result.push(str.charCodeAt(i));
832
+ else {
833
+ result.push(parseInt(str.substring(i + 1, i + 3), 16));
834
+ i += 2;
835
+ }
836
+ }
837
+ return result;
838
+ };
839
+ /*-- Constants --*/
840
+ // Describes precisely all strings that are encodable in numeric mode.
841
+ QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
842
+ // Describes precisely all strings that are encodable in alphanumeric mode.
843
+ QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
844
+ // The set of all legal characters in alphanumeric mode,
845
+ // where each character value maps to the index in the string.
846
+ QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
847
+ return QrSegment;
848
+ }());
849
+ qrcodegen.QrSegment = QrSegment;
850
+ })(qrcodegen || (qrcodegen = {}));
851
+ /*---- Public helper enumeration ----*/
852
+ (function (qrcodegen) {
853
+ (function (QrCode) {
684
854
  /*
685
- * A segment of character/binary/control data in a QR Code symbol.
686
- * Instances of this class are immutable.
687
- * The mid-level way to create a segment is to take the payload data
688
- * and call a static factory function such as QrSegment.makeNumeric().
689
- * The low-level way to create a segment is to custom-make the bit buffer
690
- * and call the QrSegment() constructor with appropriate values.
691
- * This segment class imposes no length restrictions, but QR Codes have restrictions.
692
- * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
693
- * Any segment longer than this is meaningless for the purpose of generating QR Codes.
855
+ * The error correction level in a QR Code symbol. Immutable.
694
856
  */
695
- var QrSegment = /** @class */ (function () {
696
- /*-- Constructor (low level) and fields --*/
697
- // Creates a new QR Code segment with the given attributes and data.
698
- // The character count (numChars) must agree with the mode and the bit buffer length,
699
- // but the constraint isn't checked. The given bit buffer is cloned and stored.
700
- function QrSegment(
701
- // The mode indicator of this segment.
702
- mode,
703
- // The length of this segment's unencoded data. Measured in characters for
704
- // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
705
- // Always zero or positive. Not the same as the data's bit length.
706
- numChars,
707
- // The data bits of this segment. Accessed through getData().
708
- bitData) {
709
- this.mode = mode;
710
- this.numChars = numChars;
711
- this.bitData = bitData;
712
- if (numChars < 0)
713
- throw new RangeError("Invalid argument");
714
- this.bitData = bitData.slice(); // Make defensive copy
857
+ var Ecc = /** @class */ (function () {
858
+ /*-- Constructor and fields --*/
859
+ function Ecc(
860
+ // In the range 0 to 3 (unsigned 2-bit integer).
861
+ ordinal,
862
+ // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
863
+ formatBits) {
864
+ this.ordinal = ordinal;
865
+ this.formatBits = formatBits;
715
866
  }
716
- /*-- Static factory functions (mid level) --*/
717
- // Returns a segment representing the given binary data encoded in
718
- // byte mode. All input byte arrays are acceptable. Any text string
719
- // can be converted to UTF-8 bytes and encoded as a byte mode segment.
720
- QrSegment.makeBytes = function (data) {
721
- var bb = [];
722
- for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
723
- var b = data_2[_i];
724
- appendBits(b, 8, bb);
725
- }
726
- return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
727
- };
728
- // Returns a segment representing the given string of decimal digits encoded in numeric mode.
729
- QrSegment.makeNumeric = function (digits) {
730
- if (!QrSegment.isNumeric(digits))
731
- throw new RangeError("String contains non-numeric characters");
732
- var bb = [];
733
- for (var i = 0; i < digits.length;) { // Consume up to 3 digits per iteration
734
- var n = Math.min(digits.length - i, 3);
735
- appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
736
- i += n;
737
- }
738
- return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
739
- };
740
- // Returns a segment representing the given text string encoded in alphanumeric mode.
741
- // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
742
- // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
743
- QrSegment.makeAlphanumeric = function (text) {
744
- if (!QrSegment.isAlphanumeric(text))
745
- throw new RangeError("String contains unencodable characters in alphanumeric mode");
746
- var bb = [];
747
- var i;
748
- for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
749
- var temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
750
- temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
751
- appendBits(temp, 11, bb);
752
- }
753
- if (i < text.length) // 1 character remaining
754
- appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
755
- return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
756
- };
757
- // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
758
- // The result may use various segment modes and switch modes to optimize the length of the bit stream.
759
- QrSegment.makeSegments = function (text) {
760
- // Select the most efficient segment encoding automatically
761
- if (text == "")
762
- return [];
763
- else if (QrSegment.isNumeric(text))
764
- return [QrSegment.makeNumeric(text)];
765
- else if (QrSegment.isAlphanumeric(text))
766
- return [QrSegment.makeAlphanumeric(text)];
767
- else
768
- return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
769
- };
770
- // Returns a segment representing an Extended Channel Interpretation
771
- // (ECI) designator with the given assignment value.
772
- QrSegment.makeEci = function (assignVal) {
773
- var bb = [];
774
- if (assignVal < 0)
775
- throw new RangeError("ECI assignment value out of range");
776
- else if (assignVal < (1 << 7))
777
- appendBits(assignVal, 8, bb);
778
- else if (assignVal < (1 << 14)) {
779
- appendBits(2, 2, bb);
780
- appendBits(assignVal, 14, bb);
781
- }
782
- else if (assignVal < 1000000) {
783
- appendBits(6, 3, bb);
784
- appendBits(assignVal, 21, bb);
785
- }
786
- else
787
- throw new RangeError("ECI assignment value out of range");
788
- return new QrSegment(QrSegment.Mode.ECI, 0, bb);
789
- };
790
- // Tests whether the given string can be encoded as a segment in numeric mode.
791
- // A string is encodable iff each character is in the range 0 to 9.
792
- QrSegment.isNumeric = function (text) {
793
- return QrSegment.NUMERIC_REGEX.test(text);
794
- };
795
- // Tests whether the given string can be encoded as a segment in alphanumeric mode.
796
- // A string is encodable iff each character is in the following set: 0 to 9, A to Z
797
- // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
798
- QrSegment.isAlphanumeric = function (text) {
799
- return QrSegment.ALPHANUMERIC_REGEX.test(text);
800
- };
801
- /*-- Methods --*/
802
- // Returns a new copy of the data bits of this segment.
803
- QrSegment.prototype.getData = function () {
804
- return this.bitData.slice(); // Make defensive copy
805
- };
806
- // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
807
- // the given version. The result is infinity if a segment has too many characters to fit its length field.
808
- QrSegment.getTotalBits = function (segs, version) {
809
- var result = 0;
810
- for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {
811
- var seg = segs_2[_i];
812
- var ccbits = seg.mode.numCharCountBits(version);
813
- if (seg.numChars >= (1 << ccbits))
814
- return Infinity; // The segment's length doesn't fit the field's bit width
815
- result += 4 + ccbits + seg.bitData.length;
816
- }
817
- return result;
818
- };
819
- // Returns a new array of bytes representing the given string encoded in UTF-8.
820
- QrSegment.toUtf8ByteArray = function (str) {
821
- str = encodeURI(str);
822
- var result = [];
823
- for (var i = 0; i < str.length; i++) {
824
- if (str.charAt(i) != "%")
825
- result.push(str.charCodeAt(i));
826
- else {
827
- result.push(parseInt(str.substring(i + 1, i + 3), 16));
828
- i += 2;
829
- }
830
- }
831
- return result;
867
+ /*-- Constants --*/
868
+ Ecc.LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
869
+ Ecc.MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
870
+ Ecc.QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
871
+ Ecc.HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
872
+ return Ecc;
873
+ }());
874
+ QrCode.Ecc = Ecc;
875
+ })(qrcodegen.QrCode || (qrcodegen.QrCode = {}));
876
+ })(qrcodegen || (qrcodegen = {}));
877
+ /*---- Public helper enumeration ----*/
878
+ (function (qrcodegen) {
879
+ (function (QrSegment) {
880
+ /*
881
+ * Describes how a segment's data bits are interpreted. Immutable.
882
+ */
883
+ var Mode = /** @class */ (function () {
884
+ /*-- Constructor and fields --*/
885
+ function Mode(
886
+ // The mode indicator bits, which is a uint4 value (range 0 to 15).
887
+ modeBits,
888
+ // Number of character count bits for three different version ranges.
889
+ numBitsCharCount) {
890
+ this.modeBits = modeBits;
891
+ this.numBitsCharCount = numBitsCharCount;
892
+ }
893
+ /*-- Method --*/
894
+ // (Package-private) Returns the bit width of the character count field for a segment in
895
+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].
896
+ Mode.prototype.numCharCountBits = function (ver) {
897
+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
832
898
  };
833
899
  /*-- Constants --*/
834
- // Describes precisely all strings that are encodable in numeric mode.
835
- QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
836
- // Describes precisely all strings that are encodable in alphanumeric mode.
837
- QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
838
- // The set of all legal characters in alphanumeric mode,
839
- // where each character value maps to the index in the string.
840
- QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
841
- return QrSegment;
900
+ Mode.NUMERIC = new Mode(0x1, [10, 12, 14]);
901
+ Mode.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
902
+ Mode.BYTE = new Mode(0x4, [8, 16, 16]);
903
+ Mode.KANJI = new Mode(0x8, [8, 10, 12]);
904
+ Mode.ECI = new Mode(0x7, [0, 0, 0]);
905
+ return Mode;
842
906
  }());
843
- qrcodegen.QrSegment = QrSegment;
844
- })(qrcodegen || (qrcodegen = {}));
845
- /*---- Public helper enumeration ----*/
846
- (function (qrcodegen) {
847
- (function (QrCode) {
848
- /*
849
- * The error correction level in a QR Code symbol. Immutable.
850
- */
851
- var Ecc = /** @class */ (function () {
852
- /*-- Constructor and fields --*/
853
- function Ecc(
854
- // In the range 0 to 3 (unsigned 2-bit integer).
855
- ordinal,
856
- // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
857
- formatBits) {
858
- this.ordinal = ordinal;
859
- this.formatBits = formatBits;
860
- }
861
- /*-- Constants --*/
862
- Ecc.LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
863
- Ecc.MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
864
- Ecc.QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
865
- Ecc.HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
866
- return Ecc;
867
- }());
868
- QrCode.Ecc = Ecc;
869
- })(qrcodegen.QrCode || (qrcodegen.QrCode = {}));
870
- })(qrcodegen || (qrcodegen = {}));
871
- /*---- Public helper enumeration ----*/
872
- (function (qrcodegen) {
873
- (function (QrSegment) {
874
- /*
875
- * Describes how a segment's data bits are interpreted. Immutable.
876
- */
877
- var Mode = /** @class */ (function () {
878
- /*-- Constructor and fields --*/
879
- function Mode(
880
- // The mode indicator bits, which is a uint4 value (range 0 to 15).
881
- modeBits,
882
- // Number of character count bits for three different version ranges.
883
- numBitsCharCount) {
884
- this.modeBits = modeBits;
885
- this.numBitsCharCount = numBitsCharCount;
886
- }
887
- /*-- Method --*/
888
- // (Package-private) Returns the bit width of the character count field for a segment in
889
- // this mode in a QR Code at the given version number. The result is in the range [0, 16].
890
- Mode.prototype.numCharCountBits = function (ver) {
891
- return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
892
- };
893
- /*-- Constants --*/
894
- Mode.NUMERIC = new Mode(0x1, [10, 12, 14]);
895
- Mode.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
896
- Mode.BYTE = new Mode(0x4, [8, 16, 16]);
897
- Mode.KANJI = new Mode(0x8, [8, 10, 12]);
898
- Mode.ECI = new Mode(0x7, [0, 0, 0]);
899
- return Mode;
900
- }());
901
- QrSegment.Mode = Mode;
902
- })(qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));
903
- })(qrcodegen || (qrcodegen = {}));
904
- var QR = qrcodegen;
907
+ QrSegment.Mode = Mode;
908
+ })(qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));
909
+ })(qrcodegen || (qrcodegen = {}));
910
+ var QR = qrcodegen;
905
911
 
906
- var defaultErrorCorrectLevel = 'H';
907
- var ErrorCorrectLevelMap = {
908
- L: QR.QrCode.Ecc.LOW,
909
- M: QR.QrCode.Ecc.MEDIUM,
910
- Q: QR.QrCode.Ecc.QUARTILE,
911
- H: QR.QrCode.Ecc.HIGH,
912
- };
913
- // Thanks the `qrcode.react`
914
- var SUPPORTS_PATH2D = (function () {
915
- try {
916
- new Path2D().addPath(new Path2D());
917
- }
918
- catch (e) {
919
- return false;
920
- }
921
- return true;
922
- })();
923
- function validErrorCorrectLevel(level) {
924
- return level in ErrorCorrectLevelMap;
912
+ var defaultErrorCorrectLevel = 'L';
913
+ var ErrorCorrectLevelMap = {
914
+ L: QR.QrCode.Ecc.LOW,
915
+ M: QR.QrCode.Ecc.MEDIUM,
916
+ Q: QR.QrCode.Ecc.QUARTILE,
917
+ H: QR.QrCode.Ecc.HIGH,
918
+ };
919
+ // Thanks the `qrcode.react`
920
+ var SUPPORTS_PATH2D = (function () {
921
+ try {
922
+ new Path2D().addPath(new Path2D());
923
+ }
924
+ catch (e) {
925
+ return false;
925
926
  }
926
- function generatePath(modules, margin) {
927
- if (margin === void 0) { margin = 0; }
928
- var ops = [];
929
- modules.forEach(function (row, y) {
930
- var start = null;
931
- row.forEach(function (cell, x) {
932
- if (!cell && start !== null) {
933
- // M0 0h7v1H0z injects the space with the move and drops the comma,
934
- // saving a char per operation
935
- ops.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
936
- start = null;
927
+ return true;
928
+ })();
929
+ function validErrorCorrectLevel(level) {
930
+ return level in ErrorCorrectLevelMap;
931
+ }
932
+ function generatePath(modules, margin) {
933
+ if (margin === void 0) { margin = 0; }
934
+ var ops = [];
935
+ modules.forEach(function (row, y) {
936
+ var start = null;
937
+ row.forEach(function (cell, x) {
938
+ if (!cell && start !== null) {
939
+ // M0 0h7v1H0z injects the space with the move and drops the comma,
940
+ // saving a char per operation
941
+ ops.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
942
+ start = null;
943
+ return;
944
+ }
945
+ // end of row, clean up or skip
946
+ if (x === row.length - 1) {
947
+ if (!cell) {
948
+ // We would have closed the op above already so this can only mean
949
+ // 2+ light modules in a row.
937
950
  return;
938
951
  }
939
- // end of row, clean up or skip
940
- if (x === row.length - 1) {
941
- if (!cell) {
942
- // We would have closed the op above already so this can only mean
943
- // 2+ light modules in a row.
944
- return;
945
- }
946
- if (start === null) {
947
- // Just a single dark module.
948
- ops.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
949
- }
950
- else {
951
- // Otherwise finish the current line.
952
- ops.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
953
- }
954
- return;
952
+ if (start === null) {
953
+ // Just a single dark module.
954
+ ops.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
955
955
  }
956
- if (cell && start === null) {
957
- start = x;
956
+ else {
957
+ // Otherwise finish the current line.
958
+ ops.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
958
959
  }
959
- });
960
+ return;
961
+ }
962
+ if (cell && start === null) {
963
+ start = x;
964
+ }
960
965
  });
961
- return ops.join('');
966
+ });
967
+ return ops.join('');
968
+ }
969
+ function getImageSettings(cells, size, margin, imageSettings) {
970
+ var width = imageSettings.width, height = imageSettings.height, imageX = imageSettings.x, imageY = imageSettings.y;
971
+ var numCells = cells.length + margin * 2;
972
+ var defaultSize = Math.floor(size * 0.1);
973
+ var scale = numCells / size;
974
+ var w = (width || defaultSize) * scale;
975
+ var h = (height || defaultSize) * scale;
976
+ var x = imageX == null ? cells.length / 2 - w / 2 : imageX * scale;
977
+ var y = imageY == null ? cells.length / 2 - h / 2 : imageY * scale;
978
+ var excavation = null;
979
+ if (imageSettings.excavate) {
980
+ var floorX = Math.floor(x);
981
+ var floorY = Math.floor(y);
982
+ var ceilW = Math.ceil(w + x - floorX);
983
+ var ceilH = Math.ceil(h + y - floorY);
984
+ excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH };
962
985
  }
963
- var QRCodeProps = {
964
- value: {
965
- type: String,
966
- required: true,
967
- default: '',
968
- },
969
- size: {
970
- type: Number,
971
- default: 100,
972
- },
973
- level: {
974
- type: String,
975
- default: defaultErrorCorrectLevel,
976
- validator: function (l) { return validErrorCorrectLevel(l); },
977
- },
978
- background: {
979
- type: String,
980
- default: '#fff',
981
- },
982
- foreground: {
983
- type: String,
984
- default: '#000',
985
- },
986
- margin: {
987
- type: Number,
988
- required: false,
989
- default: 0,
990
- },
991
- };
992
- var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
993
- type: String,
994
- required: false,
995
- default: 'canvas',
996
- validator: function (as) { return ['canvas', 'svg'].indexOf(as) > -1; },
997
- } });
998
- var QRCodeSvg = vue.defineComponent({
999
- name: 'QRCodeSvg',
1000
- props: QRCodeProps,
1001
- setup: function (props) {
1002
- var numCells = vue.ref(0);
1003
- var fgPath = vue.ref('');
1004
- var generate = function () {
1005
- var value = props.value, level = props.level, margin = props.margin;
1006
- var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1007
- numCells.value = cells.length + margin * 2;
1008
- // Drawing strategy: instead of a rect per module, we're going to create a
1009
- // single path for the dark modules and layer that on top of a light rect,
1010
- // for a total of 2 DOM nodes. We pay a bit more in string concat but that's
1011
- // way faster than DOM ops.
1012
- // For level 1, 441 nodes -> 2
1013
- // For level 40, 31329 -> 2
1014
- fgPath.value = generatePath(cells, margin);
1015
- };
1016
- generate();
1017
- vue.onUpdated(generate);
1018
- return function () { return vue.h('svg', {
1019
- width: props.size,
1020
- height: props.size,
1021
- 'shape-rendering': "crispEdges",
1022
- xmlns: 'http://www.w3.org/2000/svg',
1023
- viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
1024
- }, [
1025
- vue.h('path', {
1026
- fill: props.background,
1027
- d: "M0,0 h".concat(numCells.value, "v").concat(numCells.value, "H0z"),
1028
- }),
1029
- vue.h('path', { fill: props.foreground, d: fgPath.value }),
1030
- ]); };
1031
- },
986
+ return { x: x, y: y, h: h, w: w, excavation: excavation };
987
+ }
988
+ function excavateModules(modules, excavation) {
989
+ return modules.slice().map(function (row, y) {
990
+ if (y < excavation.y || y >= excavation.y + excavation.h) {
991
+ return row;
992
+ }
993
+ return row.map(function (cell, x) {
994
+ if (x < excavation.x || x >= excavation.x + excavation.w) {
995
+ return cell;
996
+ }
997
+ return false;
998
+ });
1032
999
  });
1033
- var QRCodeCanvas = vue.defineComponent({
1034
- name: 'QRCodeCanvas',
1035
- props: QRCodeProps,
1036
- setup: function (props) {
1037
- var canvasEl = vue.ref(null);
1038
- var generate = function () {
1039
- var value = props.value, level = props.level, size = props.size, margin = props.margin, background = props.background, foreground = props.foreground;
1040
- var canvas = canvasEl.value;
1041
- if (!canvas) {
1042
- return;
1043
- }
1044
- var ctx = canvas.getContext('2d');
1045
- if (!ctx) {
1046
- return;
1000
+ }
1001
+ var QRCodeProps = {
1002
+ value: {
1003
+ type: String,
1004
+ required: true,
1005
+ default: '',
1006
+ },
1007
+ size: {
1008
+ type: Number,
1009
+ default: 100,
1010
+ },
1011
+ level: {
1012
+ type: String,
1013
+ default: defaultErrorCorrectLevel,
1014
+ validator: function (l) { return validErrorCorrectLevel(l); },
1015
+ },
1016
+ background: {
1017
+ type: String,
1018
+ default: '#fff',
1019
+ },
1020
+ foreground: {
1021
+ type: String,
1022
+ default: '#000',
1023
+ },
1024
+ margin: {
1025
+ type: Number,
1026
+ required: false,
1027
+ default: 0,
1028
+ },
1029
+ imageSettings: {
1030
+ type: Object,
1031
+ required: false,
1032
+ default: function () { return ({}); },
1033
+ },
1034
+ };
1035
+ var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
1036
+ type: String,
1037
+ required: false,
1038
+ default: 'canvas',
1039
+ validator: function (as) { return ['canvas', 'svg'].indexOf(as) > -1; },
1040
+ } });
1041
+ var QrcodeSvg = vue.defineComponent({
1042
+ name: 'QRCodeSvg',
1043
+ props: QRCodeProps,
1044
+ setup: function (props) {
1045
+ var numCells = vue.ref(0);
1046
+ var fgPath = vue.ref('');
1047
+ var imageProps;
1048
+ var generate = function () {
1049
+ var value = props.value, level = props.level, margin = props.margin;
1050
+ var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1051
+ numCells.value = cells.length + margin * 2;
1052
+ if (props.imageSettings.src) {
1053
+ var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
1054
+ imageProps = {
1055
+ x: imageSettings.x + margin,
1056
+ y: imageSettings.y + margin,
1057
+ width: imageSettings.w,
1058
+ height: imageSettings.h,
1059
+ };
1060
+ if (imageSettings.excavation) {
1061
+ cells = excavateModules(cells, imageSettings.excavation);
1047
1062
  }
1048
- var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1049
- var numCells = cells.length + margin * 2;
1050
- var devicePixelRatio = window.devicePixelRatio || 1;
1051
- var scale = (size / numCells) * devicePixelRatio;
1052
- canvas.height = canvas.width = size * devicePixelRatio;
1053
- ctx.scale(scale, scale);
1054
- ctx.fillStyle = background;
1055
- ctx.fillRect(0, 0, numCells, numCells);
1056
- ctx.fillStyle = foreground;
1057
- if (SUPPORTS_PATH2D) {
1058
- ctx.fill(new Path2D(generatePath(cells, margin)));
1063
+ }
1064
+ // Drawing strategy: instead of a rect per module, we're going to create a
1065
+ // single path for the dark modules and layer that on top of a light rect,
1066
+ // for a total of 2 DOM nodes. We pay a bit more in string concat but that's
1067
+ // way faster than DOM ops.
1068
+ // For level 1, 441 nodes -> 2
1069
+ // For level 40, 31329 -> 2
1070
+ fgPath.value = generatePath(cells, margin);
1071
+ };
1072
+ generate();
1073
+ vue.onUpdated(generate);
1074
+ return function () { return vue.h('svg', {
1075
+ width: props.size,
1076
+ height: props.size,
1077
+ 'shape-rendering': "crispEdges",
1078
+ xmlns: 'http://www.w3.org/2000/svg',
1079
+ viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
1080
+ }, [
1081
+ vue.h('path', {
1082
+ fill: props.background,
1083
+ d: "M0,0 h".concat(numCells.value, "v").concat(numCells.value, "H0z"),
1084
+ }),
1085
+ vue.h('path', { fill: props.foreground, d: fgPath.value }),
1086
+ props.imageSettings.src && vue.h('image', __assign({ href: props.imageSettings.src }, imageProps)),
1087
+ ]); };
1088
+ },
1089
+ });
1090
+ var QrcodeCanvas = vue.defineComponent({
1091
+ name: 'QRCodeCanvas',
1092
+ props: QRCodeProps,
1093
+ setup: function (props, ctx) {
1094
+ var canvasEl = vue.ref(null);
1095
+ var imageRef = vue.ref(null);
1096
+ var generate = function () {
1097
+ var value = props.value, level = props.level, size = props.size, margin = props.margin, background = props.background, foreground = props.foreground;
1098
+ var canvas = canvasEl.value;
1099
+ if (!canvas) {
1100
+ return;
1101
+ }
1102
+ var ctx = canvas.getContext('2d');
1103
+ if (!ctx) {
1104
+ return;
1105
+ }
1106
+ var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1107
+ var numCells = cells.length + margin * 2;
1108
+ var image = imageRef.value;
1109
+ var imageProps = { x: 0, y: 0, width: 0, height: 0 };
1110
+ var showImage = props.imageSettings.src && image != null && image.naturalWidth !== 0 && image.naturalHeight !== 0;
1111
+ if (showImage) {
1112
+ var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
1113
+ imageProps = {
1114
+ x: imageSettings.x + margin,
1115
+ y: imageSettings.y + margin,
1116
+ width: imageSettings.w,
1117
+ height: imageSettings.h,
1118
+ };
1119
+ if (imageSettings.excavation) {
1120
+ cells = excavateModules(cells, imageSettings.excavation);
1059
1121
  }
1060
- else {
1061
- cells.forEach(function (row, rdx) {
1062
- row.forEach(function (cell, cdx) {
1063
- if (cell) {
1064
- ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
1065
- }
1066
- });
1122
+ }
1123
+ var devicePixelRatio = window.devicePixelRatio || 1;
1124
+ var scale = (size / numCells) * devicePixelRatio;
1125
+ canvas.height = canvas.width = size * devicePixelRatio;
1126
+ ctx.scale(scale, scale);
1127
+ ctx.fillStyle = background;
1128
+ ctx.fillRect(0, 0, numCells, numCells);
1129
+ ctx.fillStyle = foreground;
1130
+ if (SUPPORTS_PATH2D) {
1131
+ ctx.fill(new Path2D(generatePath(cells, margin)));
1132
+ }
1133
+ else {
1134
+ cells.forEach(function (row, rdx) {
1135
+ row.forEach(function (cell, cdx) {
1136
+ if (cell) {
1137
+ ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
1138
+ }
1067
1139
  });
1068
- }
1069
- };
1070
- vue.onMounted(generate);
1071
- vue.onUpdated(generate);
1072
- return function () { return vue.h('canvas', {
1073
- ref: canvasEl,
1074
- style: { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") },
1075
- }); };
1076
- },
1077
- });
1078
- var QrcodeVue = vue.defineComponent({
1079
- name: 'Qrcode',
1080
- render: function () {
1081
- var _a = this.$props, renderAs = _a.renderAs, value = _a.value, _size = _a.size, _margin = _a.margin, _level = _a.level, background = _a.background, foreground = _a.foreground;
1082
- var size = _size >>> 0;
1083
- var margin = _margin >>> 0;
1084
- var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
1085
- return vue.h(renderAs === 'svg' ? QRCodeSvg : QRCodeCanvas, { value: value, size: size, margin: margin, level: level, background: background, foreground: foreground });
1086
- },
1087
- props: QRCodeVueProps,
1088
- });
1140
+ });
1141
+ }
1142
+ if (showImage) {
1143
+ ctx.drawImage(image, imageProps.x, imageProps.y, imageProps.width, imageProps.height);
1144
+ }
1145
+ };
1146
+ vue.onMounted(generate);
1147
+ vue.onUpdated(generate);
1148
+ var style = ctx.attrs.style;
1149
+ return function () { return vue.h(vue.Fragment, [
1150
+ vue.h('canvas', __assign(__assign({}, ctx.attrs), { ref: canvasEl, style: __assign(__assign({}, style), { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") }) })),
1151
+ props.imageSettings.src && vue.h('img', {
1152
+ ref: imageRef,
1153
+ src: props.imageSettings.src,
1154
+ style: { display: 'none' },
1155
+ onLoad: generate,
1156
+ })
1157
+ ]); };
1158
+ },
1159
+ });
1160
+ var QrcodeVue = vue.defineComponent({
1161
+ name: 'Qrcode',
1162
+ render: function () {
1163
+ var _a = this.$props, renderAs = _a.renderAs, value = _a.value, _size = _a.size, _margin = _a.margin, _level = _a.level, background = _a.background, foreground = _a.foreground, imageSettings = _a.imageSettings;
1164
+ var size = _size >>> 0;
1165
+ var margin = _margin >>> 0;
1166
+ var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
1167
+ return vue.h(renderAs === 'svg' ? QrcodeSvg : QrcodeCanvas, { value: value, size: size, margin: margin, level: level, background: background, foreground: foreground, imageSettings: imageSettings });
1168
+ },
1169
+ props: QRCodeVueProps,
1170
+ });
1171
+
1172
+ exports.QrcodeCanvas = QrcodeCanvas;
1173
+ exports.QrcodeSvg = QrcodeSvg;
1174
+ exports.default = QrcodeVue;
1089
1175
 
1090
- return QrcodeVue;
1176
+ Object.defineProperty(exports, '__esModule', { value: true });
1091
1177
 
1092
1178
  }));