qrcodegen.js 38 KB

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