Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

qrCode.ts

984 lines42.3 KB

1// @ts-nocheck
2/* oxlint-disable eslint/no-useless-escape */
3/*
4 * QR Code generator library (TypeScript)
5 *
6 * Copyright (c) Project Nayuki. (MIT License)
7 * https://www.nayuki.io/page/qr-code-generator-library
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy of
10 * this software and associated documentation files (the "Software"), to deal in
11 * the Software without restriction, including without limitation the rights to
12 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
13 * the Software, and to permit persons to whom the Software is furnished to do so,
14 * subject to the following conditions:
15 * - The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 * - The Software is provided "as is", without warranty of any kind, express or
18 * implied, including but not limited to the warranties of merchantability,
19 * fitness for a particular purpose and noninfringement. In no event shall the
20 * authors or copyright holders be liable for any claim, damages or other
21 * liability, whether in an action of contract, tort or otherwise, arising from,
22 * out of or in connection with the Software or the use or other dealings in the
23 * Software.
24 */
25​
26"use strict";
27​
28namespace qrcodegen {
29 type bit = number;
30 type byte = number;
31 type int = number;
32​
33 /*---- QR Code symbol class ----*/
34​
35 /*
36 * A QR Code symbol, which is a type of two-dimension barcode.
37 * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
38 * Instances of this class represent an immutable square grid of dark and light cells.
39 * The class provides static factory functions to create a QR Code from text or binary data.
40 * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
41 * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
42 *
43 * Ways to create a QR Code object:
44 * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
45 * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
46 * - Low level: Custom-make the array of data codeword bytes (including
47 * segment headers and final padding, excluding error correction codewords),
48 * supply the appropriate version number, and call the QrCode() constructor.
49 * (Note that all ways require supplying the desired error correction level.)
50 */
51 export class QrCode {
52 /*-- Static factory functions (high level) --*/
53​
54 // Returns a QR Code representing the given Unicode text string at the given error correction level.
55 // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
56 // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
57 // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
58 // ecl argument if it can be done without increasing the version.
59 public static encodeText(text: string, ecl: QrCode.Ecc): QrCode {
60 const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text);
61 return QrCode.encodeSegments(segs, ecl);
62 }
63​
64 // Returns a QR Code representing the given binary data at the given error correction level.
65 // This function always encodes using the binary segment mode, not any text mode. The maximum number of
66 // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
67 // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
68 public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCode.Ecc): QrCode {
69 const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data);
70 return QrCode.encodeSegments([seg], ecl);
71 }
72​
73 /*-- Static factory functions (mid level) --*/
74​
75 // Returns a QR Code representing the given segments with the given encoding parameters.
76 // The smallest possible QR Code version within the given range is automatically
77 // chosen for the output. Iff boostEcl is true, then the ECC level of the result
78 // may be higher than the ecl argument if it can be done without increasing the
79 // version. The mask number is either between 0 to 7 (inclusive) to force that
80 // mask, or -1 to automatically choose an appropriate mask (which may be slow).
81 // This function allows the user to create a custom sequence of segments that switches
82 // between modes (such as alphanumeric and byte) to encode text in less space.
83 // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
84 public static encodeSegments(
85 segs: Readonly<Array<QrSegment>>,
86 ecl: QrCode.Ecc,
87 minVersion: int = 1,
88 maxVersion: int = 40,
89 mask: int = -1,
90 boostEcl: boolean = true,
91 ): QrCode {
92 if (
93 !(
94 QrCode.MIN_VERSION <= minVersion &&
95 minVersion <= maxVersion &&
96 maxVersion <= QrCode.MAX_VERSION
97 ) ||
98 mask < -1 ||
99 mask > 7
100 )
101 throw new RangeError("Invalid value");
102​
103 // Find the minimal version number to use
104 let version: int;
105 let dataUsedBits: int;
106 for (version = minVersion; ; version++) {
107 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
108 const usedBits: number = QrSegment.getTotalBits(segs, version);
109 if (usedBits <= dataCapacityBits) {
110 dataUsedBits = usedBits;
111 break; // This version number is found to be suitable
112 }
113 if (version >= maxVersion)
114 // All versions in the range could not fit the given data
115 throw new RangeError("Data too long");
116 }
117​
118 // Increase the error correction level while the data still fits in the current version number
119 for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {
120 // From low to high
121 if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
122 ecl = newEcl;
123 }
124​
125 // Concatenate all segments to create the data bit string
126 let bb: Array<bit> = [];
127 for (const seg of segs) {
128 appendBits(seg.mode.modeBits, 4, bb);
129 appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
130 for (const b of seg.getData()) bb.push(b);
131 }
132 assert(bb.length == dataUsedBits);
133​
134 // Add terminator and pad up to a byte if applicable
135 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;
136 assert(bb.length <= dataCapacityBits);
137 appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
138 appendBits(0, (8 - (bb.length % 8)) % 8, bb);
139 assert(bb.length % 8 == 0);
140​
141 // Pad with alternating bytes until data capacity is reached
142 for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)
143 appendBits(padByte, 8, bb);
144​
145 // Pack bits into bytes in big endian
146 let dataCodewords: Array<byte> = [];
147 while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);
148 bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3] |= b << (7 - (i & 7))));
149​
150 // Create the QR Code object
151 return new QrCode(version, ecl, dataCodewords, mask);
152 }
153​
154 /*-- Fields --*/
155​
156 // The width and height of this QR Code, measured in modules, between
157 // 21 and 177 (inclusive). This is equal to version * 4 + 17.
158 public readonly size: int;
159​
160 // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
161 // Even if a QR Code is created with automatic masking requested (mask = -1),
162 // the resulting object still has a mask value between 0 and 7.
163 public readonly mask: int;
164​
165 // The modules of this QR Code (false = light, true = dark).
166 // Immutable after constructor finishes. Accessed through getModule().
167 private readonly modules: Array<Array<boolean>> = [];
168​
169 // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
170 private readonly isFunction: Array<Array<boolean>> = [];
171​
172 /*-- Constructor (low level) and fields --*/
173​
174 // Creates a new QR Code with the given version number,
175 // error correction level, data codeword bytes, and mask number.
176 // This is a low-level API that most users should not use directly.
177 // A mid-level API is the encodeSegments() function.
178 public constructor(
179 // The version number of this QR Code, which is between 1 and 40 (inclusive).
180 // This determines the size of this barcode.
181 public readonly version: int,
182​
183 // The error correction level used in this QR Code.
184 public readonly errorCorrectionLevel: QrCode.Ecc,
185​
186 dataCodewords: Readonly<Array<byte>>,
187​
188 msk: int,
189 ) {
190 // Check scalar arguments
191 if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
192 throw new RangeError("Version value out of range");
193 if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range");
194 this.size = version * 4 + 17;
195​
196 // Initialize both grids to be size*size arrays of Boolean false
197 let row: Array<boolean> = [];
198 for (let i = 0; i < this.size; i++) row.push(false);
199 for (let i = 0; i < this.size; i++) {
200 this.modules.push(row.slice()); // Initially all light
201 this.isFunction.push(row.slice());
202 }
203​
204 // Compute ECC, draw modules
205 this.drawFunctionPatterns();
206 const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);
207 this.drawCodewords(allCodewords);
208​
209 // Do masking
210 if (msk == -1) {
211 // Automatically choose best mask
212 let minPenalty: int = 1000000000;
213 for (let i = 0; i < 8; i++) {
214 this.applyMask(i);
215 this.drawFormatBits(i);
216 const penalty: int = this.getPenaltyScore();
217 if (penalty < minPenalty) {
218 msk = i;
219 minPenalty = penalty;
220 }
221 this.applyMask(i); // Undoes the mask due to XOR
222 }
223 }
224 assert(0 <= msk && msk <= 7);
225 this.mask = msk;
226 this.applyMask(msk); // Apply the final choice of mask
227 this.drawFormatBits(msk); // Overwrite old format bits
228​
229 this.isFunction = [];
230 }
231​
232 /*-- Accessor methods --*/
233​
234 // Returns the color of the module (pixel) at the given coordinates, which is false
235 // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
236 // If the given coordinates are out of bounds, then false (light) is returned.
237 public getModule(x: int, y: int): boolean {
238 return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
239 }
240​
241 /*-- Private helper methods for constructor: Drawing function modules --*/
242​
243 // Reads this object's version field, and draws and marks all function modules.
244 private drawFunctionPatterns(): void {
245 // Draw horizontal and vertical timing patterns
246 for (let i = 0; i < this.size; i++) {
247 this.setFunctionModule(6, i, i % 2 == 0);
248 this.setFunctionModule(i, 6, i % 2 == 0);
249 }
250​
251 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
252 this.drawFinderPattern(3, 3);
253 this.drawFinderPattern(this.size - 4, 3);
254 this.drawFinderPattern(3, this.size - 4);
255​
256 // Draw numerous alignment patterns
257 const alignPatPos: Array<int> = this.getAlignmentPatternPositions();
258 const numAlign: int = alignPatPos.length;
259 for (let i = 0; i < numAlign; i++) {
260 for (let j = 0; j < numAlign; j++) {
261 // Don't draw on the three finder corners
262 if (
263 !((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))
264 )
265 this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
266 }
267 }
268​
269 // Draw configuration data
270 this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
271 this.drawVersion();
272 }
273​
274 // Draws two copies of the format bits (with its own error correction code)
275 // based on the given mask and this object's error correction level field.
276 private drawFormatBits(mask: int): void {
277 // Calculate error correction code and pack bits
278 const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3
279 let rem: int = data;
280 for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
281 const bits = ((data << 10) | rem) ^ 0x5412; // uint15
282 assert(bits >>> 15 == 0);
283​
284 // Draw first copy
285 for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));
286 this.setFunctionModule(8, 7, getBit(bits, 6));
287 this.setFunctionModule(8, 8, getBit(bits, 7));
288 this.setFunctionModule(7, 8, getBit(bits, 8));
289 for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));
290​
291 // Draw second copy
292 for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
293 for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
294 this.setFunctionModule(8, this.size - 8, true); // Always dark
295 }
296​
297 // Draws two copies of the version bits (with its own error correction code),
298 // based on this object's version field, iff 7 <= version <= 40.
299 private drawVersion(): void {
300 if (this.version < 7) return;
301​
302 // Calculate error correction code and pack bits
303 let rem: int = this.version; // version is uint6, in the range [7, 40]
304 for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
305 const bits: int = (this.version << 12) | rem; // uint18
306 assert(bits >>> 18 == 0);
307​
308 // Draw two copies
309 for (let i = 0; i < 18; i++) {
310 const color: boolean = getBit(bits, i);
311 const a: int = this.size - 11 + (i % 3);
312 const b: int = Math.floor(i / 3);
313 this.setFunctionModule(a, b, color);
314 this.setFunctionModule(b, a, color);
315 }
316 }
317​
318 // Draws a 9*9 finder pattern including the border separator,
319 // with the center module at (x, y). Modules can be out of bounds.
320 private drawFinderPattern(x: int, y: int): void {
321 for (let dy = -4; dy <= 4; dy++) {
322 for (let dx = -4; dx <= 4; dx++) {
323 const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
324 const xx: int = x + dx;
325 const yy: int = y + dy;
326 if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
327 this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
328 }
329 }
330 }
331​
332 // Draws a 5*5 alignment pattern, with the center module
333 // at (x, y). All modules must be in bounds.
334 private drawAlignmentPattern(x: int, y: int): void {
335 for (let dy = -2; dy <= 2; dy++) {
336 for (let dx = -2; dx <= 2; dx++)
337 this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
338 }
339 }
340​
341 // Sets the color of a module and marks it as a function module.
342 // Only used by the constructor. Coordinates must be in bounds.
343 private setFunctionModule(x: int, y: int, isDark: boolean): void {
344 this.modules[y][x] = isDark;
345 this.isFunction[y][x] = true;
346 }
347​
348 /*-- Private helper methods for constructor: Codewords and masking --*/
349​
350 // Returns a new byte string representing the given data with the appropriate error correction
351 // codewords appended to it, based on this object's version and error correction level.
352 private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {
353 const ver: int = this.version;
354 const ecl: QrCode.Ecc = this.errorCorrectionLevel;
355 if (data.length != QrCode.getNumDataCodewords(ver, ecl))
356 throw new RangeError("Invalid argument");
357​
358 // Calculate parameter numbers
359 const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
360 const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
361 const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
362 const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks);
363 const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);
364​
365 // Split data into blocks and append ECC to each block
366 let blocks: Array<Array<byte>> = [];
367 const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);
368 for (let i = 0, k = 0; i < numBlocks; i++) {
369 let dat: Array<byte> = data.slice(
370 k,
371 k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1),
372 );
373 k += dat.length;
374 const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
375 if (i < numShortBlocks) dat.push(0);
376 blocks.push(dat.concat(ecc));
377 }
378​
379 // Interleave (not concatenate) the bytes from every block into a single sequence
380 let result: Array<byte> = [];
381 for (let i = 0; i < blocks[0].length; i++) {
382 blocks.forEach((block, j) => {
383 // Skip the padding byte in short blocks
384 if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]);
385 });
386 }
387 assert(result.length == rawCodewords);
388 return result;
389 }
390​
391 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
392 // data area of this QR Code. Function modules need to be marked off before this is called.
393 private drawCodewords(data: Readonly<Array<byte>>): void {
394 if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
395 throw new RangeError("Invalid argument");
396 let i: int = 0; // Bit index into the data
397 // Do the funny zigzag scan
398 for (let right = this.size - 1; right >= 1; right -= 2) {
399 // Index of right column in each column pair
400 if (right == 6) right = 5;
401 for (let vert = 0; vert < this.size; vert++) {
402 // Vertical counter
403 for (let j = 0; j < 2; j++) {
404 const x: int = right - j; // Actual x coordinate
405 const upward: boolean = ((right + 1) & 2) == 0;
406 const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate
407 if (!this.isFunction[y][x] && i < data.length * 8) {
408 this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
409 i++;
410 }
411 // If this QR Code has any remainder bits (0 to 7), they were assigned as
412 // 0/false/light by the constructor and are left unchanged by this method
413 }
414 }
415 }
416 assert(i == data.length * 8);
417 }
418​
419 // XORs the codeword modules in this QR Code with the given mask pattern.
420 // The function modules must be marked and the codeword bits must be drawn
421 // before masking. Due to the arithmetic of XOR, calling applyMask() with
422 // the same mask value a second time will undo the mask. A final well-formed
423 // QR Code needs exactly one (not zero, two, etc.) mask applied.
424 private applyMask(mask: int): void {
425 if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range");
426 for (let y = 0; y < this.size; y++) {
427 for (let x = 0; x < this.size; x++) {
428 let invert: boolean;
429 switch (mask) {
430 case 0:
431 invert = (x + y) % 2 == 0;
432 break;
433 case 1:
434 invert = y % 2 == 0;
435 break;
436 case 2:
437 invert = x % 3 == 0;
438 break;
439 case 3:
440 invert = (x + y) % 3 == 0;
441 break;
442 case 4:
443 invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
444 break;
445 case 5:
446 invert = ((x * y) % 2) + ((x * y) % 3) == 0;
447 break;
448 case 6:
449 invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;
450 break;
451 case 7:
452 invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;
453 break;
454 default:
455 throw new Error("Unreachable");
456 }
457 if (!this.isFunction[y][x] && invert) this.modules[y][x] = !this.modules[y][x];
458 }
459 }
460 }
461​
462 // Calculates and returns the penalty score based on state of this QR Code's current modules.
463 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
464 private getPenaltyScore(): int {
465 let result: int = 0;
466​
467 // Adjacent modules in row having same color, and finder-like patterns
468 for (let y = 0; y < this.size; y++) {
469 let runColor = false;
470 let runX = 0;
471 let runHistory = [0, 0, 0, 0, 0, 0, 0];
472 for (let x = 0; x < this.size; x++) {
473 if (this.modules[y][x] == runColor) {
474 runX++;
475 if (runX == 5) result += QrCode.PENALTY_N1;
476 else if (runX > 5) result++;
477 } else {
478 this.finderPenaltyAddHistory(runX, runHistory);
479 if (!runColor)
480 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
481 runColor = this.modules[y][x];
482 runX = 1;
483 }
484 }
485 result +=
486 this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
487 }
488 // Adjacent modules in column having same color, and finder-like patterns
489 for (let x = 0; x < this.size; x++) {
490 let runColor = false;
491 let runY = 0;
492 let runHistory = [0, 0, 0, 0, 0, 0, 0];
493 for (let y = 0; y < this.size; y++) {
494 if (this.modules[y][x] == runColor) {
495 runY++;
496 if (runY == 5) result += QrCode.PENALTY_N1;
497 else if (runY > 5) result++;
498 } else {
499 this.finderPenaltyAddHistory(runY, runHistory);
500 if (!runColor)
501 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
502 runColor = this.modules[y][x];
503 runY = 1;
504 }
505 }
506 result +=
507 this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
508 }
509​
510 // 2*2 blocks of modules having same color
511 for (let y = 0; y < this.size - 1; y++) {
512 for (let x = 0; x < this.size - 1; x++) {
513 const color: boolean = this.modules[y][x];
514 if (
515 color == this.modules[y][x + 1] &&
516 color == this.modules[y + 1][x] &&
517 color == this.modules[y + 1][x + 1]
518 )
519 result += QrCode.PENALTY_N2;
520 }
521 }
522​
523 // Balance of dark and light modules
524 let dark: int = 0;
525 for (const row of this.modules)
526 dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
527 const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2
528 // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
529 const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
530 assert(0 <= k && k <= 9);
531 result += k * QrCode.PENALTY_N4;
532 assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
533 return result;
534 }
535​
536 /*-- Private helper functions --*/
537​
538 // Returns an ascending list of positions of alignment patterns for this version number.
539 // Each position is in the range [0,177), and are used on both the x and y axes.
540 // This could be implemented as lookup table of 40 variable-length lists of integers.
541 private getAlignmentPatternPositions(): Array<int> {
542 if (this.version == 1) return [];
543 else {
544 const numAlign: int = Math.floor(this.version / 7) + 2;
545 const step: int =
546 this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
547 let result: Array<int> = [6];
548 for (let pos = this.size - 7; result.length < numAlign; pos -= step)
549 result.splice(1, 0, pos);
550 return result;
551 }
552 }
553​
554 // Returns the number of data bits that can be stored in a QR Code of the given version number, after
555 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
556 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
557 private static getNumRawDataModules(ver: int): int {
558 if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
559 throw new RangeError("Version number out of range");
560 let result: int = (16 * ver + 128) * ver + 64;
561 if (ver >= 2) {
562 const numAlign: int = Math.floor(ver / 7) + 2;
563 result -= (25 * numAlign - 10) * numAlign - 55;
564 if (ver >= 7) result -= 36;
565 }
566 assert(208 <= result && result <= 29648);
567 return result;
568 }
569​
570 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
571 // QR Code of the given version number and error correction level, with remainder bits discarded.
572 // This stateless pure function could be implemented as a (40*4)-cell lookup table.
573 private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int {
574 return (
575 Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
576 QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
577 QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]
578 );
579 }
580​
581 // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
582 // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
583 private static reedSolomonComputeDivisor(degree: int): Array<byte> {
584 if (degree < 1 || degree > 255) throw new RangeError("Degree out of range");
585 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
586 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
587 let result: Array<byte> = [];
588 for (let i = 0; i < degree - 1; i++) result.push(0);
589 result.push(1); // Start off with the monomial x^0
590​
591 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
592 // and drop the highest monomial term which is always 1x^degree.
593 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
594 let root = 1;
595 for (let i = 0; i < degree; i++) {
596 // Multiply the current product by (x - r^i)
597 for (let j = 0; j < result.length; j++) {
598 result[j] = QrCode.reedSolomonMultiply(result[j], root);
599 if (j + 1 < result.length) result[j] ^= result[j + 1];
600 }
601 root = QrCode.reedSolomonMultiply(root, 0x02);
602 }
603 return result;
604 }
605​
606 // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
607 private static reedSolomonComputeRemainder(
608 data: Readonly<Array<byte>>,
609 divisor: Readonly<Array<byte>>,
610 ): Array<byte> {
611 let result: Array<byte> = divisor.map((_) => 0);
612 for (const b of data) {
613 // Polynomial division
614 const factor: byte = b ^ (result.shift() as byte);
615 result.push(0);
616 divisor.forEach((coef, i) => (result[i] ^= QrCode.reedSolomonMultiply(coef, factor)));
617 }
618 return result;
619 }
620​
621 // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
622 // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
623 private static reedSolomonMultiply(x: byte, y: byte): byte {
624 if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError("Byte out of range");
625 // Russian peasant multiplication
626 let z: int = 0;
627 for (let i = 7; i >= 0; i--) {
628 z = (z << 1) ^ ((z >>> 7) * 0x11d);
629 z ^= ((y >>> i) & 1) * x;
630 }
631 assert(z >>> 8 == 0);
632 return z as byte;
633 }
634​
635 // Can only be called immediately after a light run is added, and
636 // returns either 0, 1, or 2. A helper function for getPenaltyScore().
637 private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {
638 const n: int = runHistory[1];
639 assert(n <= this.size * 3);
640 const core: boolean =
641 n > 0 &&
642 runHistory[2] == n &&
643 runHistory[3] == n * 3 &&
644 runHistory[4] == n &&
645 runHistory[5] == n;
646 return (
647 (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) +
648 (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0)
649 );
650 }
651​
652 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
653 private finderPenaltyTerminateAndCount(
654 currentRunColor: boolean,
655 currentRunLength: int,
656 runHistory: Array<int>,
657 ): int {
658 if (currentRunColor) {
659 // Terminate dark run
660 this.finderPenaltyAddHistory(currentRunLength, runHistory);
661 currentRunLength = 0;
662 }
663 currentRunLength += this.size; // Add light border to final run
664 this.finderPenaltyAddHistory(currentRunLength, runHistory);
665 return this.finderPenaltyCountPatterns(runHistory);
666 }
667​
668 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
669 private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {
670 if (runHistory[0] == 0) currentRunLength += this.size; // Add light border to initial run
671 runHistory.pop();
672 runHistory.unshift(currentRunLength);
673 }
674​
675 /*-- Constants and tables --*/
676​
677 // The minimum version number supported in the QR Code Model 2 standard.
678 public static readonly MIN_VERSION: int = 1;
679 // The maximum version number supported in the QR Code Model 2 standard.
680 public static readonly MAX_VERSION: int = 40;
681​
682 // For use in getPenaltyScore(), when evaluating which mask is best.
683 private static readonly PENALTY_N1: int = 3;
684 private static readonly PENALTY_N2: int = 3;
685 private static readonly PENALTY_N3: int = 40;
686 private static readonly PENALTY_N4: int = 10;
687​
688 private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [
689 // Version: (note that index 0 is for padding, and is set to an illegal value)
690 //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
691 [
692 -1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28,
693 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
694 ], // Low
695 [
696 -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28,
697 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
698 ], // Medium
699 [
700 -1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30,
701 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
702 ], // Quartile
703 [
704 -1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24,
705 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
706 ], // High
707 ];
708​
709 private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [
710 // Version: (note that index 0 is for padding, and is set to an illegal value)
711 //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
712 [
713 -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,
714 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25,
715 ], // Low
716 [
717 -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,
718 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,
719 ], // Medium
720 [
721 -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,
722 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,
723 ], // Quartile
724 [
725 -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,
726 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,
727 ], // High
728 ];
729 }
730​
731 // Appends the given number of low-order bits of the given value
732 // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
733 function appendBits(val: int, len: int, bb: Array<bit>): void {
734 if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError("Value out of range");
735 for (
736 let i = len - 1;
737 i >= 0;
738 i-- // Append bit by bit
739 )
740 bb.push((val >>> i) & 1);
741 }
742​
743 // Returns true iff the i'th bit of x is set to 1.
744 function getBit(x: int, i: int): boolean {
745 return ((x >>> i) & 1) != 0;
746 }
747​
748 // Throws an exception if the given condition is false.
749 function assert(cond: boolean): void {
750 if (!cond) throw new Error("Assertion error");
751 }
752​
753 /*---- Data segment class ----*/
754​
755 /*
756 * A segment of character/binary/control data in a QR Code symbol.
757 * Instances of this class are immutable.
758 * The mid-level way to create a segment is to take the payload data
759 * and call a static factory function such as QrSegment.makeNumeric().
760 * The low-level way to create a segment is to custom-make the bit buffer
761 * and call the QrSegment() constructor with appropriate values.
762 * This segment class imposes no length restrictions, but QR Codes have restrictions.
763 * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
764 * Any segment longer than this is meaningless for the purpose of generating QR Codes.
765 */
766 export class QrSegment {
767 /*-- Static factory functions (mid level) --*/
768​
769 // Returns a segment representing the given binary data encoded in
770 // byte mode. All input byte arrays are acceptable. Any text string
771 // can be converted to UTF-8 bytes and encoded as a byte mode segment.
772 public static makeBytes(data: Readonly<Array<byte>>): QrSegment {
773 let bb: Array<bit> = [];
774 for (const b of data) appendBits(b, 8, bb);
775 return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
776 }
777​
778 // Returns a segment representing the given string of decimal digits encoded in numeric mode.
779 public static makeNumeric(digits: string): QrSegment {
780 if (!QrSegment.isNumeric(digits))
781 throw new RangeError("String contains non-numeric characters");
782 let bb: Array<bit> = [];
783 for (let i = 0; i < digits.length; ) {
784 // Consume up to 3 digits per iteration
785 const n: int = Math.min(digits.length - i, 3);
786 appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
787 i += n;
788 }
789 return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
790 }
791​
792 // Returns a segment representing the given text string encoded in alphanumeric mode.
793 // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
794 // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
795 public static makeAlphanumeric(text: string): QrSegment {
796 if (!QrSegment.isAlphanumeric(text))
797 throw new RangeError("String contains unencodable characters in alphanumeric mode");
798 let bb: Array<bit> = [];
799 let i: int;
800 for (i = 0; i + 2 <= text.length; i += 2) {
801 // Process groups of 2
802 let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
803 temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
804 appendBits(temp, 11, bb);
805 }
806 if (i < text.length)
807 // 1 character remaining
808 appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
809 return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
810 }
811​
812 // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
813 // The result may use various segment modes and switch modes to optimize the length of the bit stream.
814 public static makeSegments(text: string): Array<QrSegment> {
815 // Select the most efficient segment encoding automatically
816 if (text == "") return [];
817 else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];
818 else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];
819 else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
820 }
821​
822 // Returns a segment representing an Extended Channel Interpretation
823 // (ECI) designator with the given assignment value.
824 public static makeEci(assignVal: int): QrSegment {
825 let bb: Array<bit> = [];
826 if (assignVal < 0) throw new RangeError("ECI assignment value out of range");
827 else if (assignVal < 1 << 7) appendBits(assignVal, 8, bb);
828 else if (assignVal < 1 << 14) {
829 appendBits(0b10, 2, bb);
830 appendBits(assignVal, 14, bb);
831 } else if (assignVal < 1000000) {
832 appendBits(0b110, 3, bb);
833 appendBits(assignVal, 21, bb);
834 } else throw new RangeError("ECI assignment value out of range");
835 return new QrSegment(QrSegment.Mode.ECI, 0, bb);
836 }
837​
838 // Tests whether the given string can be encoded as a segment in numeric mode.
839 // A string is encodable iff each character is in the range 0 to 9.
840 public static isNumeric(text: string): boolean {
841 return QrSegment.NUMERIC_REGEX.test(text);
842 }
843​
844 // Tests whether the given string can be encoded as a segment in alphanumeric mode.
845 // A string is encodable iff each character is in the following set: 0 to 9, A to Z
846 // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
847 public static isAlphanumeric(text: string): boolean {
848 return QrSegment.ALPHANUMERIC_REGEX.test(text);
849 }
850​
851 /*-- Constructor (low level) and fields --*/
852​
853 // Creates a new QR Code segment with the given attributes and data.
854 // The character count (numChars) must agree with the mode and the bit buffer length,
855 // but the constraint isn't checked. The given bit buffer is cloned and stored.
856 public constructor(
857 // The mode indicator of this segment.
858 public readonly mode: QrSegment.Mode,
859​
860 // The length of this segment's unencoded data. Measured in characters for
861 // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
862 // Always zero or positive. Not the same as the data's bit length.
863 public readonly numChars: int,
864​
865 // The data bits of this segment. Accessed through getData().
866 private readonly bitData: Array<bit>,
867 ) {
868 if (numChars < 0) throw new RangeError("Invalid argument");
869 this.bitData = bitData.slice(); // Make defensive copy
870 }
871​
872 /*-- Methods --*/
873​
874 // Returns a new copy of the data bits of this segment.
875 public getData(): Array<bit> {
876 return this.bitData.slice(); // Make defensive copy
877 }
878​
879 // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
880 // the given version. The result is infinity if a segment has too many characters to fit its length field.
881 public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {
882 let result: number = 0;
883 for (const seg of segs) {
884 const ccbits: int = seg.mode.numCharCountBits(version);
885 if (seg.numChars >= 1 << ccbits) return Infinity; // The segment's length doesn't fit the field's bit width
886 result += 4 + ccbits + seg.bitData.length;
887 }
888 return result;
889 }
890​
891 // Returns a new array of bytes representing the given string encoded in UTF-8.
892 private static toUtf8ByteArray(str: string): Array<byte> {
893 str = encodeURI(str);
894 let result: Array<byte> = [];
895 for (let i = 0; i < str.length; i++) {
896 if (str.charAt(i) != "%") result.push(str.charCodeAt(i));
897 else {
898 result.push(parseInt(str.substring(i + 1, i + 3), 16));
899 i += 2;
900 }
901 }
902 return result;
903 }
904​
905 /*-- Constants --*/
906​
907 // Describes precisely all strings that are encodable in numeric mode.
908 private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;
909​
910 // Describes precisely all strings that are encodable in alphanumeric mode.
911 private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/;
912​
913 // The set of all legal characters in alphanumeric mode,
914 // where each character value maps to the index in the string.
915 private static readonly ALPHANUMERIC_CHARSET: string =
916 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
917 }
919​
920/*---- Public helper enumeration ----*/
921​
922namespace qrcodegen.QrCode {
923 type int = number;
924​
925 /*
926 * The error correction level in a QR Code symbol. Immutable.
927 */
928 export class Ecc {
929 /*-- Constants --*/
930​
931 public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
932 public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
933 public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
934 public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
935​
936 /*-- Constructor and fields --*/
937​
938 private constructor(
939 // In the range 0 to 3 (unsigned 2-bit integer).
940 public readonly ordinal: int,
941 // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
942 public readonly formatBits: int,
943 ) {}
944 }
946​
947/*---- Public helper enumeration ----*/
948​
949namespace qrcodegen.QrSegment {
950 type int = number;
951​
952 /*
953 * Describes how a segment's data bits are interpreted. Immutable.
954 */
955 export class Mode {
956 /*-- Constants --*/
957​
958 public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]);
959 public static readonly ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
960 public static readonly BYTE = new Mode(0x4, [8, 16, 16]);
961 public static readonly KANJI = new Mode(0x8, [8, 10, 12]);
962 public static readonly ECI = new Mode(0x7, [0, 0, 0]);
963​
964 /*-- Constructor and fields --*/
965​
966 private constructor(
967 // The mode indicator bits, which is a uint4 value (range 0 to 15).
968 public readonly modeBits: int,
969 // Number of character count bits for three different version ranges.
970 private readonly numBitsCharCount: [int, int, int],
971 ) {}
972​
973 /*-- Method --*/
974​
975 // (Package-private) Returns the bit width of the character count field for a segment in
976 // this mode in a QR Code at the given version number. The result is in the range [0, 16].
977 public numCharCountBits(ver: int): int {
978 return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
979 }
980 }
982​
983export const QrCode = qrcodegen.QrCode;
984export const QrSegment = qrcodegen.QrSegment;