-
Notifications
You must be signed in to change notification settings - Fork 1
/
qrcode.js
5414 lines (4595 loc) · 381 KB
/
qrcode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.QRCode = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
// can-promise has a crash in some versions of react native that dont have
// standard global objects
// https://github.com/soldair/node-qrcode/issues/157
module.exports = function () {
return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
}
},{}],2:[function(require,module,exports){
/**
* Alignment pattern are fixed reference pattern in defined positions
* in a matrix symbology, which enables the decode software to re-synchronise
* the coordinate mapping of the image modules in the event of moderate amounts
* of distortion of the image.
*
* Alignment patterns are present only in QR Code symbols of version 2 or larger
* and their number depends on the symbol version.
*/
var getSymbolSize = require('./utils').getSymbolSize
/**
* Calculate the row/column coordinates of the center module of each alignment pattern
* for the specified QR Code version.
*
* The alignment patterns are positioned symmetrically on either side of the diagonal
* running from the top left corner of the symbol to the bottom right corner.
*
* Since positions are simmetrical only half of the coordinates are returned.
* Each item of the array will represent in turn the x and y coordinate.
* @see {@link getPositions}
*
* @param {Number} version QR Code version
* @return {Array} Array of coordinate
*/
exports.getRowColCoords = function getRowColCoords (version) {
if (version === 1) return []
var posCount = Math.floor(version / 7) + 2
var size = getSymbolSize(version)
var intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
var positions = [size - 7] // Last coord is always (size - 7)
for (var i = 1; i < posCount - 1; i++) {
positions[i] = positions[i - 1] - intervals
}
positions.push(6) // First coord is always 6
return positions.reverse()
}
/**
* Returns an array containing the positions of each alignment pattern.
* Each array's element represent the center point of the pattern as (x, y) coordinates
*
* Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
* and filtering out the items that overlaps with finder pattern
*
* @example
* For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
* The alignment patterns, therefore, are to be centered on (row, column)
* positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
* Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
* and are not therefore used for alignment patterns.
*
* var pos = getPositions(7)
* // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
*
* @param {Number} version QR Code version
* @return {Array} Array of coordinates
*/
exports.getPositions = function getPositions (version) {
var coords = []
var pos = exports.getRowColCoords(version)
var posLength = pos.length
for (var i = 0; i < posLength; i++) {
for (var j = 0; j < posLength; j++) {
// Skip if position is occupied by finder patterns
if ((i === 0 && j === 0) || // top-left
(i === 0 && j === posLength - 1) || // bottom-left
(i === posLength - 1 && j === 0)) { // top-right
continue
}
coords.push([pos[i], pos[j]])
}
}
return coords
}
},{"./utils":21}],3:[function(require,module,exports){
var Mode = require('./mode')
/**
* Array of characters available in alphanumeric mode
*
* As per QR Code specification, to each character
* is assigned a value from 0 to 44 which in this case coincides
* with the array index
*
* @type {Array}
*/
var ALPHA_NUM_CHARS = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
' ', '$', '%', '*', '+', '-', '.', '/', ':'
]
function AlphanumericData (data) {
this.mode = Mode.ALPHANUMERIC
this.data = data
}
AlphanumericData.getBitsLength = function getBitsLength (length) {
return 11 * Math.floor(length / 2) + 6 * (length % 2)
}
AlphanumericData.prototype.getLength = function getLength () {
return this.data.length
}
AlphanumericData.prototype.getBitsLength = function getBitsLength () {
return AlphanumericData.getBitsLength(this.data.length)
}
AlphanumericData.prototype.write = function write (bitBuffer) {
var i
// Input data characters are divided into groups of two characters
// and encoded as 11-bit binary codes.
for (i = 0; i + 2 <= this.data.length; i += 2) {
// The character value of the first character is multiplied by 45
var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
// The character value of the second digit is added to the product
value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
// The sum is then stored as 11-bit binary number
bitBuffer.put(value, 11)
}
// If the number of input data characters is not a multiple of two,
// the character value of the final character is encoded as a 6-bit binary number.
if (this.data.length % 2) {
bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
}
}
module.exports = AlphanumericData
},{"./mode":14}],4:[function(require,module,exports){
function BitBuffer () {
this.buffer = []
this.length = 0
}
BitBuffer.prototype = {
get: function (index) {
var bufIndex = Math.floor(index / 8)
return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
},
put: function (num, length) {
for (var i = 0; i < length; i++) {
this.putBit(((num >>> (length - i - 1)) & 1) === 1)
}
},
getLengthInBits: function () {
return this.length
},
putBit: function (bit) {
var bufIndex = Math.floor(this.length / 8)
if (this.buffer.length <= bufIndex) {
this.buffer.push(0)
}
if (bit) {
this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))
}
this.length++
}
}
module.exports = BitBuffer
},{}],5:[function(require,module,exports){
var BufferUtil = require('../utils/buffer')
/**
* Helper class to handle QR Code symbol modules
*
* @param {Number} size Symbol size
*/
function BitMatrix (size) {
if (!size || size < 1) {
throw new Error('BitMatrix size must be defined and greater than 0')
}
this.size = size
this.data = BufferUtil.alloc(size * size)
this.reservedBit = BufferUtil.alloc(size * size)
}
/**
* Set bit value at specified location
* If reserved flag is set, this bit will be ignored during masking process
*
* @param {Number} row
* @param {Number} col
* @param {Boolean} value
* @param {Boolean} reserved
*/
BitMatrix.prototype.set = function (row, col, value, reserved) {
var index = row * this.size + col
this.data[index] = value
if (reserved) this.reservedBit[index] = true
}
/**
* Returns bit value at specified location
*
* @param {Number} row
* @param {Number} col
* @return {Boolean}
*/
BitMatrix.prototype.get = function (row, col) {
return this.data[row * this.size + col]
}
/**
* Applies xor operator at specified location
* (used during masking process)
*
* @param {Number} row
* @param {Number} col
* @param {Boolean} value
*/
BitMatrix.prototype.xor = function (row, col, value) {
this.data[row * this.size + col] ^= value
}
/**
* Check if bit at specified location is reserved
*
* @param {Number} row
* @param {Number} col
* @return {Boolean}
*/
BitMatrix.prototype.isReserved = function (row, col) {
return this.reservedBit[row * this.size + col]
}
module.exports = BitMatrix
},{"../utils/buffer":28}],6:[function(require,module,exports){
var BufferUtil = require('../utils/buffer')
var Mode = require('./mode')
function ByteData (data) {
this.mode = Mode.BYTE
this.data = BufferUtil.from(data)
}
ByteData.getBitsLength = function getBitsLength (length) {
return length * 8
}
ByteData.prototype.getLength = function getLength () {
return this.data.length
}
ByteData.prototype.getBitsLength = function getBitsLength () {
return ByteData.getBitsLength(this.data.length)
}
ByteData.prototype.write = function (bitBuffer) {
for (var i = 0, l = this.data.length; i < l; i++) {
bitBuffer.put(this.data[i], 8)
}
}
module.exports = ByteData
},{"../utils/buffer":28,"./mode":14}],7:[function(require,module,exports){
var ECLevel = require('./error-correction-level')
var EC_BLOCKS_TABLE = [
// L M Q H
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 2, 2,
1, 2, 2, 4,
1, 2, 4, 4,
2, 4, 4, 4,
2, 4, 6, 5,
2, 4, 6, 6,
2, 5, 8, 8,
4, 5, 8, 8,
4, 5, 8, 11,
4, 8, 10, 11,
4, 9, 12, 16,
4, 9, 16, 16,
6, 10, 12, 18,
6, 10, 17, 16,
6, 11, 16, 19,
6, 13, 18, 21,
7, 14, 21, 25,
8, 16, 20, 25,
8, 17, 23, 25,
9, 17, 23, 34,
9, 18, 25, 30,
10, 20, 27, 32,
12, 21, 29, 35,
12, 23, 34, 37,
12, 25, 34, 40,
13, 26, 35, 42,
14, 28, 38, 45,
15, 29, 40, 48,
16, 31, 43, 51,
17, 33, 45, 54,
18, 35, 48, 57,
19, 37, 51, 60,
19, 38, 53, 63,
20, 40, 56, 66,
21, 43, 59, 70,
22, 45, 62, 74,
24, 47, 65, 77,
25, 49, 68, 81
]
var EC_CODEWORDS_TABLE = [
// L M Q H
7, 10, 13, 17,
10, 16, 22, 28,
15, 26, 36, 44,
20, 36, 52, 64,
26, 48, 72, 88,
36, 64, 96, 112,
40, 72, 108, 130,
48, 88, 132, 156,
60, 110, 160, 192,
72, 130, 192, 224,
80, 150, 224, 264,
96, 176, 260, 308,
104, 198, 288, 352,
120, 216, 320, 384,
132, 240, 360, 432,
144, 280, 408, 480,
168, 308, 448, 532,
180, 338, 504, 588,
196, 364, 546, 650,
224, 416, 600, 700,
224, 442, 644, 750,
252, 476, 690, 816,
270, 504, 750, 900,
300, 560, 810, 960,
312, 588, 870, 1050,
336, 644, 952, 1110,
360, 700, 1020, 1200,
390, 728, 1050, 1260,
420, 784, 1140, 1350,
450, 812, 1200, 1440,
480, 868, 1290, 1530,
510, 924, 1350, 1620,
540, 980, 1440, 1710,
570, 1036, 1530, 1800,
570, 1064, 1590, 1890,
600, 1120, 1680, 1980,
630, 1204, 1770, 2100,
660, 1260, 1860, 2220,
720, 1316, 1950, 2310,
750, 1372, 2040, 2430
]
/**
* Returns the number of error correction block that the QR Code should contain
* for the specified version and error correction level.
*
* @param {Number} version QR Code version
* @param {Number} errorCorrectionLevel Error correction level
* @return {Number} Number of error correction blocks
*/
exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
switch (errorCorrectionLevel) {
case ECLevel.L:
return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
case ECLevel.M:
return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
case ECLevel.Q:
return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
case ECLevel.H:
return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
default:
return undefined
}
}
/**
* Returns the number of error correction codewords to use for the specified
* version and error correction level.
*
* @param {Number} version QR Code version
* @param {Number} errorCorrectionLevel Error correction level
* @return {Number} Number of error correction codewords
*/
exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
switch (errorCorrectionLevel) {
case ECLevel.L:
return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
case ECLevel.M:
return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
case ECLevel.Q:
return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
case ECLevel.H:
return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
default:
return undefined
}
}
},{"./error-correction-level":8}],8:[function(require,module,exports){
exports.L = { bit: 1 }
exports.M = { bit: 0 }
exports.Q = { bit: 3 }
exports.H = { bit: 2 }
function fromString (string) {
if (typeof string !== 'string') {
throw new Error('Param is not a string')
}
var lcStr = string.toLowerCase()
switch (lcStr) {
case 'l':
case 'low':
return exports.L
case 'm':
case 'medium':
return exports.M
case 'q':
case 'quartile':
return exports.Q
case 'h':
case 'high':
return exports.H
default:
throw new Error('Unknown EC Level: ' + string)
}
}
exports.isValid = function isValid (level) {
return level && typeof level.bit !== 'undefined' &&
level.bit >= 0 && level.bit < 4
}
exports.from = function from (value, defaultValue) {
if (exports.isValid(value)) {
return value
}
try {
return fromString(value)
} catch (e) {
return defaultValue
}
}
},{}],9:[function(require,module,exports){
var getSymbolSize = require('./utils').getSymbolSize
var FINDER_PATTERN_SIZE = 7
/**
* Returns an array containing the positions of each finder pattern.
* Each array's element represent the top-left point of the pattern as (x, y) coordinates
*
* @param {Number} version QR Code version
* @return {Array} Array of coordinates
*/
exports.getPositions = function getPositions (version) {
var size = getSymbolSize(version)
return [
// top-left
[0, 0],
// top-right
[size - FINDER_PATTERN_SIZE, 0],
// bottom-left
[0, size - FINDER_PATTERN_SIZE]
]
}
},{"./utils":21}],10:[function(require,module,exports){
var Utils = require('./utils')
var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
var G15_BCH = Utils.getBCHDigit(G15)
/**
* Returns format information with relative error correction bits
*
* The format information is a 15-bit sequence containing 5 data bits,
* with 10 error correction bits calculated using the (15, 5) BCH code.
*
* @param {Number} errorCorrectionLevel Error correction level
* @param {Number} mask Mask pattern
* @return {Number} Encoded format information bits
*/
exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
var data = ((errorCorrectionLevel.bit << 3) | mask)
var d = data << 10
while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))
}
// xor final data with mask pattern in order to ensure that
// no combination of Error Correction Level and data mask pattern
// will result in an all-zero data string
return ((data << 10) | d) ^ G15_MASK
}
},{"./utils":21}],11:[function(require,module,exports){
var BufferUtil = require('../utils/buffer')
var EXP_TABLE = BufferUtil.alloc(512)
var LOG_TABLE = BufferUtil.alloc(256)
/**
* Precompute the log and anti-log tables for faster computation later
*
* For each possible value in the galois field 2^8, we will pre-compute
* the logarithm and anti-logarithm (exponential) of this value
*
* ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
*/
;(function initTables () {
var x = 1
for (var i = 0; i < 255; i++) {
EXP_TABLE[i] = x
LOG_TABLE[x] = i
x <<= 1 // multiply by 2
// The QR code specification says to use byte-wise modulo 100011101 arithmetic.
// This means that when a number is 256 or larger, it should be XORed with 0x11D.
if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
x ^= 0x11D
}
}
// Optimization: double the size of the anti-log table so that we don't need to mod 255 to
// stay inside the bounds (because we will mainly use this table for the multiplication of
// two GF numbers, no more).
// @see {@link mul}
for (i = 255; i < 512; i++) {
EXP_TABLE[i] = EXP_TABLE[i - 255]
}
}())
/**
* Returns log value of n inside Galois Field
*
* @param {Number} n
* @return {Number}
*/
exports.log = function log (n) {
if (n < 1) throw new Error('log(' + n + ')')
return LOG_TABLE[n]
}
/**
* Returns anti-log value of n inside Galois Field
*
* @param {Number} n
* @return {Number}
*/
exports.exp = function exp (n) {
return EXP_TABLE[n]
}
/**
* Multiplies two number inside Galois Field
*
* @param {Number} x
* @param {Number} y
* @return {Number}
*/
exports.mul = function mul (x, y) {
if (x === 0 || y === 0) return 0
// should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
// @see {@link initTables}
return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
}
},{"../utils/buffer":28}],12:[function(require,module,exports){
var Mode = require('./mode')
var Utils = require('./utils')
function KanjiData (data) {
this.mode = Mode.KANJI
this.data = data
}
KanjiData.getBitsLength = function getBitsLength (length) {
return length * 13
}
KanjiData.prototype.getLength = function getLength () {
return this.data.length
}
KanjiData.prototype.getBitsLength = function getBitsLength () {
return KanjiData.getBitsLength(this.data.length)
}
KanjiData.prototype.write = function (bitBuffer) {
var i
// In the Shift JIS system, Kanji characters are represented by a two byte combination.
// These byte values are shifted from the JIS X 0208 values.
// JIS X 0208 gives details of the shift coded representation.
for (i = 0; i < this.data.length; i++) {
var value = Utils.toSJIS(this.data[i])
// For characters with Shift JIS values from 0x8140 to 0x9FFC:
if (value >= 0x8140 && value <= 0x9FFC) {
// Subtract 0x8140 from Shift JIS value
value -= 0x8140
// For characters with Shift JIS values from 0xE040 to 0xEBBF
} else if (value >= 0xE040 && value <= 0xEBBF) {
// Subtract 0xC140 from Shift JIS value
value -= 0xC140
} else {
throw new Error(
'Invalid SJIS character: ' + this.data[i] + '\n' +
'Make sure your charset is UTF-8')
}
// Multiply most significant byte of result by 0xC0
// and add least significant byte to product
value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)
// Convert result to a 13-bit binary string
bitBuffer.put(value, 13)
}
}
module.exports = KanjiData
},{"./mode":14,"./utils":21}],13:[function(require,module,exports){
/**
* Data mask pattern reference
* @type {Object}
*/
exports.Patterns = {
PATTERN000: 0,
PATTERN001: 1,
PATTERN010: 2,
PATTERN011: 3,
PATTERN100: 4,
PATTERN101: 5,
PATTERN110: 6,
PATTERN111: 7
}
/**
* Weighted penalty scores for the undesirable features
* @type {Object}
*/
var PenaltyScores = {
N1: 3,
N2: 3,
N3: 40,
N4: 10
}
/**
* Check if mask pattern value is valid
*
* @param {Number} mask Mask pattern
* @return {Boolean} true if valid, false otherwise
*/
exports.isValid = function isValid (mask) {
return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
}
/**
* Returns mask pattern from a value.
* If value is not valid, returns undefined
*
* @param {Number|String} value Mask pattern value
* @return {Number} Valid mask pattern or undefined
*/
exports.from = function from (value) {
return exports.isValid(value) ? parseInt(value, 10) : undefined
}
/**
* Find adjacent modules in row/column with the same color
* and assign a penalty value.
*
* Points: N1 + i
* i is the amount by which the number of adjacent modules of the same color exceeds 5
*/
exports.getPenaltyN1 = function getPenaltyN1 (data) {
var size = data.size
var points = 0
var sameCountCol = 0
var sameCountRow = 0
var lastCol = null
var lastRow = null
for (var row = 0; row < size; row++) {
sameCountCol = sameCountRow = 0
lastCol = lastRow = null
for (var col = 0; col < size; col++) {
var module = data.get(row, col)
if (module === lastCol) {
sameCountCol++
} else {
if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
lastCol = module
sameCountCol = 1
}
module = data.get(col, row)
if (module === lastRow) {
sameCountRow++
} else {
if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
lastRow = module
sameCountRow = 1
}
}
if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
}
return points
}
/**
* Find 2x2 blocks with the same color and assign a penalty value
*
* Points: N2 * (m - 1) * (n - 1)
*/
exports.getPenaltyN2 = function getPenaltyN2 (data) {
var size = data.size
var points = 0
for (var row = 0; row < size - 1; row++) {
for (var col = 0; col < size - 1; col++) {
var last = data.get(row, col) +
data.get(row, col + 1) +
data.get(row + 1, col) +
data.get(row + 1, col + 1)
if (last === 4 || last === 0) points++
}
}
return points * PenaltyScores.N2
}
/**
* Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
* preceded or followed by light area 4 modules wide
*
* Points: N3 * number of pattern found
*/
exports.getPenaltyN3 = function getPenaltyN3 (data) {
var size = data.size
var points = 0
var bitsCol = 0
var bitsRow = 0
for (var row = 0; row < size; row++) {
bitsCol = bitsRow = 0
for (var col = 0; col < size; col++) {
bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)
if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++
bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)
if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++
}
}
return points * PenaltyScores.N3
}
/**
* Calculate proportion of dark modules in entire symbol
*
* Points: N4 * k
*
* k is the rating of the deviation of the proportion of dark modules
* in the symbol from 50% in steps of 5%
*/
exports.getPenaltyN4 = function getPenaltyN4 (data) {
var darkCount = 0
var modulesCount = data.data.length
for (var i = 0; i < modulesCount; i++) darkCount += data.data[i]
var k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)
return k * PenaltyScores.N4
}
/**
* Return mask value at given position
*
* @param {Number} maskPattern Pattern reference value
* @param {Number} i Row
* @param {Number} j Column
* @return {Boolean} Mask value
*/
function getMaskAt (maskPattern, i, j) {
switch (maskPattern) {
case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
case exports.Patterns.PATTERN001: return i % 2 === 0
case exports.Patterns.PATTERN010: return j % 3 === 0
case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
default: throw new Error('bad maskPattern:' + maskPattern)
}
}
/**
* Apply a mask pattern to a BitMatrix
*
* @param {Number} pattern Pattern reference number
* @param {BitMatrix} data BitMatrix data
*/
exports.applyMask = function applyMask (pattern, data) {
var size = data.size
for (var col = 0; col < size; col++) {
for (var row = 0; row < size; row++) {
if (data.isReserved(row, col)) continue
data.xor(row, col, getMaskAt(pattern, row, col))
}
}
}
/**
* Returns the best mask pattern for data
*
* @param {BitMatrix} data
* @return {Number} Mask pattern reference number
*/
exports.getBestMask = function getBestMask (data, setupFormatFunc) {
var numPatterns = Object.keys(exports.Patterns).length
var bestPattern = 0
var lowerPenalty = Infinity
for (var p = 0; p < numPatterns; p++) {
setupFormatFunc(p)
exports.applyMask(p, data)
// Calculate penalty
var penalty =
exports.getPenaltyN1(data) +
exports.getPenaltyN2(data) +
exports.getPenaltyN3(data) +
exports.getPenaltyN4(data)
// Undo previously applied mask
exports.applyMask(p, data)
if (penalty < lowerPenalty) {
lowerPenalty = penalty
bestPattern = p
}
}
return bestPattern
}
},{}],14:[function(require,module,exports){
var VersionCheck = require('./version-check')
var Regex = require('./regex')
/**
* Numeric mode encodes data from the decimal digit set (0 - 9)
* (byte values 30HEX to 39HEX).
* Normally, 3 data characters are represented by 10 bits.
*
* @type {Object}
*/
exports.NUMERIC = {
id: 'Numeric',
bit: 1 << 0,
ccBits: [10, 12, 14]
}
/**
* Alphanumeric mode encodes data from a set of 45 characters,
* i.e. 10 numeric digits (0 - 9),
* 26 alphabetic characters (A - Z),
* and 9 symbols (SP, $, %, *, +, -, ., /, :).
* Normally, two input characters are represented by 11 bits.
*
* @type {Object}
*/
exports.ALPHANUMERIC = {
id: 'Alphanumeric',
bit: 1 << 1,
ccBits: [9, 11, 13]
}
/**
* In byte mode, data is encoded at 8 bits per character.
*
* @type {Object}
*/
exports.BYTE = {
id: 'Byte',
bit: 1 << 2,
ccBits: [8, 16, 16]
}
/**
* The Kanji mode efficiently encodes Kanji characters in accordance with
* the Shift JIS system based on JIS X 0208.
* The Shift JIS values are shifted from the JIS X 0208 values.
* JIS X 0208 gives details of the shift coded representation.
* Each two-byte character value is compacted to a 13-bit binary codeword.
*
* @type {Object}
*/
exports.KANJI = {
id: 'Kanji',
bit: 1 << 3,
ccBits: [8, 10, 12]
}
/**
* Mixed mode will contain a sequences of data in a combination of any of
* the modes described above
*
* @type {Object}
*/
exports.MIXED = {
bit: -1
}
/**
* Returns the number of bits needed to store the data length
* according to QR Code specifications.
*
* @param {Mode} mode Data mode
* @param {Number} version QR Code version
* @return {Number} Number of bits
*/
exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
if (!VersionCheck.isValid(version)) {
throw new Error('Invalid version: ' + version)
}
if (version >= 1 && version < 10) return mode.ccBits[0]
else if (version < 27) return mode.ccBits[1]
return mode.ccBits[2]
}
/**
* Returns the most efficient mode to store the specified data
*
* @param {String} dataStr Input data string
* @return {Mode} Best mode
*/
exports.getBestModeForData = function getBestModeForData (dataStr) {
if (Regex.testNumeric(dataStr)) return exports.NUMERIC
else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
else if (Regex.testKanji(dataStr)) return exports.KANJI
else return exports.BYTE