qrcodegen.js 38 KB

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