@bounded-sh/client 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +298 -0
  2. package/dist/auth/hooks/useAuth.d.ts +8 -0
  3. package/dist/auth/index.d.ts +73 -0
  4. package/dist/auth/oidc-auth.d.ts +27 -0
  5. package/dist/auth/providers/email-auth-provider.d.ts +38 -0
  6. package/dist/auth/providers/guest-auth-provider.d.ts +14 -0
  7. package/dist/auth/providers/guest-keystore.d.ts +12 -0
  8. package/dist/auth/providers/mock-auth-provider.d.ts +49 -0
  9. package/dist/auth/providers/offchain-auth-provider.d.ts +56 -0
  10. package/dist/auth/providers/phantom-wallet-provider.d.ts +117 -0
  11. package/dist/auth/providers/privy-expo-provider.d.ts +115 -0
  12. package/dist/auth/providers/privy-wallet-provider.d.ts +80 -0
  13. package/dist/auth/providers/sol/sol-utils.d.ts +2 -0
  14. package/dist/auth/providers/solana-mobile-wallet-provider.d.ts +155 -0
  15. package/dist/auth/providers/transaction-utils.d.ts +10 -0
  16. package/dist/global.d.ts +13 -0
  17. package/dist/index-BHTfW8CV.esm.js +16091 -0
  18. package/dist/index-BHTfW8CV.esm.js.map +1 -0
  19. package/dist/index-C1VOdmRN.js +16130 -0
  20. package/dist/index-C1VOdmRN.js.map +1 -0
  21. package/dist/index-CT2j1oic.esm.js +16089 -0
  22. package/dist/index-CT2j1oic.esm.js.map +1 -0
  23. package/dist/index-VGx-869x.js +23572 -0
  24. package/dist/index-VGx-869x.js.map +1 -0
  25. package/dist/index-o5Hv9pfS.esm.js +23456 -0
  26. package/dist/index-o5Hv9pfS.esm.js.map +1 -0
  27. package/dist/index-sKqrgk0t.js +16132 -0
  28. package/dist/index-sKqrgk0t.js.map +1 -0
  29. package/dist/index.browser-BJZ7fYwv.js +5081 -0
  30. package/dist/index.browser-BJZ7fYwv.js.map +1 -0
  31. package/dist/index.browser-DaNhOhkQ.esm.js +4220 -0
  32. package/dist/index.browser-DaNhOhkQ.esm.js.map +1 -0
  33. package/dist/index.browser-DhAcjdpV.esm.js +5071 -0
  34. package/dist/index.browser-DhAcjdpV.esm.js.map +1 -0
  35. package/dist/index.browser-utVKQsEC.js +4225 -0
  36. package/dist/index.browser-utVKQsEC.js.map +1 -0
  37. package/dist/index.d.ts +21 -0
  38. package/dist/index.esm.js +8 -0
  39. package/dist/index.esm.js.map +1 -0
  40. package/dist/index.js +105 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/index.native-B5IBOdv_.js +19684 -0
  43. package/dist/index.native-B5IBOdv_.js.map +1 -0
  44. package/dist/index.native-JPUkdHJj.esm.js +19565 -0
  45. package/dist/index.native-JPUkdHJj.esm.js.map +1 -0
  46. package/dist/index.native.d.ts +26 -0
  47. package/dist/index.native.esm.js +6 -0
  48. package/dist/index.native.esm.js.map +1 -0
  49. package/dist/index.native.js +98 -0
  50. package/dist/index.native.js.map +1 -0
  51. package/dist/phantom-wallet-provider-CDLyxrih.js +1466 -0
  52. package/dist/phantom-wallet-provider-CDLyxrih.js.map +1 -0
  53. package/dist/phantom-wallet-provider-DMlaSrAl.esm.js +1445 -0
  54. package/dist/phantom-wallet-provider-DMlaSrAl.esm.js.map +1 -0
  55. package/dist/platform.d.ts +81 -0
  56. package/dist/privy-wallet-provider-DiHHTDbZ.js +956 -0
  57. package/dist/privy-wallet-provider-DiHHTDbZ.js.map +1 -0
  58. package/dist/privy-wallet-provider-nR52lXzI.esm.js +933 -0
  59. package/dist/privy-wallet-provider-nR52lXzI.esm.js.map +1 -0
  60. package/dist/solana-mobile-wallet-provider-B4CeMMQd.esm.js +1460 -0
  61. package/dist/solana-mobile-wallet-provider-B4CeMMQd.esm.js.map +1 -0
  62. package/dist/solana-mobile-wallet-provider-BYMfFjZb.js +1481 -0
  63. package/dist/solana-mobile-wallet-provider-BYMfFjZb.js.map +1 -0
  64. package/dist/utils.d.ts +1 -0
  65. package/package.json +100 -0
@@ -0,0 +1,4225 @@
1
+ 'use strict';
2
+
3
+ var mobileWalletAdapterProtocol = require('@solana-mobile/mobile-wallet-adapter-protocol');
4
+ var index_native = require('./index.native-B5IBOdv_.js');
5
+ require('axios');
6
+ require('@solana/web3.js');
7
+ require('@coral-xyz/anchor');
8
+ require('react');
9
+
10
+ /** Name of the feature. */
11
+ const SolanaSignAndSendTransaction = 'solana:signAndSendTransaction';
12
+
13
+ /** Name of the feature. */
14
+ const SolanaSignIn = 'solana:signIn';
15
+
16
+ /** Name of the feature. */
17
+ const SolanaSignMessage = 'solana:signMessage';
18
+
19
+ /** Name of the feature. */
20
+ const SolanaSignTransaction = 'solana:signTransaction';
21
+
22
+ /** Name of the feature. */
23
+ const StandardConnect = 'standard:connect';
24
+
25
+ /** Name of the feature. */
26
+ const StandardDisconnect = 'standard:disconnect';
27
+
28
+ /** Name of the feature. */
29
+ const StandardEvents = 'standard:events';
30
+
31
+ var browser = {};
32
+
33
+ var canPromise;
34
+ var hasRequiredCanPromise;
35
+
36
+ function requireCanPromise () {
37
+ if (hasRequiredCanPromise) return canPromise;
38
+ hasRequiredCanPromise = 1;
39
+ // can-promise has a crash in some versions of react native that dont have
40
+ // standard global objects
41
+ // https://github.com/soldair/node-qrcode/issues/157
42
+
43
+ canPromise = function () {
44
+ return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
45
+ };
46
+ return canPromise;
47
+ }
48
+
49
+ var qrcode = {};
50
+
51
+ var utils$1 = {};
52
+
53
+ var hasRequiredUtils$1;
54
+
55
+ function requireUtils$1 () {
56
+ if (hasRequiredUtils$1) return utils$1;
57
+ hasRequiredUtils$1 = 1;
58
+ let toSJISFunction;
59
+ const CODEWORDS_COUNT = [
60
+ 0, // Not used
61
+ 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
62
+ 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
63
+ 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
64
+ 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
65
+ ];
66
+
67
+ /**
68
+ * Returns the QR Code size for the specified version
69
+ *
70
+ * @param {Number} version QR Code version
71
+ * @return {Number} size of QR code
72
+ */
73
+ utils$1.getSymbolSize = function getSymbolSize (version) {
74
+ if (!version) throw new Error('"version" cannot be null or undefined')
75
+ if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
76
+ return version * 4 + 17
77
+ };
78
+
79
+ /**
80
+ * Returns the total number of codewords used to store data and EC information.
81
+ *
82
+ * @param {Number} version QR Code version
83
+ * @return {Number} Data length in bits
84
+ */
85
+ utils$1.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
86
+ return CODEWORDS_COUNT[version]
87
+ };
88
+
89
+ /**
90
+ * Encode data with Bose-Chaudhuri-Hocquenghem
91
+ *
92
+ * @param {Number} data Value to encode
93
+ * @return {Number} Encoded value
94
+ */
95
+ utils$1.getBCHDigit = function (data) {
96
+ let digit = 0;
97
+
98
+ while (data !== 0) {
99
+ digit++;
100
+ data >>>= 1;
101
+ }
102
+
103
+ return digit
104
+ };
105
+
106
+ utils$1.setToSJISFunction = function setToSJISFunction (f) {
107
+ if (typeof f !== 'function') {
108
+ throw new Error('"toSJISFunc" is not a valid function.')
109
+ }
110
+
111
+ toSJISFunction = f;
112
+ };
113
+
114
+ utils$1.isKanjiModeEnabled = function () {
115
+ return typeof toSJISFunction !== 'undefined'
116
+ };
117
+
118
+ utils$1.toSJIS = function toSJIS (kanji) {
119
+ return toSJISFunction(kanji)
120
+ };
121
+ return utils$1;
122
+ }
123
+
124
+ var errorCorrectionLevel = {};
125
+
126
+ var hasRequiredErrorCorrectionLevel;
127
+
128
+ function requireErrorCorrectionLevel () {
129
+ if (hasRequiredErrorCorrectionLevel) return errorCorrectionLevel;
130
+ hasRequiredErrorCorrectionLevel = 1;
131
+ (function (exports$1) {
132
+ exports$1.L = { bit: 1 };
133
+ exports$1.M = { bit: 0 };
134
+ exports$1.Q = { bit: 3 };
135
+ exports$1.H = { bit: 2 };
136
+
137
+ function fromString (string) {
138
+ if (typeof string !== 'string') {
139
+ throw new Error('Param is not a string')
140
+ }
141
+
142
+ const lcStr = string.toLowerCase();
143
+
144
+ switch (lcStr) {
145
+ case 'l':
146
+ case 'low':
147
+ return exports$1.L
148
+
149
+ case 'm':
150
+ case 'medium':
151
+ return exports$1.M
152
+
153
+ case 'q':
154
+ case 'quartile':
155
+ return exports$1.Q
156
+
157
+ case 'h':
158
+ case 'high':
159
+ return exports$1.H
160
+
161
+ default:
162
+ throw new Error('Unknown EC Level: ' + string)
163
+ }
164
+ }
165
+
166
+ exports$1.isValid = function isValid (level) {
167
+ return level && typeof level.bit !== 'undefined' &&
168
+ level.bit >= 0 && level.bit < 4
169
+ };
170
+
171
+ exports$1.from = function from (value, defaultValue) {
172
+ if (exports$1.isValid(value)) {
173
+ return value
174
+ }
175
+
176
+ try {
177
+ return fromString(value)
178
+ } catch (e) {
179
+ return defaultValue
180
+ }
181
+ };
182
+ } (errorCorrectionLevel));
183
+ return errorCorrectionLevel;
184
+ }
185
+
186
+ var bitBuffer;
187
+ var hasRequiredBitBuffer;
188
+
189
+ function requireBitBuffer () {
190
+ if (hasRequiredBitBuffer) return bitBuffer;
191
+ hasRequiredBitBuffer = 1;
192
+ function BitBuffer () {
193
+ this.buffer = [];
194
+ this.length = 0;
195
+ }
196
+
197
+ BitBuffer.prototype = {
198
+
199
+ get: function (index) {
200
+ const bufIndex = Math.floor(index / 8);
201
+ return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
202
+ },
203
+
204
+ put: function (num, length) {
205
+ for (let i = 0; i < length; i++) {
206
+ this.putBit(((num >>> (length - i - 1)) & 1) === 1);
207
+ }
208
+ },
209
+
210
+ getLengthInBits: function () {
211
+ return this.length
212
+ },
213
+
214
+ putBit: function (bit) {
215
+ const bufIndex = Math.floor(this.length / 8);
216
+ if (this.buffer.length <= bufIndex) {
217
+ this.buffer.push(0);
218
+ }
219
+
220
+ if (bit) {
221
+ this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
222
+ }
223
+
224
+ this.length++;
225
+ }
226
+ };
227
+
228
+ bitBuffer = BitBuffer;
229
+ return bitBuffer;
230
+ }
231
+
232
+ /**
233
+ * Helper class to handle QR Code symbol modules
234
+ *
235
+ * @param {Number} size Symbol size
236
+ */
237
+
238
+ var bitMatrix;
239
+ var hasRequiredBitMatrix;
240
+
241
+ function requireBitMatrix () {
242
+ if (hasRequiredBitMatrix) return bitMatrix;
243
+ hasRequiredBitMatrix = 1;
244
+ function BitMatrix (size) {
245
+ if (!size || size < 1) {
246
+ throw new Error('BitMatrix size must be defined and greater than 0')
247
+ }
248
+
249
+ this.size = size;
250
+ this.data = new Uint8Array(size * size);
251
+ this.reservedBit = new Uint8Array(size * size);
252
+ }
253
+
254
+ /**
255
+ * Set bit value at specified location
256
+ * If reserved flag is set, this bit will be ignored during masking process
257
+ *
258
+ * @param {Number} row
259
+ * @param {Number} col
260
+ * @param {Boolean} value
261
+ * @param {Boolean} reserved
262
+ */
263
+ BitMatrix.prototype.set = function (row, col, value, reserved) {
264
+ const index = row * this.size + col;
265
+ this.data[index] = value;
266
+ if (reserved) this.reservedBit[index] = true;
267
+ };
268
+
269
+ /**
270
+ * Returns bit value at specified location
271
+ *
272
+ * @param {Number} row
273
+ * @param {Number} col
274
+ * @return {Boolean}
275
+ */
276
+ BitMatrix.prototype.get = function (row, col) {
277
+ return this.data[row * this.size + col]
278
+ };
279
+
280
+ /**
281
+ * Applies xor operator at specified location
282
+ * (used during masking process)
283
+ *
284
+ * @param {Number} row
285
+ * @param {Number} col
286
+ * @param {Boolean} value
287
+ */
288
+ BitMatrix.prototype.xor = function (row, col, value) {
289
+ this.data[row * this.size + col] ^= value;
290
+ };
291
+
292
+ /**
293
+ * Check if bit at specified location is reserved
294
+ *
295
+ * @param {Number} row
296
+ * @param {Number} col
297
+ * @return {Boolean}
298
+ */
299
+ BitMatrix.prototype.isReserved = function (row, col) {
300
+ return this.reservedBit[row * this.size + col]
301
+ };
302
+
303
+ bitMatrix = BitMatrix;
304
+ return bitMatrix;
305
+ }
306
+
307
+ var alignmentPattern = {};
308
+
309
+ /**
310
+ * Alignment pattern are fixed reference pattern in defined positions
311
+ * in a matrix symbology, which enables the decode software to re-synchronise
312
+ * the coordinate mapping of the image modules in the event of moderate amounts
313
+ * of distortion of the image.
314
+ *
315
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
316
+ * and their number depends on the symbol version.
317
+ */
318
+
319
+ var hasRequiredAlignmentPattern;
320
+
321
+ function requireAlignmentPattern () {
322
+ if (hasRequiredAlignmentPattern) return alignmentPattern;
323
+ hasRequiredAlignmentPattern = 1;
324
+ (function (exports$1) {
325
+ const getSymbolSize = requireUtils$1().getSymbolSize;
326
+
327
+ /**
328
+ * Calculate the row/column coordinates of the center module of each alignment pattern
329
+ * for the specified QR Code version.
330
+ *
331
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
332
+ * running from the top left corner of the symbol to the bottom right corner.
333
+ *
334
+ * Since positions are simmetrical only half of the coordinates are returned.
335
+ * Each item of the array will represent in turn the x and y coordinate.
336
+ * @see {@link getPositions}
337
+ *
338
+ * @param {Number} version QR Code version
339
+ * @return {Array} Array of coordinate
340
+ */
341
+ exports$1.getRowColCoords = function getRowColCoords (version) {
342
+ if (version === 1) return []
343
+
344
+ const posCount = Math.floor(version / 7) + 2;
345
+ const size = getSymbolSize(version);
346
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
347
+ const positions = [size - 7]; // Last coord is always (size - 7)
348
+
349
+ for (let i = 1; i < posCount - 1; i++) {
350
+ positions[i] = positions[i - 1] - intervals;
351
+ }
352
+
353
+ positions.push(6); // First coord is always 6
354
+
355
+ return positions.reverse()
356
+ };
357
+
358
+ /**
359
+ * Returns an array containing the positions of each alignment pattern.
360
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
361
+ *
362
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
363
+ * and filtering out the items that overlaps with finder pattern
364
+ *
365
+ * @example
366
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
367
+ * The alignment patterns, therefore, are to be centered on (row, column)
368
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
369
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
370
+ * and are not therefore used for alignment patterns.
371
+ *
372
+ * let pos = getPositions(7)
373
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
374
+ *
375
+ * @param {Number} version QR Code version
376
+ * @return {Array} Array of coordinates
377
+ */
378
+ exports$1.getPositions = function getPositions (version) {
379
+ const coords = [];
380
+ const pos = exports$1.getRowColCoords(version);
381
+ const posLength = pos.length;
382
+
383
+ for (let i = 0; i < posLength; i++) {
384
+ for (let j = 0; j < posLength; j++) {
385
+ // Skip if position is occupied by finder patterns
386
+ if ((i === 0 && j === 0) || // top-left
387
+ (i === 0 && j === posLength - 1) || // bottom-left
388
+ (i === posLength - 1 && j === 0)) { // top-right
389
+ continue
390
+ }
391
+
392
+ coords.push([pos[i], pos[j]]);
393
+ }
394
+ }
395
+
396
+ return coords
397
+ };
398
+ } (alignmentPattern));
399
+ return alignmentPattern;
400
+ }
401
+
402
+ var finderPattern = {};
403
+
404
+ var hasRequiredFinderPattern;
405
+
406
+ function requireFinderPattern () {
407
+ if (hasRequiredFinderPattern) return finderPattern;
408
+ hasRequiredFinderPattern = 1;
409
+ const getSymbolSize = requireUtils$1().getSymbolSize;
410
+ const FINDER_PATTERN_SIZE = 7;
411
+
412
+ /**
413
+ * Returns an array containing the positions of each finder pattern.
414
+ * Each array's element represent the top-left point of the pattern as (x, y) coordinates
415
+ *
416
+ * @param {Number} version QR Code version
417
+ * @return {Array} Array of coordinates
418
+ */
419
+ finderPattern.getPositions = function getPositions (version) {
420
+ const size = getSymbolSize(version);
421
+
422
+ return [
423
+ // top-left
424
+ [0, 0],
425
+ // top-right
426
+ [size - FINDER_PATTERN_SIZE, 0],
427
+ // bottom-left
428
+ [0, size - FINDER_PATTERN_SIZE]
429
+ ]
430
+ };
431
+ return finderPattern;
432
+ }
433
+
434
+ var maskPattern = {};
435
+
436
+ /**
437
+ * Data mask pattern reference
438
+ * @type {Object}
439
+ */
440
+
441
+ var hasRequiredMaskPattern;
442
+
443
+ function requireMaskPattern () {
444
+ if (hasRequiredMaskPattern) return maskPattern;
445
+ hasRequiredMaskPattern = 1;
446
+ (function (exports$1) {
447
+ exports$1.Patterns = {
448
+ PATTERN000: 0,
449
+ PATTERN001: 1,
450
+ PATTERN010: 2,
451
+ PATTERN011: 3,
452
+ PATTERN100: 4,
453
+ PATTERN101: 5,
454
+ PATTERN110: 6,
455
+ PATTERN111: 7
456
+ };
457
+
458
+ /**
459
+ * Weighted penalty scores for the undesirable features
460
+ * @type {Object}
461
+ */
462
+ const PenaltyScores = {
463
+ N1: 3,
464
+ N2: 3,
465
+ N3: 40,
466
+ N4: 10
467
+ };
468
+
469
+ /**
470
+ * Check if mask pattern value is valid
471
+ *
472
+ * @param {Number} mask Mask pattern
473
+ * @return {Boolean} true if valid, false otherwise
474
+ */
475
+ exports$1.isValid = function isValid (mask) {
476
+ return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
477
+ };
478
+
479
+ /**
480
+ * Returns mask pattern from a value.
481
+ * If value is not valid, returns undefined
482
+ *
483
+ * @param {Number|String} value Mask pattern value
484
+ * @return {Number} Valid mask pattern or undefined
485
+ */
486
+ exports$1.from = function from (value) {
487
+ return exports$1.isValid(value) ? parseInt(value, 10) : undefined
488
+ };
489
+
490
+ /**
491
+ * Find adjacent modules in row/column with the same color
492
+ * and assign a penalty value.
493
+ *
494
+ * Points: N1 + i
495
+ * i is the amount by which the number of adjacent modules of the same color exceeds 5
496
+ */
497
+ exports$1.getPenaltyN1 = function getPenaltyN1 (data) {
498
+ const size = data.size;
499
+ let points = 0;
500
+ let sameCountCol = 0;
501
+ let sameCountRow = 0;
502
+ let lastCol = null;
503
+ let lastRow = null;
504
+
505
+ for (let row = 0; row < size; row++) {
506
+ sameCountCol = sameCountRow = 0;
507
+ lastCol = lastRow = null;
508
+
509
+ for (let col = 0; col < size; col++) {
510
+ let module = data.get(row, col);
511
+ if (module === lastCol) {
512
+ sameCountCol++;
513
+ } else {
514
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
515
+ lastCol = module;
516
+ sameCountCol = 1;
517
+ }
518
+
519
+ module = data.get(col, row);
520
+ if (module === lastRow) {
521
+ sameCountRow++;
522
+ } else {
523
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
524
+ lastRow = module;
525
+ sameCountRow = 1;
526
+ }
527
+ }
528
+
529
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
530
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
531
+ }
532
+
533
+ return points
534
+ };
535
+
536
+ /**
537
+ * Find 2x2 blocks with the same color and assign a penalty value
538
+ *
539
+ * Points: N2 * (m - 1) * (n - 1)
540
+ */
541
+ exports$1.getPenaltyN2 = function getPenaltyN2 (data) {
542
+ const size = data.size;
543
+ let points = 0;
544
+
545
+ for (let row = 0; row < size - 1; row++) {
546
+ for (let col = 0; col < size - 1; col++) {
547
+ const last = data.get(row, col) +
548
+ data.get(row, col + 1) +
549
+ data.get(row + 1, col) +
550
+ data.get(row + 1, col + 1);
551
+
552
+ if (last === 4 || last === 0) points++;
553
+ }
554
+ }
555
+
556
+ return points * PenaltyScores.N2
557
+ };
558
+
559
+ /**
560
+ * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
561
+ * preceded or followed by light area 4 modules wide
562
+ *
563
+ * Points: N3 * number of pattern found
564
+ */
565
+ exports$1.getPenaltyN3 = function getPenaltyN3 (data) {
566
+ const size = data.size;
567
+ let points = 0;
568
+ let bitsCol = 0;
569
+ let bitsRow = 0;
570
+
571
+ for (let row = 0; row < size; row++) {
572
+ bitsCol = bitsRow = 0;
573
+ for (let col = 0; col < size; col++) {
574
+ bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col);
575
+ if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++;
576
+
577
+ bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row);
578
+ if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++;
579
+ }
580
+ }
581
+
582
+ return points * PenaltyScores.N3
583
+ };
584
+
585
+ /**
586
+ * Calculate proportion of dark modules in entire symbol
587
+ *
588
+ * Points: N4 * k
589
+ *
590
+ * k is the rating of the deviation of the proportion of dark modules
591
+ * in the symbol from 50% in steps of 5%
592
+ */
593
+ exports$1.getPenaltyN4 = function getPenaltyN4 (data) {
594
+ let darkCount = 0;
595
+ const modulesCount = data.data.length;
596
+
597
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
598
+
599
+ const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10);
600
+
601
+ return k * PenaltyScores.N4
602
+ };
603
+
604
+ /**
605
+ * Return mask value at given position
606
+ *
607
+ * @param {Number} maskPattern Pattern reference value
608
+ * @param {Number} i Row
609
+ * @param {Number} j Column
610
+ * @return {Boolean} Mask value
611
+ */
612
+ function getMaskAt (maskPattern, i, j) {
613
+ switch (maskPattern) {
614
+ case exports$1.Patterns.PATTERN000: return (i + j) % 2 === 0
615
+ case exports$1.Patterns.PATTERN001: return i % 2 === 0
616
+ case exports$1.Patterns.PATTERN010: return j % 3 === 0
617
+ case exports$1.Patterns.PATTERN011: return (i + j) % 3 === 0
618
+ case exports$1.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
619
+ case exports$1.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
620
+ case exports$1.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
621
+ case exports$1.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
622
+
623
+ default: throw new Error('bad maskPattern:' + maskPattern)
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Apply a mask pattern to a BitMatrix
629
+ *
630
+ * @param {Number} pattern Pattern reference number
631
+ * @param {BitMatrix} data BitMatrix data
632
+ */
633
+ exports$1.applyMask = function applyMask (pattern, data) {
634
+ const size = data.size;
635
+
636
+ for (let col = 0; col < size; col++) {
637
+ for (let row = 0; row < size; row++) {
638
+ if (data.isReserved(row, col)) continue
639
+ data.xor(row, col, getMaskAt(pattern, row, col));
640
+ }
641
+ }
642
+ };
643
+
644
+ /**
645
+ * Returns the best mask pattern for data
646
+ *
647
+ * @param {BitMatrix} data
648
+ * @return {Number} Mask pattern reference number
649
+ */
650
+ exports$1.getBestMask = function getBestMask (data, setupFormatFunc) {
651
+ const numPatterns = Object.keys(exports$1.Patterns).length;
652
+ let bestPattern = 0;
653
+ let lowerPenalty = Infinity;
654
+
655
+ for (let p = 0; p < numPatterns; p++) {
656
+ setupFormatFunc(p);
657
+ exports$1.applyMask(p, data);
658
+
659
+ // Calculate penalty
660
+ const penalty =
661
+ exports$1.getPenaltyN1(data) +
662
+ exports$1.getPenaltyN2(data) +
663
+ exports$1.getPenaltyN3(data) +
664
+ exports$1.getPenaltyN4(data);
665
+
666
+ // Undo previously applied mask
667
+ exports$1.applyMask(p, data);
668
+
669
+ if (penalty < lowerPenalty) {
670
+ lowerPenalty = penalty;
671
+ bestPattern = p;
672
+ }
673
+ }
674
+
675
+ return bestPattern
676
+ };
677
+ } (maskPattern));
678
+ return maskPattern;
679
+ }
680
+
681
+ var errorCorrectionCode = {};
682
+
683
+ var hasRequiredErrorCorrectionCode;
684
+
685
+ function requireErrorCorrectionCode () {
686
+ if (hasRequiredErrorCorrectionCode) return errorCorrectionCode;
687
+ hasRequiredErrorCorrectionCode = 1;
688
+ const ECLevel = requireErrorCorrectionLevel();
689
+
690
+ const EC_BLOCKS_TABLE = [
691
+ // L M Q H
692
+ 1, 1, 1, 1,
693
+ 1, 1, 1, 1,
694
+ 1, 1, 2, 2,
695
+ 1, 2, 2, 4,
696
+ 1, 2, 4, 4,
697
+ 2, 4, 4, 4,
698
+ 2, 4, 6, 5,
699
+ 2, 4, 6, 6,
700
+ 2, 5, 8, 8,
701
+ 4, 5, 8, 8,
702
+ 4, 5, 8, 11,
703
+ 4, 8, 10, 11,
704
+ 4, 9, 12, 16,
705
+ 4, 9, 16, 16,
706
+ 6, 10, 12, 18,
707
+ 6, 10, 17, 16,
708
+ 6, 11, 16, 19,
709
+ 6, 13, 18, 21,
710
+ 7, 14, 21, 25,
711
+ 8, 16, 20, 25,
712
+ 8, 17, 23, 25,
713
+ 9, 17, 23, 34,
714
+ 9, 18, 25, 30,
715
+ 10, 20, 27, 32,
716
+ 12, 21, 29, 35,
717
+ 12, 23, 34, 37,
718
+ 12, 25, 34, 40,
719
+ 13, 26, 35, 42,
720
+ 14, 28, 38, 45,
721
+ 15, 29, 40, 48,
722
+ 16, 31, 43, 51,
723
+ 17, 33, 45, 54,
724
+ 18, 35, 48, 57,
725
+ 19, 37, 51, 60,
726
+ 19, 38, 53, 63,
727
+ 20, 40, 56, 66,
728
+ 21, 43, 59, 70,
729
+ 22, 45, 62, 74,
730
+ 24, 47, 65, 77,
731
+ 25, 49, 68, 81
732
+ ];
733
+
734
+ const EC_CODEWORDS_TABLE = [
735
+ // L M Q H
736
+ 7, 10, 13, 17,
737
+ 10, 16, 22, 28,
738
+ 15, 26, 36, 44,
739
+ 20, 36, 52, 64,
740
+ 26, 48, 72, 88,
741
+ 36, 64, 96, 112,
742
+ 40, 72, 108, 130,
743
+ 48, 88, 132, 156,
744
+ 60, 110, 160, 192,
745
+ 72, 130, 192, 224,
746
+ 80, 150, 224, 264,
747
+ 96, 176, 260, 308,
748
+ 104, 198, 288, 352,
749
+ 120, 216, 320, 384,
750
+ 132, 240, 360, 432,
751
+ 144, 280, 408, 480,
752
+ 168, 308, 448, 532,
753
+ 180, 338, 504, 588,
754
+ 196, 364, 546, 650,
755
+ 224, 416, 600, 700,
756
+ 224, 442, 644, 750,
757
+ 252, 476, 690, 816,
758
+ 270, 504, 750, 900,
759
+ 300, 560, 810, 960,
760
+ 312, 588, 870, 1050,
761
+ 336, 644, 952, 1110,
762
+ 360, 700, 1020, 1200,
763
+ 390, 728, 1050, 1260,
764
+ 420, 784, 1140, 1350,
765
+ 450, 812, 1200, 1440,
766
+ 480, 868, 1290, 1530,
767
+ 510, 924, 1350, 1620,
768
+ 540, 980, 1440, 1710,
769
+ 570, 1036, 1530, 1800,
770
+ 570, 1064, 1590, 1890,
771
+ 600, 1120, 1680, 1980,
772
+ 630, 1204, 1770, 2100,
773
+ 660, 1260, 1860, 2220,
774
+ 720, 1316, 1950, 2310,
775
+ 750, 1372, 2040, 2430
776
+ ];
777
+
778
+ /**
779
+ * Returns the number of error correction block that the QR Code should contain
780
+ * for the specified version and error correction level.
781
+ *
782
+ * @param {Number} version QR Code version
783
+ * @param {Number} errorCorrectionLevel Error correction level
784
+ * @return {Number} Number of error correction blocks
785
+ */
786
+ errorCorrectionCode.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
787
+ switch (errorCorrectionLevel) {
788
+ case ECLevel.L:
789
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
790
+ case ECLevel.M:
791
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
792
+ case ECLevel.Q:
793
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
794
+ case ECLevel.H:
795
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
796
+ default:
797
+ return undefined
798
+ }
799
+ };
800
+
801
+ /**
802
+ * Returns the number of error correction codewords to use for the specified
803
+ * version and error correction level.
804
+ *
805
+ * @param {Number} version QR Code version
806
+ * @param {Number} errorCorrectionLevel Error correction level
807
+ * @return {Number} Number of error correction codewords
808
+ */
809
+ errorCorrectionCode.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
810
+ switch (errorCorrectionLevel) {
811
+ case ECLevel.L:
812
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
813
+ case ECLevel.M:
814
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
815
+ case ECLevel.Q:
816
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
817
+ case ECLevel.H:
818
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
819
+ default:
820
+ return undefined
821
+ }
822
+ };
823
+ return errorCorrectionCode;
824
+ }
825
+
826
+ var polynomial = {};
827
+
828
+ var galoisField = {};
829
+
830
+ var hasRequiredGaloisField;
831
+
832
+ function requireGaloisField () {
833
+ if (hasRequiredGaloisField) return galoisField;
834
+ hasRequiredGaloisField = 1;
835
+ const EXP_TABLE = new Uint8Array(512);
836
+ const LOG_TABLE = new Uint8Array(256)
837
+ /**
838
+ * Precompute the log and anti-log tables for faster computation later
839
+ *
840
+ * For each possible value in the galois field 2^8, we will pre-compute
841
+ * the logarithm and anti-logarithm (exponential) of this value
842
+ *
843
+ * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
844
+ */
845
+ ;(function initTables () {
846
+ let x = 1;
847
+ for (let i = 0; i < 255; i++) {
848
+ EXP_TABLE[i] = x;
849
+ LOG_TABLE[x] = i;
850
+
851
+ x <<= 1; // multiply by 2
852
+
853
+ // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
854
+ // This means that when a number is 256 or larger, it should be XORed with 0x11D.
855
+ if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
856
+ x ^= 0x11D;
857
+ }
858
+ }
859
+
860
+ // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
861
+ // stay inside the bounds (because we will mainly use this table for the multiplication of
862
+ // two GF numbers, no more).
863
+ // @see {@link mul}
864
+ for (let i = 255; i < 512; i++) {
865
+ EXP_TABLE[i] = EXP_TABLE[i - 255];
866
+ }
867
+ }());
868
+
869
+ /**
870
+ * Returns log value of n inside Galois Field
871
+ *
872
+ * @param {Number} n
873
+ * @return {Number}
874
+ */
875
+ galoisField.log = function log (n) {
876
+ if (n < 1) throw new Error('log(' + n + ')')
877
+ return LOG_TABLE[n]
878
+ };
879
+
880
+ /**
881
+ * Returns anti-log value of n inside Galois Field
882
+ *
883
+ * @param {Number} n
884
+ * @return {Number}
885
+ */
886
+ galoisField.exp = function exp (n) {
887
+ return EXP_TABLE[n]
888
+ };
889
+
890
+ /**
891
+ * Multiplies two number inside Galois Field
892
+ *
893
+ * @param {Number} x
894
+ * @param {Number} y
895
+ * @return {Number}
896
+ */
897
+ galoisField.mul = function mul (x, y) {
898
+ if (x === 0 || y === 0) return 0
899
+
900
+ // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
901
+ // @see {@link initTables}
902
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
903
+ };
904
+ return galoisField;
905
+ }
906
+
907
+ var hasRequiredPolynomial;
908
+
909
+ function requirePolynomial () {
910
+ if (hasRequiredPolynomial) return polynomial;
911
+ hasRequiredPolynomial = 1;
912
+ (function (exports$1) {
913
+ const GF = requireGaloisField();
914
+
915
+ /**
916
+ * Multiplies two polynomials inside Galois Field
917
+ *
918
+ * @param {Uint8Array} p1 Polynomial
919
+ * @param {Uint8Array} p2 Polynomial
920
+ * @return {Uint8Array} Product of p1 and p2
921
+ */
922
+ exports$1.mul = function mul (p1, p2) {
923
+ const coeff = new Uint8Array(p1.length + p2.length - 1);
924
+
925
+ for (let i = 0; i < p1.length; i++) {
926
+ for (let j = 0; j < p2.length; j++) {
927
+ coeff[i + j] ^= GF.mul(p1[i], p2[j]);
928
+ }
929
+ }
930
+
931
+ return coeff
932
+ };
933
+
934
+ /**
935
+ * Calculate the remainder of polynomials division
936
+ *
937
+ * @param {Uint8Array} divident Polynomial
938
+ * @param {Uint8Array} divisor Polynomial
939
+ * @return {Uint8Array} Remainder
940
+ */
941
+ exports$1.mod = function mod (divident, divisor) {
942
+ let result = new Uint8Array(divident);
943
+
944
+ while ((result.length - divisor.length) >= 0) {
945
+ const coeff = result[0];
946
+
947
+ for (let i = 0; i < divisor.length; i++) {
948
+ result[i] ^= GF.mul(divisor[i], coeff);
949
+ }
950
+
951
+ // remove all zeros from buffer head
952
+ let offset = 0;
953
+ while (offset < result.length && result[offset] === 0) offset++;
954
+ result = result.slice(offset);
955
+ }
956
+
957
+ return result
958
+ };
959
+
960
+ /**
961
+ * Generate an irreducible generator polynomial of specified degree
962
+ * (used by Reed-Solomon encoder)
963
+ *
964
+ * @param {Number} degree Degree of the generator polynomial
965
+ * @return {Uint8Array} Buffer containing polynomial coefficients
966
+ */
967
+ exports$1.generateECPolynomial = function generateECPolynomial (degree) {
968
+ let poly = new Uint8Array([1]);
969
+ for (let i = 0; i < degree; i++) {
970
+ poly = exports$1.mul(poly, new Uint8Array([1, GF.exp(i)]));
971
+ }
972
+
973
+ return poly
974
+ };
975
+ } (polynomial));
976
+ return polynomial;
977
+ }
978
+
979
+ var reedSolomonEncoder;
980
+ var hasRequiredReedSolomonEncoder;
981
+
982
+ function requireReedSolomonEncoder () {
983
+ if (hasRequiredReedSolomonEncoder) return reedSolomonEncoder;
984
+ hasRequiredReedSolomonEncoder = 1;
985
+ const Polynomial = requirePolynomial();
986
+
987
+ function ReedSolomonEncoder (degree) {
988
+ this.genPoly = undefined;
989
+ this.degree = degree;
990
+
991
+ if (this.degree) this.initialize(this.degree);
992
+ }
993
+
994
+ /**
995
+ * Initialize the encoder.
996
+ * The input param should correspond to the number of error correction codewords.
997
+ *
998
+ * @param {Number} degree
999
+ */
1000
+ ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
1001
+ // create an irreducible generator polynomial
1002
+ this.degree = degree;
1003
+ this.genPoly = Polynomial.generateECPolynomial(this.degree);
1004
+ };
1005
+
1006
+ /**
1007
+ * Encodes a chunk of data
1008
+ *
1009
+ * @param {Uint8Array} data Buffer containing input data
1010
+ * @return {Uint8Array} Buffer containing encoded data
1011
+ */
1012
+ ReedSolomonEncoder.prototype.encode = function encode (data) {
1013
+ if (!this.genPoly) {
1014
+ throw new Error('Encoder not initialized')
1015
+ }
1016
+
1017
+ // Calculate EC for this data block
1018
+ // extends data size to data+genPoly size
1019
+ const paddedData = new Uint8Array(data.length + this.degree);
1020
+ paddedData.set(data);
1021
+
1022
+ // The error correction codewords are the remainder after dividing the data codewords
1023
+ // by a generator polynomial
1024
+ const remainder = Polynomial.mod(paddedData, this.genPoly);
1025
+
1026
+ // return EC data blocks (last n byte, where n is the degree of genPoly)
1027
+ // If coefficients number in remainder are less than genPoly degree,
1028
+ // pad with 0s to the left to reach the needed number of coefficients
1029
+ const start = this.degree - remainder.length;
1030
+ if (start > 0) {
1031
+ const buff = new Uint8Array(this.degree);
1032
+ buff.set(remainder, start);
1033
+
1034
+ return buff
1035
+ }
1036
+
1037
+ return remainder
1038
+ };
1039
+
1040
+ reedSolomonEncoder = ReedSolomonEncoder;
1041
+ return reedSolomonEncoder;
1042
+ }
1043
+
1044
+ var version = {};
1045
+
1046
+ var mode = {};
1047
+
1048
+ var versionCheck = {};
1049
+
1050
+ /**
1051
+ * Check if QR Code version is valid
1052
+ *
1053
+ * @param {Number} version QR Code version
1054
+ * @return {Boolean} true if valid version, false otherwise
1055
+ */
1056
+
1057
+ var hasRequiredVersionCheck;
1058
+
1059
+ function requireVersionCheck () {
1060
+ if (hasRequiredVersionCheck) return versionCheck;
1061
+ hasRequiredVersionCheck = 1;
1062
+ versionCheck.isValid = function isValid (version) {
1063
+ return !isNaN(version) && version >= 1 && version <= 40
1064
+ };
1065
+ return versionCheck;
1066
+ }
1067
+
1068
+ var regex = {};
1069
+
1070
+ var hasRequiredRegex;
1071
+
1072
+ function requireRegex () {
1073
+ if (hasRequiredRegex) return regex;
1074
+ hasRequiredRegex = 1;
1075
+ const numeric = '[0-9]+';
1076
+ const alphanumeric = '[A-Z $%*+\\-./:]+';
1077
+ let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
1078
+ '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
1079
+ '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
1080
+ '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+';
1081
+ kanji = kanji.replace(/u/g, '\\u');
1082
+
1083
+ const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+';
1084
+
1085
+ regex.KANJI = new RegExp(kanji, 'g');
1086
+ regex.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g');
1087
+ regex.BYTE = new RegExp(byte, 'g');
1088
+ regex.NUMERIC = new RegExp(numeric, 'g');
1089
+ regex.ALPHANUMERIC = new RegExp(alphanumeric, 'g');
1090
+
1091
+ const TEST_KANJI = new RegExp('^' + kanji + '$');
1092
+ const TEST_NUMERIC = new RegExp('^' + numeric + '$');
1093
+ const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$');
1094
+
1095
+ regex.testKanji = function testKanji (str) {
1096
+ return TEST_KANJI.test(str)
1097
+ };
1098
+
1099
+ regex.testNumeric = function testNumeric (str) {
1100
+ return TEST_NUMERIC.test(str)
1101
+ };
1102
+
1103
+ regex.testAlphanumeric = function testAlphanumeric (str) {
1104
+ return TEST_ALPHANUMERIC.test(str)
1105
+ };
1106
+ return regex;
1107
+ }
1108
+
1109
+ var hasRequiredMode;
1110
+
1111
+ function requireMode () {
1112
+ if (hasRequiredMode) return mode;
1113
+ hasRequiredMode = 1;
1114
+ (function (exports$1) {
1115
+ const VersionCheck = requireVersionCheck();
1116
+ const Regex = requireRegex();
1117
+
1118
+ /**
1119
+ * Numeric mode encodes data from the decimal digit set (0 - 9)
1120
+ * (byte values 30HEX to 39HEX).
1121
+ * Normally, 3 data characters are represented by 10 bits.
1122
+ *
1123
+ * @type {Object}
1124
+ */
1125
+ exports$1.NUMERIC = {
1126
+ id: 'Numeric',
1127
+ bit: 1 << 0,
1128
+ ccBits: [10, 12, 14]
1129
+ };
1130
+
1131
+ /**
1132
+ * Alphanumeric mode encodes data from a set of 45 characters,
1133
+ * i.e. 10 numeric digits (0 - 9),
1134
+ * 26 alphabetic characters (A - Z),
1135
+ * and 9 symbols (SP, $, %, *, +, -, ., /, :).
1136
+ * Normally, two input characters are represented by 11 bits.
1137
+ *
1138
+ * @type {Object}
1139
+ */
1140
+ exports$1.ALPHANUMERIC = {
1141
+ id: 'Alphanumeric',
1142
+ bit: 1 << 1,
1143
+ ccBits: [9, 11, 13]
1144
+ };
1145
+
1146
+ /**
1147
+ * In byte mode, data is encoded at 8 bits per character.
1148
+ *
1149
+ * @type {Object}
1150
+ */
1151
+ exports$1.BYTE = {
1152
+ id: 'Byte',
1153
+ bit: 1 << 2,
1154
+ ccBits: [8, 16, 16]
1155
+ };
1156
+
1157
+ /**
1158
+ * The Kanji mode efficiently encodes Kanji characters in accordance with
1159
+ * the Shift JIS system based on JIS X 0208.
1160
+ * The Shift JIS values are shifted from the JIS X 0208 values.
1161
+ * JIS X 0208 gives details of the shift coded representation.
1162
+ * Each two-byte character value is compacted to a 13-bit binary codeword.
1163
+ *
1164
+ * @type {Object}
1165
+ */
1166
+ exports$1.KANJI = {
1167
+ id: 'Kanji',
1168
+ bit: 1 << 3,
1169
+ ccBits: [8, 10, 12]
1170
+ };
1171
+
1172
+ /**
1173
+ * Mixed mode will contain a sequences of data in a combination of any of
1174
+ * the modes described above
1175
+ *
1176
+ * @type {Object}
1177
+ */
1178
+ exports$1.MIXED = {
1179
+ bit: -1
1180
+ };
1181
+
1182
+ /**
1183
+ * Returns the number of bits needed to store the data length
1184
+ * according to QR Code specifications.
1185
+ *
1186
+ * @param {Mode} mode Data mode
1187
+ * @param {Number} version QR Code version
1188
+ * @return {Number} Number of bits
1189
+ */
1190
+ exports$1.getCharCountIndicator = function getCharCountIndicator (mode, version) {
1191
+ if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
1192
+
1193
+ if (!VersionCheck.isValid(version)) {
1194
+ throw new Error('Invalid version: ' + version)
1195
+ }
1196
+
1197
+ if (version >= 1 && version < 10) return mode.ccBits[0]
1198
+ else if (version < 27) return mode.ccBits[1]
1199
+ return mode.ccBits[2]
1200
+ };
1201
+
1202
+ /**
1203
+ * Returns the most efficient mode to store the specified data
1204
+ *
1205
+ * @param {String} dataStr Input data string
1206
+ * @return {Mode} Best mode
1207
+ */
1208
+ exports$1.getBestModeForData = function getBestModeForData (dataStr) {
1209
+ if (Regex.testNumeric(dataStr)) return exports$1.NUMERIC
1210
+ else if (Regex.testAlphanumeric(dataStr)) return exports$1.ALPHANUMERIC
1211
+ else if (Regex.testKanji(dataStr)) return exports$1.KANJI
1212
+ else return exports$1.BYTE
1213
+ };
1214
+
1215
+ /**
1216
+ * Return mode name as string
1217
+ *
1218
+ * @param {Mode} mode Mode object
1219
+ * @returns {String} Mode name
1220
+ */
1221
+ exports$1.toString = function toString (mode) {
1222
+ if (mode && mode.id) return mode.id
1223
+ throw new Error('Invalid mode')
1224
+ };
1225
+
1226
+ /**
1227
+ * Check if input param is a valid mode object
1228
+ *
1229
+ * @param {Mode} mode Mode object
1230
+ * @returns {Boolean} True if valid mode, false otherwise
1231
+ */
1232
+ exports$1.isValid = function isValid (mode) {
1233
+ return mode && mode.bit && mode.ccBits
1234
+ };
1235
+
1236
+ /**
1237
+ * Get mode object from its name
1238
+ *
1239
+ * @param {String} string Mode name
1240
+ * @returns {Mode} Mode object
1241
+ */
1242
+ function fromString (string) {
1243
+ if (typeof string !== 'string') {
1244
+ throw new Error('Param is not a string')
1245
+ }
1246
+
1247
+ const lcStr = string.toLowerCase();
1248
+
1249
+ switch (lcStr) {
1250
+ case 'numeric':
1251
+ return exports$1.NUMERIC
1252
+ case 'alphanumeric':
1253
+ return exports$1.ALPHANUMERIC
1254
+ case 'kanji':
1255
+ return exports$1.KANJI
1256
+ case 'byte':
1257
+ return exports$1.BYTE
1258
+ default:
1259
+ throw new Error('Unknown mode: ' + string)
1260
+ }
1261
+ }
1262
+
1263
+ /**
1264
+ * Returns mode from a value.
1265
+ * If value is not a valid mode, returns defaultValue
1266
+ *
1267
+ * @param {Mode|String} value Encoding mode
1268
+ * @param {Mode} defaultValue Fallback value
1269
+ * @return {Mode} Encoding mode
1270
+ */
1271
+ exports$1.from = function from (value, defaultValue) {
1272
+ if (exports$1.isValid(value)) {
1273
+ return value
1274
+ }
1275
+
1276
+ try {
1277
+ return fromString(value)
1278
+ } catch (e) {
1279
+ return defaultValue
1280
+ }
1281
+ };
1282
+ } (mode));
1283
+ return mode;
1284
+ }
1285
+
1286
+ var hasRequiredVersion;
1287
+
1288
+ function requireVersion () {
1289
+ if (hasRequiredVersion) return version;
1290
+ hasRequiredVersion = 1;
1291
+ (function (exports$1) {
1292
+ const Utils = requireUtils$1();
1293
+ const ECCode = requireErrorCorrectionCode();
1294
+ const ECLevel = requireErrorCorrectionLevel();
1295
+ const Mode = requireMode();
1296
+ const VersionCheck = requireVersionCheck();
1297
+
1298
+ // Generator polynomial used to encode version information
1299
+ const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
1300
+ const G18_BCH = Utils.getBCHDigit(G18);
1301
+
1302
+ function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
1303
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
1304
+ if (length <= exports$1.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
1305
+ return currentVersion
1306
+ }
1307
+ }
1308
+
1309
+ return undefined
1310
+ }
1311
+
1312
+ function getReservedBitsCount (mode, version) {
1313
+ // Character count indicator + mode indicator bits
1314
+ return Mode.getCharCountIndicator(mode, version) + 4
1315
+ }
1316
+
1317
+ function getTotalBitsFromDataArray (segments, version) {
1318
+ let totalBits = 0;
1319
+
1320
+ segments.forEach(function (data) {
1321
+ const reservedBits = getReservedBitsCount(data.mode, version);
1322
+ totalBits += reservedBits + data.getBitsLength();
1323
+ });
1324
+
1325
+ return totalBits
1326
+ }
1327
+
1328
+ function getBestVersionForMixedData (segments, errorCorrectionLevel) {
1329
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
1330
+ const length = getTotalBitsFromDataArray(segments, currentVersion);
1331
+ if (length <= exports$1.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
1332
+ return currentVersion
1333
+ }
1334
+ }
1335
+
1336
+ return undefined
1337
+ }
1338
+
1339
+ /**
1340
+ * Returns version number from a value.
1341
+ * If value is not a valid version, returns defaultValue
1342
+ *
1343
+ * @param {Number|String} value QR Code version
1344
+ * @param {Number} defaultValue Fallback value
1345
+ * @return {Number} QR Code version number
1346
+ */
1347
+ exports$1.from = function from (value, defaultValue) {
1348
+ if (VersionCheck.isValid(value)) {
1349
+ return parseInt(value, 10)
1350
+ }
1351
+
1352
+ return defaultValue
1353
+ };
1354
+
1355
+ /**
1356
+ * Returns how much data can be stored with the specified QR code version
1357
+ * and error correction level
1358
+ *
1359
+ * @param {Number} version QR Code version (1-40)
1360
+ * @param {Number} errorCorrectionLevel Error correction level
1361
+ * @param {Mode} mode Data mode
1362
+ * @return {Number} Quantity of storable data
1363
+ */
1364
+ exports$1.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
1365
+ if (!VersionCheck.isValid(version)) {
1366
+ throw new Error('Invalid QR Code version')
1367
+ }
1368
+
1369
+ // Use Byte mode as default
1370
+ if (typeof mode === 'undefined') mode = Mode.BYTE;
1371
+
1372
+ // Total codewords for this QR code version (Data + Error correction)
1373
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
1374
+
1375
+ // Total number of error correction codewords
1376
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
1377
+
1378
+ // Total number of data codewords
1379
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
1380
+
1381
+ if (mode === Mode.MIXED) return dataTotalCodewordsBits
1382
+
1383
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
1384
+
1385
+ // Return max number of storable codewords
1386
+ switch (mode) {
1387
+ case Mode.NUMERIC:
1388
+ return Math.floor((usableBits / 10) * 3)
1389
+
1390
+ case Mode.ALPHANUMERIC:
1391
+ return Math.floor((usableBits / 11) * 2)
1392
+
1393
+ case Mode.KANJI:
1394
+ return Math.floor(usableBits / 13)
1395
+
1396
+ case Mode.BYTE:
1397
+ default:
1398
+ return Math.floor(usableBits / 8)
1399
+ }
1400
+ };
1401
+
1402
+ /**
1403
+ * Returns the minimum version needed to contain the amount of data
1404
+ *
1405
+ * @param {Segment} data Segment of data
1406
+ * @param {Number} [errorCorrectionLevel=H] Error correction level
1407
+ * @param {Mode} mode Data mode
1408
+ * @return {Number} QR Code version
1409
+ */
1410
+ exports$1.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
1411
+ let seg;
1412
+
1413
+ const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
1414
+
1415
+ if (Array.isArray(data)) {
1416
+ if (data.length > 1) {
1417
+ return getBestVersionForMixedData(data, ecl)
1418
+ }
1419
+
1420
+ if (data.length === 0) {
1421
+ return 1
1422
+ }
1423
+
1424
+ seg = data[0];
1425
+ } else {
1426
+ seg = data;
1427
+ }
1428
+
1429
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
1430
+ };
1431
+
1432
+ /**
1433
+ * Returns version information with relative error correction bits
1434
+ *
1435
+ * The version information is included in QR Code symbols of version 7 or larger.
1436
+ * It consists of an 18-bit sequence containing 6 data bits,
1437
+ * with 12 error correction bits calculated using the (18, 6) Golay code.
1438
+ *
1439
+ * @param {Number} version QR Code version
1440
+ * @return {Number} Encoded version info bits
1441
+ */
1442
+ exports$1.getEncodedBits = function getEncodedBits (version) {
1443
+ if (!VersionCheck.isValid(version) || version < 7) {
1444
+ throw new Error('Invalid QR Code version')
1445
+ }
1446
+
1447
+ let d = version << 12;
1448
+
1449
+ while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
1450
+ d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH));
1451
+ }
1452
+
1453
+ return (version << 12) | d
1454
+ };
1455
+ } (version));
1456
+ return version;
1457
+ }
1458
+
1459
+ var formatInfo = {};
1460
+
1461
+ var hasRequiredFormatInfo;
1462
+
1463
+ function requireFormatInfo () {
1464
+ if (hasRequiredFormatInfo) return formatInfo;
1465
+ hasRequiredFormatInfo = 1;
1466
+ const Utils = requireUtils$1();
1467
+
1468
+ const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
1469
+ const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
1470
+ const G15_BCH = Utils.getBCHDigit(G15);
1471
+
1472
+ /**
1473
+ * Returns format information with relative error correction bits
1474
+ *
1475
+ * The format information is a 15-bit sequence containing 5 data bits,
1476
+ * with 10 error correction bits calculated using the (15, 5) BCH code.
1477
+ *
1478
+ * @param {Number} errorCorrectionLevel Error correction level
1479
+ * @param {Number} mask Mask pattern
1480
+ * @return {Number} Encoded format information bits
1481
+ */
1482
+ formatInfo.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
1483
+ const data = ((errorCorrectionLevel.bit << 3) | mask);
1484
+ let d = data << 10;
1485
+
1486
+ while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
1487
+ d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH));
1488
+ }
1489
+
1490
+ // xor final data with mask pattern in order to ensure that
1491
+ // no combination of Error Correction Level and data mask pattern
1492
+ // will result in an all-zero data string
1493
+ return ((data << 10) | d) ^ G15_MASK
1494
+ };
1495
+ return formatInfo;
1496
+ }
1497
+
1498
+ var segments = {};
1499
+
1500
+ var numericData;
1501
+ var hasRequiredNumericData;
1502
+
1503
+ function requireNumericData () {
1504
+ if (hasRequiredNumericData) return numericData;
1505
+ hasRequiredNumericData = 1;
1506
+ const Mode = requireMode();
1507
+
1508
+ function NumericData (data) {
1509
+ this.mode = Mode.NUMERIC;
1510
+ this.data = data.toString();
1511
+ }
1512
+
1513
+ NumericData.getBitsLength = function getBitsLength (length) {
1514
+ return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
1515
+ };
1516
+
1517
+ NumericData.prototype.getLength = function getLength () {
1518
+ return this.data.length
1519
+ };
1520
+
1521
+ NumericData.prototype.getBitsLength = function getBitsLength () {
1522
+ return NumericData.getBitsLength(this.data.length)
1523
+ };
1524
+
1525
+ NumericData.prototype.write = function write (bitBuffer) {
1526
+ let i, group, value;
1527
+
1528
+ // The input data string is divided into groups of three digits,
1529
+ // and each group is converted to its 10-bit binary equivalent.
1530
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
1531
+ group = this.data.substr(i, 3);
1532
+ value = parseInt(group, 10);
1533
+
1534
+ bitBuffer.put(value, 10);
1535
+ }
1536
+
1537
+ // If the number of input digits is not an exact multiple of three,
1538
+ // the final one or two digits are converted to 4 or 7 bits respectively.
1539
+ const remainingNum = this.data.length - i;
1540
+ if (remainingNum > 0) {
1541
+ group = this.data.substr(i);
1542
+ value = parseInt(group, 10);
1543
+
1544
+ bitBuffer.put(value, remainingNum * 3 + 1);
1545
+ }
1546
+ };
1547
+
1548
+ numericData = NumericData;
1549
+ return numericData;
1550
+ }
1551
+
1552
+ var alphanumericData;
1553
+ var hasRequiredAlphanumericData;
1554
+
1555
+ function requireAlphanumericData () {
1556
+ if (hasRequiredAlphanumericData) return alphanumericData;
1557
+ hasRequiredAlphanumericData = 1;
1558
+ const Mode = requireMode();
1559
+
1560
+ /**
1561
+ * Array of characters available in alphanumeric mode
1562
+ *
1563
+ * As per QR Code specification, to each character
1564
+ * is assigned a value from 0 to 44 which in this case coincides
1565
+ * with the array index
1566
+ *
1567
+ * @type {Array}
1568
+ */
1569
+ const ALPHA_NUM_CHARS = [
1570
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1571
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
1572
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
1573
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'
1574
+ ];
1575
+
1576
+ function AlphanumericData (data) {
1577
+ this.mode = Mode.ALPHANUMERIC;
1578
+ this.data = data;
1579
+ }
1580
+
1581
+ AlphanumericData.getBitsLength = function getBitsLength (length) {
1582
+ return 11 * Math.floor(length / 2) + 6 * (length % 2)
1583
+ };
1584
+
1585
+ AlphanumericData.prototype.getLength = function getLength () {
1586
+ return this.data.length
1587
+ };
1588
+
1589
+ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
1590
+ return AlphanumericData.getBitsLength(this.data.length)
1591
+ };
1592
+
1593
+ AlphanumericData.prototype.write = function write (bitBuffer) {
1594
+ let i;
1595
+
1596
+ // Input data characters are divided into groups of two characters
1597
+ // and encoded as 11-bit binary codes.
1598
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
1599
+ // The character value of the first character is multiplied by 45
1600
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
1601
+
1602
+ // The character value of the second digit is added to the product
1603
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
1604
+
1605
+ // The sum is then stored as 11-bit binary number
1606
+ bitBuffer.put(value, 11);
1607
+ }
1608
+
1609
+ // If the number of input data characters is not a multiple of two,
1610
+ // the character value of the final character is encoded as a 6-bit binary number.
1611
+ if (this.data.length % 2) {
1612
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
1613
+ }
1614
+ };
1615
+
1616
+ alphanumericData = AlphanumericData;
1617
+ return alphanumericData;
1618
+ }
1619
+
1620
+ var byteData;
1621
+ var hasRequiredByteData;
1622
+
1623
+ function requireByteData () {
1624
+ if (hasRequiredByteData) return byteData;
1625
+ hasRequiredByteData = 1;
1626
+ const Mode = requireMode();
1627
+
1628
+ function ByteData (data) {
1629
+ this.mode = Mode.BYTE;
1630
+ if (typeof (data) === 'string') {
1631
+ this.data = new TextEncoder().encode(data);
1632
+ } else {
1633
+ this.data = new Uint8Array(data);
1634
+ }
1635
+ }
1636
+
1637
+ ByteData.getBitsLength = function getBitsLength (length) {
1638
+ return length * 8
1639
+ };
1640
+
1641
+ ByteData.prototype.getLength = function getLength () {
1642
+ return this.data.length
1643
+ };
1644
+
1645
+ ByteData.prototype.getBitsLength = function getBitsLength () {
1646
+ return ByteData.getBitsLength(this.data.length)
1647
+ };
1648
+
1649
+ ByteData.prototype.write = function (bitBuffer) {
1650
+ for (let i = 0, l = this.data.length; i < l; i++) {
1651
+ bitBuffer.put(this.data[i], 8);
1652
+ }
1653
+ };
1654
+
1655
+ byteData = ByteData;
1656
+ return byteData;
1657
+ }
1658
+
1659
+ var kanjiData;
1660
+ var hasRequiredKanjiData;
1661
+
1662
+ function requireKanjiData () {
1663
+ if (hasRequiredKanjiData) return kanjiData;
1664
+ hasRequiredKanjiData = 1;
1665
+ const Mode = requireMode();
1666
+ const Utils = requireUtils$1();
1667
+
1668
+ function KanjiData (data) {
1669
+ this.mode = Mode.KANJI;
1670
+ this.data = data;
1671
+ }
1672
+
1673
+ KanjiData.getBitsLength = function getBitsLength (length) {
1674
+ return length * 13
1675
+ };
1676
+
1677
+ KanjiData.prototype.getLength = function getLength () {
1678
+ return this.data.length
1679
+ };
1680
+
1681
+ KanjiData.prototype.getBitsLength = function getBitsLength () {
1682
+ return KanjiData.getBitsLength(this.data.length)
1683
+ };
1684
+
1685
+ KanjiData.prototype.write = function (bitBuffer) {
1686
+ let i;
1687
+
1688
+ // In the Shift JIS system, Kanji characters are represented by a two byte combination.
1689
+ // These byte values are shifted from the JIS X 0208 values.
1690
+ // JIS X 0208 gives details of the shift coded representation.
1691
+ for (i = 0; i < this.data.length; i++) {
1692
+ let value = Utils.toSJIS(this.data[i]);
1693
+
1694
+ // For characters with Shift JIS values from 0x8140 to 0x9FFC:
1695
+ if (value >= 0x8140 && value <= 0x9FFC) {
1696
+ // Subtract 0x8140 from Shift JIS value
1697
+ value -= 0x8140;
1698
+
1699
+ // For characters with Shift JIS values from 0xE040 to 0xEBBF
1700
+ } else if (value >= 0xE040 && value <= 0xEBBF) {
1701
+ // Subtract 0xC140 from Shift JIS value
1702
+ value -= 0xC140;
1703
+ } else {
1704
+ throw new Error(
1705
+ 'Invalid SJIS character: ' + this.data[i] + '\n' +
1706
+ 'Make sure your charset is UTF-8')
1707
+ }
1708
+
1709
+ // Multiply most significant byte of result by 0xC0
1710
+ // and add least significant byte to product
1711
+ value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff);
1712
+
1713
+ // Convert result to a 13-bit binary string
1714
+ bitBuffer.put(value, 13);
1715
+ }
1716
+ };
1717
+
1718
+ kanjiData = KanjiData;
1719
+ return kanjiData;
1720
+ }
1721
+
1722
+ var dijkstra = {exports: {}};
1723
+
1724
+ var hasRequiredDijkstra;
1725
+
1726
+ function requireDijkstra () {
1727
+ if (hasRequiredDijkstra) return dijkstra.exports;
1728
+ hasRequiredDijkstra = 1;
1729
+ (function (module) {
1730
+
1731
+ /******************************************************************************
1732
+ * Created 2008-08-19.
1733
+ *
1734
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
1735
+ *
1736
+ * Copyright (C) 2008
1737
+ * Wyatt Baldwin <self@wyattbaldwin.com>
1738
+ * All rights reserved
1739
+ *
1740
+ * Licensed under the MIT license.
1741
+ *
1742
+ * http://www.opensource.org/licenses/mit-license.php
1743
+ *
1744
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1745
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1746
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1747
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1748
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1749
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1750
+ * THE SOFTWARE.
1751
+ *****************************************************************************/
1752
+ var dijkstra = {
1753
+ single_source_shortest_paths: function(graph, s, d) {
1754
+ // Predecessor map for each node that has been encountered.
1755
+ // node ID => predecessor node ID
1756
+ var predecessors = {};
1757
+
1758
+ // Costs of shortest paths from s to all nodes encountered.
1759
+ // node ID => cost
1760
+ var costs = {};
1761
+ costs[s] = 0;
1762
+
1763
+ // Costs of shortest paths from s to all nodes encountered; differs from
1764
+ // `costs` in that it provides easy access to the node that currently has
1765
+ // the known shortest path from s.
1766
+ // XXX: Do we actually need both `costs` and `open`?
1767
+ var open = dijkstra.PriorityQueue.make();
1768
+ open.push(s, 0);
1769
+
1770
+ var closest,
1771
+ u, v,
1772
+ cost_of_s_to_u,
1773
+ adjacent_nodes,
1774
+ cost_of_e,
1775
+ cost_of_s_to_u_plus_cost_of_e,
1776
+ cost_of_s_to_v,
1777
+ first_visit;
1778
+ while (!open.empty()) {
1779
+ // In the nodes remaining in graph that have a known cost from s,
1780
+ // find the node, u, that currently has the shortest path from s.
1781
+ closest = open.pop();
1782
+ u = closest.value;
1783
+ cost_of_s_to_u = closest.cost;
1784
+
1785
+ // Get nodes adjacent to u...
1786
+ adjacent_nodes = graph[u] || {};
1787
+
1788
+ // ...and explore the edges that connect u to those nodes, updating
1789
+ // the cost of the shortest paths to any or all of those nodes as
1790
+ // necessary. v is the node across the current edge from u.
1791
+ for (v in adjacent_nodes) {
1792
+ if (adjacent_nodes.hasOwnProperty(v)) {
1793
+ // Get the cost of the edge running from u to v.
1794
+ cost_of_e = adjacent_nodes[v];
1795
+
1796
+ // Cost of s to u plus the cost of u to v across e--this is *a*
1797
+ // cost from s to v that may or may not be less than the current
1798
+ // known cost to v.
1799
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
1800
+
1801
+ // If we haven't visited v yet OR if the current known cost from s to
1802
+ // v is greater than the new cost we just found (cost of s to u plus
1803
+ // cost of u to v across e), update v's cost in the cost list and
1804
+ // update v's predecessor in the predecessor list (it's now u).
1805
+ cost_of_s_to_v = costs[v];
1806
+ first_visit = (typeof costs[v] === 'undefined');
1807
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
1808
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
1809
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
1810
+ predecessors[v] = u;
1811
+ }
1812
+ }
1813
+ }
1814
+ }
1815
+
1816
+ if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
1817
+ var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
1818
+ throw new Error(msg);
1819
+ }
1820
+
1821
+ return predecessors;
1822
+ },
1823
+
1824
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
1825
+ var nodes = [];
1826
+ var u = d;
1827
+ while (u) {
1828
+ nodes.push(u);
1829
+ predecessors[u];
1830
+ u = predecessors[u];
1831
+ }
1832
+ nodes.reverse();
1833
+ return nodes;
1834
+ },
1835
+
1836
+ find_path: function(graph, s, d) {
1837
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
1838
+ return dijkstra.extract_shortest_path_from_predecessor_list(
1839
+ predecessors, d);
1840
+ },
1841
+
1842
+ /**
1843
+ * A very naive priority queue implementation.
1844
+ */
1845
+ PriorityQueue: {
1846
+ make: function (opts) {
1847
+ var T = dijkstra.PriorityQueue,
1848
+ t = {},
1849
+ key;
1850
+ opts = opts || {};
1851
+ for (key in T) {
1852
+ if (T.hasOwnProperty(key)) {
1853
+ t[key] = T[key];
1854
+ }
1855
+ }
1856
+ t.queue = [];
1857
+ t.sorter = opts.sorter || T.default_sorter;
1858
+ return t;
1859
+ },
1860
+
1861
+ default_sorter: function (a, b) {
1862
+ return a.cost - b.cost;
1863
+ },
1864
+
1865
+ /**
1866
+ * Add a new item to the queue and ensure the highest priority element
1867
+ * is at the front of the queue.
1868
+ */
1869
+ push: function (value, cost) {
1870
+ var item = {value: value, cost: cost};
1871
+ this.queue.push(item);
1872
+ this.queue.sort(this.sorter);
1873
+ },
1874
+
1875
+ /**
1876
+ * Return the highest priority element in the queue.
1877
+ */
1878
+ pop: function () {
1879
+ return this.queue.shift();
1880
+ },
1881
+
1882
+ empty: function () {
1883
+ return this.queue.length === 0;
1884
+ }
1885
+ }
1886
+ };
1887
+
1888
+
1889
+ // node.js module exports
1890
+ {
1891
+ module.exports = dijkstra;
1892
+ }
1893
+ } (dijkstra));
1894
+ return dijkstra.exports;
1895
+ }
1896
+
1897
+ var hasRequiredSegments;
1898
+
1899
+ function requireSegments () {
1900
+ if (hasRequiredSegments) return segments;
1901
+ hasRequiredSegments = 1;
1902
+ (function (exports$1) {
1903
+ const Mode = requireMode();
1904
+ const NumericData = requireNumericData();
1905
+ const AlphanumericData = requireAlphanumericData();
1906
+ const ByteData = requireByteData();
1907
+ const KanjiData = requireKanjiData();
1908
+ const Regex = requireRegex();
1909
+ const Utils = requireUtils$1();
1910
+ const dijkstra = requireDijkstra();
1911
+
1912
+ /**
1913
+ * Returns UTF8 byte length
1914
+ *
1915
+ * @param {String} str Input string
1916
+ * @return {Number} Number of byte
1917
+ */
1918
+ function getStringByteLength (str) {
1919
+ return unescape(encodeURIComponent(str)).length
1920
+ }
1921
+
1922
+ /**
1923
+ * Get a list of segments of the specified mode
1924
+ * from a string
1925
+ *
1926
+ * @param {Mode} mode Segment mode
1927
+ * @param {String} str String to process
1928
+ * @return {Array} Array of object with segments data
1929
+ */
1930
+ function getSegments (regex, mode, str) {
1931
+ const segments = [];
1932
+ let result;
1933
+
1934
+ while ((result = regex.exec(str)) !== null) {
1935
+ segments.push({
1936
+ data: result[0],
1937
+ index: result.index,
1938
+ mode: mode,
1939
+ length: result[0].length
1940
+ });
1941
+ }
1942
+
1943
+ return segments
1944
+ }
1945
+
1946
+ /**
1947
+ * Extracts a series of segments with the appropriate
1948
+ * modes from a string
1949
+ *
1950
+ * @param {String} dataStr Input string
1951
+ * @return {Array} Array of object with segments data
1952
+ */
1953
+ function getSegmentsFromString (dataStr) {
1954
+ const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
1955
+ const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
1956
+ let byteSegs;
1957
+ let kanjiSegs;
1958
+
1959
+ if (Utils.isKanjiModeEnabled()) {
1960
+ byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
1961
+ kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
1962
+ } else {
1963
+ byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
1964
+ kanjiSegs = [];
1965
+ }
1966
+
1967
+ const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
1968
+
1969
+ return segs
1970
+ .sort(function (s1, s2) {
1971
+ return s1.index - s2.index
1972
+ })
1973
+ .map(function (obj) {
1974
+ return {
1975
+ data: obj.data,
1976
+ mode: obj.mode,
1977
+ length: obj.length
1978
+ }
1979
+ })
1980
+ }
1981
+
1982
+ /**
1983
+ * Returns how many bits are needed to encode a string of
1984
+ * specified length with the specified mode
1985
+ *
1986
+ * @param {Number} length String length
1987
+ * @param {Mode} mode Segment mode
1988
+ * @return {Number} Bit length
1989
+ */
1990
+ function getSegmentBitsLength (length, mode) {
1991
+ switch (mode) {
1992
+ case Mode.NUMERIC:
1993
+ return NumericData.getBitsLength(length)
1994
+ case Mode.ALPHANUMERIC:
1995
+ return AlphanumericData.getBitsLength(length)
1996
+ case Mode.KANJI:
1997
+ return KanjiData.getBitsLength(length)
1998
+ case Mode.BYTE:
1999
+ return ByteData.getBitsLength(length)
2000
+ }
2001
+ }
2002
+
2003
+ /**
2004
+ * Merges adjacent segments which have the same mode
2005
+ *
2006
+ * @param {Array} segs Array of object with segments data
2007
+ * @return {Array} Array of object with segments data
2008
+ */
2009
+ function mergeSegments (segs) {
2010
+ return segs.reduce(function (acc, curr) {
2011
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
2012
+ if (prevSeg && prevSeg.mode === curr.mode) {
2013
+ acc[acc.length - 1].data += curr.data;
2014
+ return acc
2015
+ }
2016
+
2017
+ acc.push(curr);
2018
+ return acc
2019
+ }, [])
2020
+ }
2021
+
2022
+ /**
2023
+ * Generates a list of all possible nodes combination which
2024
+ * will be used to build a segments graph.
2025
+ *
2026
+ * Nodes are divided by groups. Each group will contain a list of all the modes
2027
+ * in which is possible to encode the given text.
2028
+ *
2029
+ * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
2030
+ * The group for '12345' will contain then 3 objects, one for each
2031
+ * possible encoding mode.
2032
+ *
2033
+ * Each node represents a possible segment.
2034
+ *
2035
+ * @param {Array} segs Array of object with segments data
2036
+ * @return {Array} Array of object with segments data
2037
+ */
2038
+ function buildNodes (segs) {
2039
+ const nodes = [];
2040
+ for (let i = 0; i < segs.length; i++) {
2041
+ const seg = segs[i];
2042
+
2043
+ switch (seg.mode) {
2044
+ case Mode.NUMERIC:
2045
+ nodes.push([seg,
2046
+ { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
2047
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2048
+ ]);
2049
+ break
2050
+ case Mode.ALPHANUMERIC:
2051
+ nodes.push([seg,
2052
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2053
+ ]);
2054
+ break
2055
+ case Mode.KANJI:
2056
+ nodes.push([seg,
2057
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2058
+ ]);
2059
+ break
2060
+ case Mode.BYTE:
2061
+ nodes.push([
2062
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2063
+ ]);
2064
+ }
2065
+ }
2066
+
2067
+ return nodes
2068
+ }
2069
+
2070
+ /**
2071
+ * Builds a graph from a list of nodes.
2072
+ * All segments in each node group will be connected with all the segments of
2073
+ * the next group and so on.
2074
+ *
2075
+ * At each connection will be assigned a weight depending on the
2076
+ * segment's byte length.
2077
+ *
2078
+ * @param {Array} nodes Array of object with segments data
2079
+ * @param {Number} version QR Code version
2080
+ * @return {Object} Graph of all possible segments
2081
+ */
2082
+ function buildGraph (nodes, version) {
2083
+ const table = {};
2084
+ const graph = { start: {} };
2085
+ let prevNodeIds = ['start'];
2086
+
2087
+ for (let i = 0; i < nodes.length; i++) {
2088
+ const nodeGroup = nodes[i];
2089
+ const currentNodeIds = [];
2090
+
2091
+ for (let j = 0; j < nodeGroup.length; j++) {
2092
+ const node = nodeGroup[j];
2093
+ const key = '' + i + j;
2094
+
2095
+ currentNodeIds.push(key);
2096
+ table[key] = { node: node, lastCount: 0 };
2097
+ graph[key] = {};
2098
+
2099
+ for (let n = 0; n < prevNodeIds.length; n++) {
2100
+ const prevNodeId = prevNodeIds[n];
2101
+
2102
+ if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
2103
+ graph[prevNodeId][key] =
2104
+ getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
2105
+ getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
2106
+
2107
+ table[prevNodeId].lastCount += node.length;
2108
+ } else {
2109
+ if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
2110
+
2111
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
2112
+ 4 + Mode.getCharCountIndicator(node.mode, version); // switch cost
2113
+ }
2114
+ }
2115
+ }
2116
+
2117
+ prevNodeIds = currentNodeIds;
2118
+ }
2119
+
2120
+ for (let n = 0; n < prevNodeIds.length; n++) {
2121
+ graph[prevNodeIds[n]].end = 0;
2122
+ }
2123
+
2124
+ return { map: graph, table: table }
2125
+ }
2126
+
2127
+ /**
2128
+ * Builds a segment from a specified data and mode.
2129
+ * If a mode is not specified, the more suitable will be used.
2130
+ *
2131
+ * @param {String} data Input data
2132
+ * @param {Mode | String} modesHint Data mode
2133
+ * @return {Segment} Segment
2134
+ */
2135
+ function buildSingleSegment (data, modesHint) {
2136
+ let mode;
2137
+ const bestMode = Mode.getBestModeForData(data);
2138
+
2139
+ mode = Mode.from(modesHint, bestMode);
2140
+
2141
+ // Make sure data can be encoded
2142
+ if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
2143
+ throw new Error('"' + data + '"' +
2144
+ ' cannot be encoded with mode ' + Mode.toString(mode) +
2145
+ '.\n Suggested mode is: ' + Mode.toString(bestMode))
2146
+ }
2147
+
2148
+ // Use Mode.BYTE if Kanji support is disabled
2149
+ if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
2150
+ mode = Mode.BYTE;
2151
+ }
2152
+
2153
+ switch (mode) {
2154
+ case Mode.NUMERIC:
2155
+ return new NumericData(data)
2156
+
2157
+ case Mode.ALPHANUMERIC:
2158
+ return new AlphanumericData(data)
2159
+
2160
+ case Mode.KANJI:
2161
+ return new KanjiData(data)
2162
+
2163
+ case Mode.BYTE:
2164
+ return new ByteData(data)
2165
+ }
2166
+ }
2167
+
2168
+ /**
2169
+ * Builds a list of segments from an array.
2170
+ * Array can contain Strings or Objects with segment's info.
2171
+ *
2172
+ * For each item which is a string, will be generated a segment with the given
2173
+ * string and the more appropriate encoding mode.
2174
+ *
2175
+ * For each item which is an object, will be generated a segment with the given
2176
+ * data and mode.
2177
+ * Objects must contain at least the property "data".
2178
+ * If property "mode" is not present, the more suitable mode will be used.
2179
+ *
2180
+ * @param {Array} array Array of objects with segments data
2181
+ * @return {Array} Array of Segments
2182
+ */
2183
+ exports$1.fromArray = function fromArray (array) {
2184
+ return array.reduce(function (acc, seg) {
2185
+ if (typeof seg === 'string') {
2186
+ acc.push(buildSingleSegment(seg, null));
2187
+ } else if (seg.data) {
2188
+ acc.push(buildSingleSegment(seg.data, seg.mode));
2189
+ }
2190
+
2191
+ return acc
2192
+ }, [])
2193
+ };
2194
+
2195
+ /**
2196
+ * Builds an optimized sequence of segments from a string,
2197
+ * which will produce the shortest possible bitstream.
2198
+ *
2199
+ * @param {String} data Input string
2200
+ * @param {Number} version QR Code version
2201
+ * @return {Array} Array of segments
2202
+ */
2203
+ exports$1.fromString = function fromString (data, version) {
2204
+ const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
2205
+
2206
+ const nodes = buildNodes(segs);
2207
+ const graph = buildGraph(nodes, version);
2208
+ const path = dijkstra.find_path(graph.map, 'start', 'end');
2209
+
2210
+ const optimizedSegs = [];
2211
+ for (let i = 1; i < path.length - 1; i++) {
2212
+ optimizedSegs.push(graph.table[path[i]].node);
2213
+ }
2214
+
2215
+ return exports$1.fromArray(mergeSegments(optimizedSegs))
2216
+ };
2217
+
2218
+ /**
2219
+ * Splits a string in various segments with the modes which
2220
+ * best represent their content.
2221
+ * The produced segments are far from being optimized.
2222
+ * The output of this function is only used to estimate a QR Code version
2223
+ * which may contain the data.
2224
+ *
2225
+ * @param {string} data Input string
2226
+ * @return {Array} Array of segments
2227
+ */
2228
+ exports$1.rawSplit = function rawSplit (data) {
2229
+ return exports$1.fromArray(
2230
+ getSegmentsFromString(data, Utils.isKanjiModeEnabled())
2231
+ )
2232
+ };
2233
+ } (segments));
2234
+ return segments;
2235
+ }
2236
+
2237
+ var hasRequiredQrcode;
2238
+
2239
+ function requireQrcode () {
2240
+ if (hasRequiredQrcode) return qrcode;
2241
+ hasRequiredQrcode = 1;
2242
+ const Utils = requireUtils$1();
2243
+ const ECLevel = requireErrorCorrectionLevel();
2244
+ const BitBuffer = requireBitBuffer();
2245
+ const BitMatrix = requireBitMatrix();
2246
+ const AlignmentPattern = requireAlignmentPattern();
2247
+ const FinderPattern = requireFinderPattern();
2248
+ const MaskPattern = requireMaskPattern();
2249
+ const ECCode = requireErrorCorrectionCode();
2250
+ const ReedSolomonEncoder = requireReedSolomonEncoder();
2251
+ const Version = requireVersion();
2252
+ const FormatInfo = requireFormatInfo();
2253
+ const Mode = requireMode();
2254
+ const Segments = requireSegments();
2255
+
2256
+ /**
2257
+ * QRCode for JavaScript
2258
+ *
2259
+ * modified by Ryan Day for nodejs support
2260
+ * Copyright (c) 2011 Ryan Day
2261
+ *
2262
+ * Licensed under the MIT license:
2263
+ * http://www.opensource.org/licenses/mit-license.php
2264
+ *
2265
+ //---------------------------------------------------------------------
2266
+ // QRCode for JavaScript
2267
+ //
2268
+ // Copyright (c) 2009 Kazuhiko Arase
2269
+ //
2270
+ // URL: http://www.d-project.com/
2271
+ //
2272
+ // Licensed under the MIT license:
2273
+ // http://www.opensource.org/licenses/mit-license.php
2274
+ //
2275
+ // The word "QR Code" is registered trademark of
2276
+ // DENSO WAVE INCORPORATED
2277
+ // http://www.denso-wave.com/qrcode/faqpatent-e.html
2278
+ //
2279
+ //---------------------------------------------------------------------
2280
+ */
2281
+
2282
+ /**
2283
+ * Add finder patterns bits to matrix
2284
+ *
2285
+ * @param {BitMatrix} matrix Modules matrix
2286
+ * @param {Number} version QR Code version
2287
+ */
2288
+ function setupFinderPattern (matrix, version) {
2289
+ const size = matrix.size;
2290
+ const pos = FinderPattern.getPositions(version);
2291
+
2292
+ for (let i = 0; i < pos.length; i++) {
2293
+ const row = pos[i][0];
2294
+ const col = pos[i][1];
2295
+
2296
+ for (let r = -1; r <= 7; r++) {
2297
+ if (row + r <= -1 || size <= row + r) continue
2298
+
2299
+ for (let c = -1; c <= 7; c++) {
2300
+ if (col + c <= -1 || size <= col + c) continue
2301
+
2302
+ if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
2303
+ (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
2304
+ (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
2305
+ matrix.set(row + r, col + c, true, true);
2306
+ } else {
2307
+ matrix.set(row + r, col + c, false, true);
2308
+ }
2309
+ }
2310
+ }
2311
+ }
2312
+ }
2313
+
2314
+ /**
2315
+ * Add timing pattern bits to matrix
2316
+ *
2317
+ * Note: this function must be called before {@link setupAlignmentPattern}
2318
+ *
2319
+ * @param {BitMatrix} matrix Modules matrix
2320
+ */
2321
+ function setupTimingPattern (matrix) {
2322
+ const size = matrix.size;
2323
+
2324
+ for (let r = 8; r < size - 8; r++) {
2325
+ const value = r % 2 === 0;
2326
+ matrix.set(r, 6, value, true);
2327
+ matrix.set(6, r, value, true);
2328
+ }
2329
+ }
2330
+
2331
+ /**
2332
+ * Add alignment patterns bits to matrix
2333
+ *
2334
+ * Note: this function must be called after {@link setupTimingPattern}
2335
+ *
2336
+ * @param {BitMatrix} matrix Modules matrix
2337
+ * @param {Number} version QR Code version
2338
+ */
2339
+ function setupAlignmentPattern (matrix, version) {
2340
+ const pos = AlignmentPattern.getPositions(version);
2341
+
2342
+ for (let i = 0; i < pos.length; i++) {
2343
+ const row = pos[i][0];
2344
+ const col = pos[i][1];
2345
+
2346
+ for (let r = -2; r <= 2; r++) {
2347
+ for (let c = -2; c <= 2; c++) {
2348
+ if (r === -2 || r === 2 || c === -2 || c === 2 ||
2349
+ (r === 0 && c === 0)) {
2350
+ matrix.set(row + r, col + c, true, true);
2351
+ } else {
2352
+ matrix.set(row + r, col + c, false, true);
2353
+ }
2354
+ }
2355
+ }
2356
+ }
2357
+ }
2358
+
2359
+ /**
2360
+ * Add version info bits to matrix
2361
+ *
2362
+ * @param {BitMatrix} matrix Modules matrix
2363
+ * @param {Number} version QR Code version
2364
+ */
2365
+ function setupVersionInfo (matrix, version) {
2366
+ const size = matrix.size;
2367
+ const bits = Version.getEncodedBits(version);
2368
+ let row, col, mod;
2369
+
2370
+ for (let i = 0; i < 18; i++) {
2371
+ row = Math.floor(i / 3);
2372
+ col = i % 3 + size - 8 - 3;
2373
+ mod = ((bits >> i) & 1) === 1;
2374
+
2375
+ matrix.set(row, col, mod, true);
2376
+ matrix.set(col, row, mod, true);
2377
+ }
2378
+ }
2379
+
2380
+ /**
2381
+ * Add format info bits to matrix
2382
+ *
2383
+ * @param {BitMatrix} matrix Modules matrix
2384
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2385
+ * @param {Number} maskPattern Mask pattern reference value
2386
+ */
2387
+ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
2388
+ const size = matrix.size;
2389
+ const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
2390
+ let i, mod;
2391
+
2392
+ for (i = 0; i < 15; i++) {
2393
+ mod = ((bits >> i) & 1) === 1;
2394
+
2395
+ // vertical
2396
+ if (i < 6) {
2397
+ matrix.set(i, 8, mod, true);
2398
+ } else if (i < 8) {
2399
+ matrix.set(i + 1, 8, mod, true);
2400
+ } else {
2401
+ matrix.set(size - 15 + i, 8, mod, true);
2402
+ }
2403
+
2404
+ // horizontal
2405
+ if (i < 8) {
2406
+ matrix.set(8, size - i - 1, mod, true);
2407
+ } else if (i < 9) {
2408
+ matrix.set(8, 15 - i - 1 + 1, mod, true);
2409
+ } else {
2410
+ matrix.set(8, 15 - i - 1, mod, true);
2411
+ }
2412
+ }
2413
+
2414
+ // fixed module
2415
+ matrix.set(size - 8, 8, 1, true);
2416
+ }
2417
+
2418
+ /**
2419
+ * Add encoded data bits to matrix
2420
+ *
2421
+ * @param {BitMatrix} matrix Modules matrix
2422
+ * @param {Uint8Array} data Data codewords
2423
+ */
2424
+ function setupData (matrix, data) {
2425
+ const size = matrix.size;
2426
+ let inc = -1;
2427
+ let row = size - 1;
2428
+ let bitIndex = 7;
2429
+ let byteIndex = 0;
2430
+
2431
+ for (let col = size - 1; col > 0; col -= 2) {
2432
+ if (col === 6) col--;
2433
+
2434
+ while (true) {
2435
+ for (let c = 0; c < 2; c++) {
2436
+ if (!matrix.isReserved(row, col - c)) {
2437
+ let dark = false;
2438
+
2439
+ if (byteIndex < data.length) {
2440
+ dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
2441
+ }
2442
+
2443
+ matrix.set(row, col - c, dark);
2444
+ bitIndex--;
2445
+
2446
+ if (bitIndex === -1) {
2447
+ byteIndex++;
2448
+ bitIndex = 7;
2449
+ }
2450
+ }
2451
+ }
2452
+
2453
+ row += inc;
2454
+
2455
+ if (row < 0 || size <= row) {
2456
+ row -= inc;
2457
+ inc = -inc;
2458
+ break
2459
+ }
2460
+ }
2461
+ }
2462
+ }
2463
+
2464
+ /**
2465
+ * Create encoded codewords from data input
2466
+ *
2467
+ * @param {Number} version QR Code version
2468
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2469
+ * @param {ByteData} data Data input
2470
+ * @return {Uint8Array} Buffer containing encoded codewords
2471
+ */
2472
+ function createData (version, errorCorrectionLevel, segments) {
2473
+ // Prepare data buffer
2474
+ const buffer = new BitBuffer();
2475
+
2476
+ segments.forEach(function (data) {
2477
+ // prefix data with mode indicator (4 bits)
2478
+ buffer.put(data.mode.bit, 4);
2479
+
2480
+ // Prefix data with character count indicator.
2481
+ // The character count indicator is a string of bits that represents the
2482
+ // number of characters that are being encoded.
2483
+ // The character count indicator must be placed after the mode indicator
2484
+ // and must be a certain number of bits long, depending on the QR version
2485
+ // and data mode
2486
+ // @see {@link Mode.getCharCountIndicator}.
2487
+ buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
2488
+
2489
+ // add binary data sequence to buffer
2490
+ data.write(buffer);
2491
+ });
2492
+
2493
+ // Calculate required number of bits
2494
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2495
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2496
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
2497
+
2498
+ // Add a terminator.
2499
+ // If the bit string is shorter than the total number of required bits,
2500
+ // a terminator of up to four 0s must be added to the right side of the string.
2501
+ // If the bit string is more than four bits shorter than the required number of bits,
2502
+ // add four 0s to the end.
2503
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
2504
+ buffer.put(0, 4);
2505
+ }
2506
+
2507
+ // If the bit string is fewer than four bits shorter, add only the number of 0s that
2508
+ // are needed to reach the required number of bits.
2509
+
2510
+ // After adding the terminator, if the number of bits in the string is not a multiple of 8,
2511
+ // pad the string on the right with 0s to make the string's length a multiple of 8.
2512
+ while (buffer.getLengthInBits() % 8 !== 0) {
2513
+ buffer.putBit(0);
2514
+ }
2515
+
2516
+ // Add pad bytes if the string is still shorter than the total number of required bits.
2517
+ // Extend the buffer to fill the data capacity of the symbol corresponding to
2518
+ // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
2519
+ // and 00010001 (0x11) alternately.
2520
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
2521
+ for (let i = 0; i < remainingByte; i++) {
2522
+ buffer.put(i % 2 ? 0x11 : 0xEC, 8);
2523
+ }
2524
+
2525
+ return createCodewords(buffer, version, errorCorrectionLevel)
2526
+ }
2527
+
2528
+ /**
2529
+ * Encode input data with Reed-Solomon and return codewords with
2530
+ * relative error correction bits
2531
+ *
2532
+ * @param {BitBuffer} bitBuffer Data to encode
2533
+ * @param {Number} version QR Code version
2534
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2535
+ * @return {Uint8Array} Buffer containing encoded codewords
2536
+ */
2537
+ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
2538
+ // Total codewords for this QR code version (Data + Error correction)
2539
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2540
+
2541
+ // Total number of error correction codewords
2542
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2543
+
2544
+ // Total number of data codewords
2545
+ const dataTotalCodewords = totalCodewords - ecTotalCodewords;
2546
+
2547
+ // Total number of blocks
2548
+ const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
2549
+
2550
+ // Calculate how many blocks each group should contain
2551
+ const blocksInGroup2 = totalCodewords % ecTotalBlocks;
2552
+ const blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
2553
+
2554
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
2555
+
2556
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
2557
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
2558
+
2559
+ // Number of EC codewords is the same for both groups
2560
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
2561
+
2562
+ // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
2563
+ const rs = new ReedSolomonEncoder(ecCount);
2564
+
2565
+ let offset = 0;
2566
+ const dcData = new Array(ecTotalBlocks);
2567
+ const ecData = new Array(ecTotalBlocks);
2568
+ let maxDataSize = 0;
2569
+ const buffer = new Uint8Array(bitBuffer.buffer);
2570
+
2571
+ // Divide the buffer into the required number of blocks
2572
+ for (let b = 0; b < ecTotalBlocks; b++) {
2573
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
2574
+
2575
+ // extract a block of data from buffer
2576
+ dcData[b] = buffer.slice(offset, offset + dataSize);
2577
+
2578
+ // Calculate EC codewords for this data block
2579
+ ecData[b] = rs.encode(dcData[b]);
2580
+
2581
+ offset += dataSize;
2582
+ maxDataSize = Math.max(maxDataSize, dataSize);
2583
+ }
2584
+
2585
+ // Create final data
2586
+ // Interleave the data and error correction codewords from each block
2587
+ const data = new Uint8Array(totalCodewords);
2588
+ let index = 0;
2589
+ let i, r;
2590
+
2591
+ // Add data codewords
2592
+ for (i = 0; i < maxDataSize; i++) {
2593
+ for (r = 0; r < ecTotalBlocks; r++) {
2594
+ if (i < dcData[r].length) {
2595
+ data[index++] = dcData[r][i];
2596
+ }
2597
+ }
2598
+ }
2599
+
2600
+ // Apped EC codewords
2601
+ for (i = 0; i < ecCount; i++) {
2602
+ for (r = 0; r < ecTotalBlocks; r++) {
2603
+ data[index++] = ecData[r][i];
2604
+ }
2605
+ }
2606
+
2607
+ return data
2608
+ }
2609
+
2610
+ /**
2611
+ * Build QR Code symbol
2612
+ *
2613
+ * @param {String} data Input string
2614
+ * @param {Number} version QR Code version
2615
+ * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
2616
+ * @param {MaskPattern} maskPattern Mask pattern
2617
+ * @return {Object} Object containing symbol data
2618
+ */
2619
+ function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
2620
+ let segments;
2621
+
2622
+ if (Array.isArray(data)) {
2623
+ segments = Segments.fromArray(data);
2624
+ } else if (typeof data === 'string') {
2625
+ let estimatedVersion = version;
2626
+
2627
+ if (!estimatedVersion) {
2628
+ const rawSegments = Segments.rawSplit(data);
2629
+
2630
+ // Estimate best version that can contain raw splitted segments
2631
+ estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel);
2632
+ }
2633
+
2634
+ // Build optimized segments
2635
+ // If estimated version is undefined, try with the highest version
2636
+ segments = Segments.fromString(data, estimatedVersion || 40);
2637
+ } else {
2638
+ throw new Error('Invalid data')
2639
+ }
2640
+
2641
+ // Get the min version that can contain data
2642
+ const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel);
2643
+
2644
+ // If no version is found, data cannot be stored
2645
+ if (!bestVersion) {
2646
+ throw new Error('The amount of data is too big to be stored in a QR Code')
2647
+ }
2648
+
2649
+ // If not specified, use min version as default
2650
+ if (!version) {
2651
+ version = bestVersion;
2652
+
2653
+ // Check if the specified version can contain the data
2654
+ } else if (version < bestVersion) {
2655
+ throw new Error('\n' +
2656
+ 'The chosen QR Code version cannot contain this amount of data.\n' +
2657
+ 'Minimum version required to store current data is: ' + bestVersion + '.\n'
2658
+ )
2659
+ }
2660
+
2661
+ const dataBits = createData(version, errorCorrectionLevel, segments);
2662
+
2663
+ // Allocate matrix buffer
2664
+ const moduleCount = Utils.getSymbolSize(version);
2665
+ const modules = new BitMatrix(moduleCount);
2666
+
2667
+ // Add function modules
2668
+ setupFinderPattern(modules, version);
2669
+ setupTimingPattern(modules);
2670
+ setupAlignmentPattern(modules, version);
2671
+
2672
+ // Add temporary dummy bits for format info just to set them as reserved.
2673
+ // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
2674
+ // since the masking operation must be performed only on the encoding region.
2675
+ // These blocks will be replaced with correct values later in code.
2676
+ setupFormatInfo(modules, errorCorrectionLevel, 0);
2677
+
2678
+ if (version >= 7) {
2679
+ setupVersionInfo(modules, version);
2680
+ }
2681
+
2682
+ // Add data codewords
2683
+ setupData(modules, dataBits);
2684
+
2685
+ if (isNaN(maskPattern)) {
2686
+ // Find best mask pattern
2687
+ maskPattern = MaskPattern.getBestMask(modules,
2688
+ setupFormatInfo.bind(null, modules, errorCorrectionLevel));
2689
+ }
2690
+
2691
+ // Apply mask pattern
2692
+ MaskPattern.applyMask(maskPattern, modules);
2693
+
2694
+ // Replace format info bits with correct values
2695
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
2696
+
2697
+ return {
2698
+ modules: modules,
2699
+ version: version,
2700
+ errorCorrectionLevel: errorCorrectionLevel,
2701
+ maskPattern: maskPattern,
2702
+ segments: segments
2703
+ }
2704
+ }
2705
+
2706
+ /**
2707
+ * QR Code
2708
+ *
2709
+ * @param {String | Array} data Input data
2710
+ * @param {Object} options Optional configurations
2711
+ * @param {Number} options.version QR Code version
2712
+ * @param {String} options.errorCorrectionLevel Error correction level
2713
+ * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
2714
+ */
2715
+ qrcode.create = function create (data, options) {
2716
+ if (typeof data === 'undefined' || data === '') {
2717
+ throw new Error('No input text')
2718
+ }
2719
+
2720
+ let errorCorrectionLevel = ECLevel.M;
2721
+ let version;
2722
+ let mask;
2723
+
2724
+ if (typeof options !== 'undefined') {
2725
+ // Use higher error correction level as default
2726
+ errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
2727
+ version = Version.from(options.version);
2728
+ mask = MaskPattern.from(options.maskPattern);
2729
+
2730
+ if (options.toSJISFunc) {
2731
+ Utils.setToSJISFunction(options.toSJISFunc);
2732
+ }
2733
+ }
2734
+
2735
+ return createSymbol(data, version, errorCorrectionLevel, mask)
2736
+ };
2737
+ return qrcode;
2738
+ }
2739
+
2740
+ var canvas = {};
2741
+
2742
+ var utils = {};
2743
+
2744
+ var hasRequiredUtils;
2745
+
2746
+ function requireUtils () {
2747
+ if (hasRequiredUtils) return utils;
2748
+ hasRequiredUtils = 1;
2749
+ (function (exports$1) {
2750
+ function hex2rgba (hex) {
2751
+ if (typeof hex === 'number') {
2752
+ hex = hex.toString();
2753
+ }
2754
+
2755
+ if (typeof hex !== 'string') {
2756
+ throw new Error('Color should be defined as hex string')
2757
+ }
2758
+
2759
+ let hexCode = hex.slice().replace('#', '').split('');
2760
+ if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
2761
+ throw new Error('Invalid hex color: ' + hex)
2762
+ }
2763
+
2764
+ // Convert from short to long form (fff -> ffffff)
2765
+ if (hexCode.length === 3 || hexCode.length === 4) {
2766
+ hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
2767
+ return [c, c]
2768
+ }));
2769
+ }
2770
+
2771
+ // Add default alpha value
2772
+ if (hexCode.length === 6) hexCode.push('F', 'F');
2773
+
2774
+ const hexValue = parseInt(hexCode.join(''), 16);
2775
+
2776
+ return {
2777
+ r: (hexValue >> 24) & 255,
2778
+ g: (hexValue >> 16) & 255,
2779
+ b: (hexValue >> 8) & 255,
2780
+ a: hexValue & 255,
2781
+ hex: '#' + hexCode.slice(0, 6).join('')
2782
+ }
2783
+ }
2784
+
2785
+ exports$1.getOptions = function getOptions (options) {
2786
+ if (!options) options = {};
2787
+ if (!options.color) options.color = {};
2788
+
2789
+ const margin = typeof options.margin === 'undefined' ||
2790
+ options.margin === null ||
2791
+ options.margin < 0
2792
+ ? 4
2793
+ : options.margin;
2794
+
2795
+ const width = options.width && options.width >= 21 ? options.width : undefined;
2796
+ const scale = options.scale || 4;
2797
+
2798
+ return {
2799
+ width: width,
2800
+ scale: width ? 4 : scale,
2801
+ margin: margin,
2802
+ color: {
2803
+ dark: hex2rgba(options.color.dark || '#000000ff'),
2804
+ light: hex2rgba(options.color.light || '#ffffffff')
2805
+ },
2806
+ type: options.type,
2807
+ rendererOpts: options.rendererOpts || {}
2808
+ }
2809
+ };
2810
+
2811
+ exports$1.getScale = function getScale (qrSize, opts) {
2812
+ return opts.width && opts.width >= qrSize + opts.margin * 2
2813
+ ? opts.width / (qrSize + opts.margin * 2)
2814
+ : opts.scale
2815
+ };
2816
+
2817
+ exports$1.getImageWidth = function getImageWidth (qrSize, opts) {
2818
+ const scale = exports$1.getScale(qrSize, opts);
2819
+ return Math.floor((qrSize + opts.margin * 2) * scale)
2820
+ };
2821
+
2822
+ exports$1.qrToImageData = function qrToImageData (imgData, qr, opts) {
2823
+ const size = qr.modules.size;
2824
+ const data = qr.modules.data;
2825
+ const scale = exports$1.getScale(size, opts);
2826
+ const symbolSize = Math.floor((size + opts.margin * 2) * scale);
2827
+ const scaledMargin = opts.margin * scale;
2828
+ const palette = [opts.color.light, opts.color.dark];
2829
+
2830
+ for (let i = 0; i < symbolSize; i++) {
2831
+ for (let j = 0; j < symbolSize; j++) {
2832
+ let posDst = (i * symbolSize + j) * 4;
2833
+ let pxColor = opts.color.light;
2834
+
2835
+ if (i >= scaledMargin && j >= scaledMargin &&
2836
+ i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
2837
+ const iSrc = Math.floor((i - scaledMargin) / scale);
2838
+ const jSrc = Math.floor((j - scaledMargin) / scale);
2839
+ pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
2840
+ }
2841
+
2842
+ imgData[posDst++] = pxColor.r;
2843
+ imgData[posDst++] = pxColor.g;
2844
+ imgData[posDst++] = pxColor.b;
2845
+ imgData[posDst] = pxColor.a;
2846
+ }
2847
+ }
2848
+ };
2849
+ } (utils));
2850
+ return utils;
2851
+ }
2852
+
2853
+ var hasRequiredCanvas;
2854
+
2855
+ function requireCanvas () {
2856
+ if (hasRequiredCanvas) return canvas;
2857
+ hasRequiredCanvas = 1;
2858
+ (function (exports$1) {
2859
+ const Utils = requireUtils();
2860
+
2861
+ function clearCanvas (ctx, canvas, size) {
2862
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
2863
+
2864
+ if (!canvas.style) canvas.style = {};
2865
+ canvas.height = size;
2866
+ canvas.width = size;
2867
+ canvas.style.height = size + 'px';
2868
+ canvas.style.width = size + 'px';
2869
+ }
2870
+
2871
+ function getCanvasElement () {
2872
+ try {
2873
+ return document.createElement('canvas')
2874
+ } catch (e) {
2875
+ throw new Error('You need to specify a canvas element')
2876
+ }
2877
+ }
2878
+
2879
+ exports$1.render = function render (qrData, canvas, options) {
2880
+ let opts = options;
2881
+ let canvasEl = canvas;
2882
+
2883
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
2884
+ opts = canvas;
2885
+ canvas = undefined;
2886
+ }
2887
+
2888
+ if (!canvas) {
2889
+ canvasEl = getCanvasElement();
2890
+ }
2891
+
2892
+ opts = Utils.getOptions(opts);
2893
+ const size = Utils.getImageWidth(qrData.modules.size, opts);
2894
+
2895
+ const ctx = canvasEl.getContext('2d');
2896
+ const image = ctx.createImageData(size, size);
2897
+ Utils.qrToImageData(image.data, qrData, opts);
2898
+
2899
+ clearCanvas(ctx, canvasEl, size);
2900
+ ctx.putImageData(image, 0, 0);
2901
+
2902
+ return canvasEl
2903
+ };
2904
+
2905
+ exports$1.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
2906
+ let opts = options;
2907
+
2908
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
2909
+ opts = canvas;
2910
+ canvas = undefined;
2911
+ }
2912
+
2913
+ if (!opts) opts = {};
2914
+
2915
+ const canvasEl = exports$1.render(qrData, canvas, opts);
2916
+
2917
+ const type = opts.type || 'image/png';
2918
+ const rendererOpts = opts.rendererOpts || {};
2919
+
2920
+ return canvasEl.toDataURL(type, rendererOpts.quality)
2921
+ };
2922
+ } (canvas));
2923
+ return canvas;
2924
+ }
2925
+
2926
+ var svgTag = {};
2927
+
2928
+ var hasRequiredSvgTag;
2929
+
2930
+ function requireSvgTag () {
2931
+ if (hasRequiredSvgTag) return svgTag;
2932
+ hasRequiredSvgTag = 1;
2933
+ const Utils = requireUtils();
2934
+
2935
+ function getColorAttrib (color, attrib) {
2936
+ const alpha = color.a / 255;
2937
+ const str = attrib + '="' + color.hex + '"';
2938
+
2939
+ return alpha < 1
2940
+ ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
2941
+ : str
2942
+ }
2943
+
2944
+ function svgCmd (cmd, x, y) {
2945
+ let str = cmd + x;
2946
+ if (typeof y !== 'undefined') str += ' ' + y;
2947
+
2948
+ return str
2949
+ }
2950
+
2951
+ function qrToPath (data, size, margin) {
2952
+ let path = '';
2953
+ let moveBy = 0;
2954
+ let newRow = false;
2955
+ let lineLength = 0;
2956
+
2957
+ for (let i = 0; i < data.length; i++) {
2958
+ const col = Math.floor(i % size);
2959
+ const row = Math.floor(i / size);
2960
+
2961
+ if (!col && !newRow) newRow = true;
2962
+
2963
+ if (data[i]) {
2964
+ lineLength++;
2965
+
2966
+ if (!(i > 0 && col > 0 && data[i - 1])) {
2967
+ path += newRow
2968
+ ? svgCmd('M', col + margin, 0.5 + row + margin)
2969
+ : svgCmd('m', moveBy, 0);
2970
+
2971
+ moveBy = 0;
2972
+ newRow = false;
2973
+ }
2974
+
2975
+ if (!(col + 1 < size && data[i + 1])) {
2976
+ path += svgCmd('h', lineLength);
2977
+ lineLength = 0;
2978
+ }
2979
+ } else {
2980
+ moveBy++;
2981
+ }
2982
+ }
2983
+
2984
+ return path
2985
+ }
2986
+
2987
+ svgTag.render = function render (qrData, options, cb) {
2988
+ const opts = Utils.getOptions(options);
2989
+ const size = qrData.modules.size;
2990
+ const data = qrData.modules.data;
2991
+ const qrcodesize = size + opts.margin * 2;
2992
+
2993
+ const bg = !opts.color.light.a
2994
+ ? ''
2995
+ : '<path ' + getColorAttrib(opts.color.light, 'fill') +
2996
+ ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>';
2997
+
2998
+ const path =
2999
+ '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
3000
+ ' d="' + qrToPath(data, size, opts.margin) + '"/>';
3001
+
3002
+ const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"';
3003
+
3004
+ const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ';
3005
+
3006
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n';
3007
+
3008
+ if (typeof cb === 'function') {
3009
+ cb(null, svgTag);
3010
+ }
3011
+
3012
+ return svgTag
3013
+ };
3014
+ return svgTag;
3015
+ }
3016
+
3017
+ var hasRequiredBrowser;
3018
+
3019
+ function requireBrowser () {
3020
+ if (hasRequiredBrowser) return browser;
3021
+ hasRequiredBrowser = 1;
3022
+ const canPromise = requireCanPromise();
3023
+
3024
+ const QRCode = requireQrcode();
3025
+ const CanvasRenderer = requireCanvas();
3026
+ const SvgRenderer = requireSvgTag();
3027
+
3028
+ function renderCanvas (renderFunc, canvas, text, opts, cb) {
3029
+ const args = [].slice.call(arguments, 1);
3030
+ const argsNum = args.length;
3031
+ const isLastArgCb = typeof args[argsNum - 1] === 'function';
3032
+
3033
+ if (!isLastArgCb && !canPromise()) {
3034
+ throw new Error('Callback required as last argument')
3035
+ }
3036
+
3037
+ if (isLastArgCb) {
3038
+ if (argsNum < 2) {
3039
+ throw new Error('Too few arguments provided')
3040
+ }
3041
+
3042
+ if (argsNum === 2) {
3043
+ cb = text;
3044
+ text = canvas;
3045
+ canvas = opts = undefined;
3046
+ } else if (argsNum === 3) {
3047
+ if (canvas.getContext && typeof cb === 'undefined') {
3048
+ cb = opts;
3049
+ opts = undefined;
3050
+ } else {
3051
+ cb = opts;
3052
+ opts = text;
3053
+ text = canvas;
3054
+ canvas = undefined;
3055
+ }
3056
+ }
3057
+ } else {
3058
+ if (argsNum < 1) {
3059
+ throw new Error('Too few arguments provided')
3060
+ }
3061
+
3062
+ if (argsNum === 1) {
3063
+ text = canvas;
3064
+ canvas = opts = undefined;
3065
+ } else if (argsNum === 2 && !canvas.getContext) {
3066
+ opts = text;
3067
+ text = canvas;
3068
+ canvas = undefined;
3069
+ }
3070
+
3071
+ return new Promise(function (resolve, reject) {
3072
+ try {
3073
+ const data = QRCode.create(text, opts);
3074
+ resolve(renderFunc(data, canvas, opts));
3075
+ } catch (e) {
3076
+ reject(e);
3077
+ }
3078
+ })
3079
+ }
3080
+
3081
+ try {
3082
+ const data = QRCode.create(text, opts);
3083
+ cb(null, renderFunc(data, canvas, opts));
3084
+ } catch (e) {
3085
+ cb(e);
3086
+ }
3087
+ }
3088
+
3089
+ browser.create = QRCode.create;
3090
+ browser.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
3091
+ browser.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
3092
+
3093
+ // only svg for now.
3094
+ browser.toString = renderCanvas.bind(null, function (data, _, opts) {
3095
+ return SvgRenderer.render(data, opts)
3096
+ });
3097
+ return browser;
3098
+ }
3099
+
3100
+ requireBrowser();
3101
+
3102
+ /** Solana Mainnet (beta) cluster, e.g. https://api.mainnet-beta.solana.com */
3103
+ const SOLANA_MAINNET_CHAIN = 'solana:mainnet';
3104
+
3105
+ //#region src/base64Utils.ts
3106
+ function fromUint8Array(byteArray) {
3107
+ return window.btoa(String.fromCharCode.call(null, ...byteArray));
3108
+ }
3109
+ function toUint8Array(base64EncodedByteArray) {
3110
+ return new Uint8Array(window.atob(base64EncodedByteArray).split("").map((c) => c.charCodeAt(0)));
3111
+ }
3112
+ //#endregion
3113
+ //#region src/embedded-modal/loadingSpinner.ts
3114
+ const modalHtml$1 = `
3115
+ <div class="mobile-wallet-adapter-embedded-loading-indicator" role="dialog" aria-modal="true" aria-labelledby="modal-title">
3116
+ <div data-modal-close style="position: absolute; width: 100%; height: 100%;"></div>
3117
+ <div class="mobile-wallet-adapter-embedded-loading-container">
3118
+ <div class="mobile-wallet-adapter-embedded-loading-animation"></div>
3119
+ </div>
3120
+ </div>
3121
+ `;
3122
+ const css$6 = `
3123
+ .mobile-wallet-adapter-embedded-loading-indicator {
3124
+ display: flex; /* Use flexbox to center content */
3125
+ justify-content: center; /* Center horizontally */
3126
+ align-items: start; /* Center vertically */
3127
+ position: fixed; /* Stay in place */
3128
+ z-index: 1; /* Sit on top */
3129
+ left: 0;
3130
+ top: 0;
3131
+ width: 100%; /* Full width */
3132
+ height: 100%; /* Full height */
3133
+ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
3134
+ overflow-y: auto; /* enable scrolling */
3135
+ }
3136
+
3137
+ .mobile-wallet-adapter-embedded-loading-container {
3138
+ display: flex;
3139
+ margin: auto;
3140
+ }
3141
+
3142
+ .mobile-wallet-adapter-embedded-loading-animation {
3143
+ position: relative;
3144
+ left: -9999px;
3145
+ width: 10px;
3146
+ height: 10px;
3147
+ border-radius: 5px;
3148
+ background-color: var(--spinner-color);
3149
+ color: var(--spinner-color);
3150
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3151
+ 9999px 0 0 0 var(--spinner-color),
3152
+ 10014px 0 0 0 var(--spinner-color);
3153
+ animation: dot-typing 1.5s infinite linear;
3154
+ }
3155
+
3156
+ @keyframes dot-typing {
3157
+ 0% {
3158
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3159
+ 9999px 0 0 0 var(--spinner-color),
3160
+ 10014px 0 0 0 var(--spinner-color);
3161
+ }
3162
+ 16.667% {
3163
+ box-shadow: 9984px -10px 0 0 var(--spinner-color),
3164
+ 9999px 0 0 0 var(--spinner-color),
3165
+ 10014px 0 0 0 var(--spinner-color);
3166
+ }
3167
+ 33.333% {
3168
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3169
+ 9999px 0 0 0 var(--spinner-color),
3170
+ 10014px 0 0 0 var(--spinner-color);
3171
+ }
3172
+ 50% {
3173
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3174
+ 9999px -10px 0 0 var(--spinner-color),
3175
+ 10014px 0 0 0 var(--spinner-color);
3176
+ }
3177
+ 66.667% {
3178
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3179
+ 9999px 0 0 0 var(--spinner-color),
3180
+ 10014px 0 0 0 var(--spinner-color);
3181
+ }
3182
+ 83.333% {
3183
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3184
+ 9999px 0 0 0 var(--spinner-color),
3185
+ 10014px -10px 0 0 var(--spinner-color);
3186
+ }
3187
+ 100% {
3188
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3189
+ 9999px 0 0 0 var(--spinner-color),
3190
+ 10014px 0 0 0 var(--spinner-color);
3191
+ }
3192
+ }
3193
+ `;
3194
+ var EmbeddedLoadingSpinner = class {
3195
+ #root = null;
3196
+ #eventListeners = {};
3197
+ #listenersAttached = false;
3198
+ dom = null;
3199
+ constructor() {
3200
+ this.init = this.init.bind(this);
3201
+ this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
3202
+ }
3203
+ async init() {
3204
+ console.log("Injecting modal");
3205
+ this.#injectHTML();
3206
+ }
3207
+ open = () => {
3208
+ console.debug("Modal open");
3209
+ this.#attachEventListeners();
3210
+ if (this.#root) this.#root.style.display = "flex";
3211
+ };
3212
+ close = (event = void 0) => {
3213
+ console.debug("Modal close");
3214
+ this.#removeEventListeners();
3215
+ if (this.#root) this.#root.style.display = "none";
3216
+ this.#eventListeners["close"]?.forEach((listener) => listener(event));
3217
+ };
3218
+ addEventListener(event, listener) {
3219
+ this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
3220
+ return () => this.removeEventListener(event, listener);
3221
+ }
3222
+ removeEventListener(event, listener) {
3223
+ this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
3224
+ }
3225
+ #injectHTML() {
3226
+ if (this.dom) return;
3227
+ this.#root = document.createElement("div");
3228
+ this.#root.id = "mobile-wallet-adapter-embedded-root-ui";
3229
+ this.#root.innerHTML = modalHtml$1;
3230
+ this.#root.style.display = "none";
3231
+ const styles = document.createElement("style");
3232
+ styles.id = "mobile-wallet-adapter-embedded-modal-styles";
3233
+ styles.textContent = css$6;
3234
+ const host = document.createElement("div");
3235
+ this.dom = host.attachShadow({ mode: "closed" });
3236
+ host.style.setProperty("--spinner-color", "#FFFFFF");
3237
+ this.dom.appendChild(styles);
3238
+ this.dom.appendChild(this.#root);
3239
+ document.body.appendChild(host);
3240
+ }
3241
+ #attachEventListeners() {
3242
+ if (!this.#root || this.#listenersAttached) return;
3243
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.addEventListener("click", (event) => {
3244
+ this.close(event);
3245
+ }));
3246
+ window.addEventListener("load", this.close);
3247
+ document.addEventListener("keydown", this.#handleKeyDown);
3248
+ this.#listenersAttached = true;
3249
+ }
3250
+ #removeEventListeners() {
3251
+ if (!this.#listenersAttached) return;
3252
+ window.removeEventListener("load", this.close);
3253
+ document.removeEventListener("keydown", this.#handleKeyDown);
3254
+ if (!this.#root) return;
3255
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.removeEventListener("click", this.close));
3256
+ this.#listenersAttached = false;
3257
+ }
3258
+ #handleKeyDown = (event) => {
3259
+ if (event.key === "Escape") this.close(event);
3260
+ };
3261
+ };
3262
+ //#endregion
3263
+ //#region src/embedded-modal/modal.ts
3264
+ const modalHtml = `
3265
+ <div class="mobile-wallet-adapter-embedded-modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
3266
+ <div data-modal-close style="position: absolute; width: 100%; height: 100%;"></div>
3267
+ <div class="mobile-wallet-adapter-embedded-modal-card">
3268
+ <div>
3269
+ <button data-modal-close class="mobile-wallet-adapter-embedded-modal-close">
3270
+ <svg width="14" height="14">
3271
+ <path d="M 6.7125,8.3036995 1.9082,13.108199 c -0.2113,0.2112 -0.4765,0.3168 -0.7957,0.3168 -0.3192,0 -0.5844,-0.1056 -0.7958,-0.3168 C 0.1056,12.896899 0,12.631699 0,12.312499 c 0,-0.3192 0.1056,-0.5844 0.3167,-0.7958 L 5.1212,6.7124995 0.3167,1.9082 C 0.1056,1.6969 0,1.4317 0,1.1125 0,0.7933 0.1056,0.5281 0.3167,0.3167 0.5281,0.1056 0.7933,0 1.1125,0 1.4317,0 1.6969,0.1056 1.9082,0.3167 L 6.7125,5.1212 11.5167,0.3167 C 11.7281,0.1056 11.9933,0 12.3125,0 c 0.3192,0 0.5844,0.1056 0.7957,0.3167 0.2112,0.2114 0.3168,0.4766 0.3168,0.7958 0,0.3192 -0.1056,0.5844 -0.3168,0.7957 L 8.3037001,6.7124995 13.1082,11.516699 c 0.2112,0.2114 0.3168,0.4766 0.3168,0.7958 0,0.3192 -0.1056,0.5844 -0.3168,0.7957 -0.2113,0.2112 -0.4765,0.3168 -0.7957,0.3168 -0.3192,0 -0.5844,-0.1056 -0.7958,-0.3168 z" />
3272
+ </svg>
3273
+ </button>
3274
+ </div>
3275
+ <div class="mobile-wallet-adapter-embedded-modal-content"></div>
3276
+ </div>
3277
+ </div>
3278
+ `;
3279
+ const css$5 = `
3280
+ .mobile-wallet-adapter-embedded-modal-container {
3281
+ display: flex; /* Use flexbox to center content */
3282
+ justify-content: center; /* Center horizontally */
3283
+ align-items: center; /* Center vertically */
3284
+ position: fixed; /* Stay in place */
3285
+ z-index: 2147483647; /* Sit on top */
3286
+ left: 0;
3287
+ top: 0;
3288
+ width: 100%; /* Full width */
3289
+ height: 100%; /* Full height */
3290
+ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
3291
+ overflow-y: auto; /* enable scrolling */
3292
+ }
3293
+
3294
+ .mobile-wallet-adapter-embedded-modal-card {
3295
+ display: flex;
3296
+ flex-direction: column;
3297
+ margin: auto 20px;
3298
+ max-width: 780px;
3299
+ padding: 20px;
3300
+ border-radius: 24px;
3301
+ background: #ffffff;
3302
+ font-family: "Inter Tight", "PT Sans", Calibri, sans-serif;
3303
+ transform: translateY(-200%);
3304
+ animation: slide-in 0.5s forwards;
3305
+ }
3306
+
3307
+ @keyframes slide-in {
3308
+ 100% { transform: translateY(0%); }
3309
+ }
3310
+
3311
+ .mobile-wallet-adapter-embedded-modal-close {
3312
+ display: flex;
3313
+ align-items: center;
3314
+ justify-content: center;
3315
+ width: 32px;
3316
+ height: 32px;
3317
+ cursor: pointer;
3318
+ background: #e4e9e9;
3319
+ border: none;
3320
+ border-radius: 50%;
3321
+ }
3322
+
3323
+ .mobile-wallet-adapter-embedded-modal-close:focus-visible {
3324
+ outline-color: red;
3325
+ }
3326
+
3327
+ .mobile-wallet-adapter-embedded-modal-close svg {
3328
+ fill: #546266;
3329
+ transition: fill 200ms ease 0s;
3330
+ }
3331
+
3332
+ .mobile-wallet-adapter-embedded-modal-close:hover svg {
3333
+ fill: #fff;
3334
+ }
3335
+ `;
3336
+ const fonts = `
3337
+ <link rel="preconnect" href="https://fonts.googleapis.com">
3338
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
3339
+ <link href="https://fonts.googleapis.com/css2?family=Inter+Tight:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
3340
+ `;
3341
+ var EmbeddedModal = class {
3342
+ #root = null;
3343
+ #eventListeners = {};
3344
+ #listenersAttached = false;
3345
+ dom = null;
3346
+ constructor() {
3347
+ this.init = this.init.bind(this);
3348
+ this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
3349
+ }
3350
+ async init() {
3351
+ console.log("Injecting modal");
3352
+ this.#injectHTML();
3353
+ }
3354
+ open = () => {
3355
+ console.debug("Modal open");
3356
+ this.#attachEventListeners();
3357
+ if (this.#root) this.#root.style.display = "flex";
3358
+ };
3359
+ close = (event = void 0) => {
3360
+ console.debug("Modal close");
3361
+ this.#removeEventListeners();
3362
+ if (this.#root) this.#root.style.display = "none";
3363
+ this.#eventListeners["close"]?.forEach((listener) => listener(event));
3364
+ };
3365
+ addEventListener(event, listener) {
3366
+ this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
3367
+ return () => this.removeEventListener(event, listener);
3368
+ }
3369
+ removeEventListener(event, listener) {
3370
+ this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
3371
+ }
3372
+ #injectHTML() {
3373
+ if (document.getElementById("mobile-wallet-adapter-embedded-root-ui")) {
3374
+ if (!this.#root) this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
3375
+ return;
3376
+ }
3377
+ this.#root = document.createElement("div");
3378
+ this.#root.id = "mobile-wallet-adapter-embedded-root-ui";
3379
+ this.#root.innerHTML = modalHtml;
3380
+ this.#root.style.display = "none";
3381
+ const content = this.#root.querySelector(".mobile-wallet-adapter-embedded-modal-content");
3382
+ if (content) content.innerHTML = this.contentHtml;
3383
+ const styles = document.createElement("style");
3384
+ styles.id = "mobile-wallet-adapter-embedded-modal-styles";
3385
+ styles.textContent = css$5 + this.contentStyles;
3386
+ const host = document.createElement("div");
3387
+ host.innerHTML = fonts;
3388
+ this.dom = host.attachShadow({ mode: "closed" });
3389
+ this.dom.appendChild(styles);
3390
+ this.dom.appendChild(this.#root);
3391
+ document.body.appendChild(host);
3392
+ }
3393
+ #attachEventListeners() {
3394
+ if (!this.#root || this.#listenersAttached) return;
3395
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.addEventListener("click", this.close));
3396
+ window.addEventListener("load", this.close);
3397
+ document.addEventListener("keydown", this.#handleKeyDown);
3398
+ this.#listenersAttached = true;
3399
+ }
3400
+ #removeEventListeners() {
3401
+ if (!this.#listenersAttached) return;
3402
+ window.removeEventListener("load", this.close);
3403
+ document.removeEventListener("keydown", this.#handleKeyDown);
3404
+ if (!this.#root) return;
3405
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.removeEventListener("click", this.close));
3406
+ this.#listenersAttached = false;
3407
+ }
3408
+ #handleKeyDown = (event) => {
3409
+ if (event.key === "Escape") this.close(event);
3410
+ };
3411
+ };
3412
+ //#endregion
3413
+ //#region src/embedded-modal/localConnectionModal.ts
3414
+ var LocalConnectionModal = class extends EmbeddedModal {
3415
+ contentStyles = css$3;
3416
+ contentHtml = ErrorDialogHtml$3;
3417
+ initWithCallback(callback) {
3418
+ super.init();
3419
+ this.#prepareLaunchAction(callback);
3420
+ }
3421
+ #prepareLaunchAction(callback) {
3422
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
3423
+ const listener = async () => {
3424
+ launchButton?.removeEventListener("click", listener);
3425
+ this.close();
3426
+ callback();
3427
+ };
3428
+ launchButton?.addEventListener("click", listener);
3429
+ }
3430
+ };
3431
+ const ErrorDialogHtml$3 = `
3432
+ <svg class="mobile-wallet-adapter-embedded-modal-launch-icon" width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
3433
+ <path d="M21.6 48C7.2 48 0 40.8 0 26.4V21.6C0 7.2 7.2 0 21.6 0H26.4C40.8 0 48 7.2 48 21.6V26.4C48 40.8 40.8 48 26.4 48H21.6Z" fill="#15994E"/>
3434
+ <mask id="mask0_189_522" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="8" width="32" height="32">
3435
+ <rect x="8" y="8" width="32" height="32" fill="#D9D9D9"/>
3436
+ </mask>
3437
+ <g mask="url(#mask0_189_522)">
3438
+ <mask id="mask1_189_522" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="8" width="32" height="32">
3439
+ <rect x="8" y="8" width="32" height="32" fill="#D9D9D9"/>
3440
+ </mask>
3441
+ <g mask="url(#mask1_189_522)">
3442
+ <path d="M22.1092 26.1208L19.4498 23.4615C19.1736 23.1851 18.8253 23.0468 18.4048 23.0468C17.9846 23.0468 17.6363 23.1851 17.3598 23.4615C17.0836 23.7377 16.9468 24.0861 16.9495 24.5065C16.9522 24.9267 17.0916 25.275 17.3678 25.5512L21.0405 29.2238C21.3463 29.5276 21.7031 29.6795 22.1108 29.6795C22.5184 29.6795 22.8742 29.5276 23.1782 29.2238L30.5918 21.8098C30.8683 21.5336 31.0065 21.1867 31.0065 20.7692C31.0065 20.3514 30.8683 20.0044 30.5918 19.7282C30.3156 19.4517 29.9673 19.3135 29.5468 19.3135C29.1266 19.3135 28.7784 19.4517 28.5022 19.7282L22.1092 26.1208ZM23.9998 37.6042C22.113 37.6042 20.3425 37.2473 18.6885 36.5335C17.0343 35.8197 15.5954 34.8512 14.3718 33.6278C13.1485 32.4043 12.18 30.9654 11.4662 29.3112C10.7524 27.6572 10.3955 25.8867 10.3955 23.9998C10.3955 22.113 10.7524 20.3425 11.4662 18.6885C12.18 17.0343 13.1485 15.5954 14.3718 14.3718C15.5954 13.1485 17.0343 12.18 18.6885 11.4662C20.3425 10.7524 22.113 10.3955 23.9998 10.3955C25.8867 10.3955 27.6572 10.7524 29.3112 11.4662C30.9654 12.18 32.4043 13.1485 33.6278 14.3718C34.8512 15.5954 35.8197 17.0343 36.5335 18.6885C37.2473 20.3425 37.6042 22.113 37.6042 23.9998C37.6042 25.8867 37.2473 27.6572 36.5335 29.3112C35.8197 30.9654 34.8512 32.4043 33.6278 33.6278C32.4043 34.8512 30.9654 35.8197 29.3112 36.5335C27.6572 37.2473 25.8867 37.6042 23.9998 37.6042Z" fill="white"/>
3443
+ </g>
3444
+ </g>
3445
+ </svg>
3446
+ <div class="mobile-wallet-adapter-embedded-modal-title">Ready to connect!</div>
3447
+ <div>
3448
+ <button data-modal-action id="mobile-wallet-adapter-launch-action" class="mobile-wallet-adapter-embedded-modal-launch-action">
3449
+ Connect Wallet
3450
+ </button>
3451
+ </div>
3452
+ `;
3453
+ const css$3 = `
3454
+ .mobile-wallet-adapter-embedded-modal-close {
3455
+ display: none;
3456
+ }
3457
+ .mobile-wallet-adapter-embedded-modal-content {
3458
+ text-align: center;
3459
+ min-width: 300px;
3460
+ }
3461
+ .mobile-wallet-adapter-embedded-modal-launch-icon {
3462
+ margin-top: 24px;
3463
+ }
3464
+ .mobile-wallet-adapter-embedded-modal-title {
3465
+ margin: 18px 100px 30px 100px;
3466
+ color: #000000;
3467
+ font-size: 2.75em;
3468
+ font-weight: 600;
3469
+ }
3470
+ .mobile-wallet-adapter-embedded-modal-launch-action {
3471
+ display: block;
3472
+ width: 100%;
3473
+ height: 56px;
3474
+ font-size: 1.25em;
3475
+ background: #000000;
3476
+ color: #FFFFFF;
3477
+ border-radius: 18px;
3478
+ }
3479
+ /* Smaller screens */
3480
+ @media all and (max-width: 600px) {
3481
+ .mobile-wallet-adapter-embedded-modal-title {
3482
+ font-size: 1.5em;
3483
+ margin-right: 12px;
3484
+ margin-left: 12px;
3485
+ }
3486
+ }
3487
+ `;
3488
+ //#endregion
3489
+ //#region src/embedded-modal/loopbackBlockedModal.ts
3490
+ var LoopbackPermissionBlockedModal = class extends EmbeddedModal {
3491
+ contentStyles = css$2;
3492
+ get contentHtml() {
3493
+ const instructions = getIsPwaLaunchedAsApp() ? "Long press the app icon on your home screen to open site settings" : "Tap the lock or settings icon in the address bar to open site settings";
3494
+ return ErrorDialogHtml$2.replace("{{PERMISSION_INSTRUCTION_DETAIL}}", instructions);
3495
+ }
3496
+ async init() {
3497
+ super.init();
3498
+ this.#prepareLaunchAction();
3499
+ }
3500
+ #prepareLaunchAction() {
3501
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
3502
+ const listener = async (event) => {
3503
+ launchButton?.removeEventListener("click", listener);
3504
+ this.close(event);
3505
+ };
3506
+ launchButton?.addEventListener("click", listener);
3507
+ }
3508
+ };
3509
+ const ErrorDialogHtml$2 = `
3510
+ <div class="mobile-wallet-adapter-embedded-modal-header">
3511
+ Local Wallet Connection
3512
+ </div>
3513
+ <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
3514
+ <path d="M21.6 48C7.2 48 0 40.8 0 26.4V21.6C0 7.2 7.2 0 21.6 0H26.4C40.8 0 48 7.2 48 21.6V26.4C48 40.8 40.8 48 26.4 48H21.6Z" fill="#ED1515"/>
3515
+ <mask id="mask0_147_1364" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="8" width="32" height="32">
3516
+ <rect x="8" y="8" width="32" height="32" fill="#D9D9D9"/>
3517
+ </mask>
3518
+ <g mask="url(#mask0_147_1364)">
3519
+ <path d="M20.1398 36.2705C19.7363 36.2705 19.3508 36.1945 18.9835 36.0425C18.6162 35.8907 18.2916 35.674 18.0098 35.3922L12.6072 29.9895C12.3254 29.7077 12.1086 29.3832 11.9568 29.0158C11.8048 28.6485 11.7288 28.2631 11.7288 27.8595V20.1395C11.7288 19.736 11.8048 19.3505 11.9568 18.9832C12.1086 18.6158 12.3254 18.2913 12.6072 18.0095L18.0098 12.6068C18.2916 12.3251 18.6162 12.1083 18.9835 11.9565C19.3508 11.8045 19.7363 11.7285 20.1398 11.7285H27.8598C28.2634 11.7285 28.6488 11.8045 29.0162 11.9565C29.3835 12.1083 29.708 12.3251 29.9898 12.6068L35.3925 18.0095C35.6743 18.2913 35.891 18.6158 36.0428 18.9832C36.1948 19.3505 36.2708 19.736 36.2708 20.1395V27.8595C36.2708 28.2631 36.1948 28.6485 36.0428 29.0158C35.891 29.3832 35.6743 29.7077 35.3925 29.9895L29.9898 35.3922C29.708 35.674 29.3835 35.8907 29.0162 36.0425C28.6488 36.1945 28.2634 36.2705 27.8598 36.2705H20.1398ZM20.1732 33.2372H27.8265L33.2375 27.8262V20.1728L27.8265 14.7618H20.1732L14.7622 20.1728V27.8262L20.1732 33.2372ZM23.9998 25.9538L26.7868 28.7408C27.0473 29.0013 27.3729 29.1302 27.7638 29.1275C28.1549 29.1248 28.4807 28.9933 28.7412 28.7328C29.0016 28.4724 29.1318 28.1466 29.1318 27.7555C29.1318 27.3646 29.0016 27.039 28.7412 26.7785L25.9542 23.9995L28.7412 21.2125C29.0016 20.9521 29.1318 20.6264 29.1318 20.2355C29.1318 19.8444 29.0016 19.5186 28.7412 19.2582C28.4807 18.9977 28.1549 18.8675 27.7638 18.8675C27.3729 18.8675 27.0473 18.9977 26.7868 19.2582L23.9998 22.0452L21.2128 19.2582C20.9524 18.9977 20.628 18.8675 20.2398 18.8675C19.8514 18.8675 19.5269 18.9977 19.2665 19.2582C19.006 19.5186 18.8758 19.8444 18.8758 20.2355C18.8758 20.6264 19.006 20.9521 19.2665 21.2125L22.0455 23.9995L19.2585 26.7865C18.998 27.047 18.8692 27.3713 18.8718 27.7595C18.8745 28.148 19.006 28.4724 19.2665 28.7328C19.5269 28.9933 19.8527 29.1235 20.2438 29.1235C20.6347 29.1235 20.9604 28.9933 21.2208 28.7328L23.9998 25.9538Z" fill="black"/>
3520
+ </g>
3521
+ </svg>
3522
+ <div class="mobile-wallet-adapter-embedded-modal-title">
3523
+ Your wallet connection is blocked
3524
+ </div>
3525
+ <div id="mobile-wallet-adapter-local-launch-message" class="mobile-wallet-adapter-embedded-modal-subtitle">
3526
+ Visit site settings in the address bar and allow "Apps on Device".
3527
+ </div>
3528
+
3529
+ <div class="mobile-wallet-adapter-embedded-modal-divider"><hr></div>
3530
+ <div class="mobile-wallet-adapter-embedded-modal-footer">
3531
+ <div class="mobile-wallet-adapter-embedded-modal-details">
3532
+ <!-- Clickable header (label associated with the checkbox) -->
3533
+ <label for="collapsible-1" class="mobile-wallet-adapter-embedded-modal-details-collapsible-header">
3534
+ <!-- Hidden checkbox to track state -->
3535
+ <input type="checkbox" id="collapsible-1" class="mobile-wallet-adapter-embedded-modal-details-collapsible-input">
3536
+ <span class="mobile-wallet-adapter-embedded-modal-details-collapsible-header-label">
3537
+ See details
3538
+ </span>
3539
+ <svg class="mobile-wallet-adapter-embedded-modal-details-collapsible-header-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3540
+ <mask id="mask0_147_1382" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
3541
+ <rect width="24" height="24" fill="#D9D9D9"/>
3542
+ </mask>
3543
+ <g mask="url(#mask0_147_1382)">
3544
+ <path d="M11.9999 17.0811C11.8506 17.0811 11.7087 17.0563 11.5741 17.0067C11.4395 16.957 11.3162 16.8762 11.2042 16.7643L6.57924 12.1393C6.36801 11.9281 6.26656 11.667 6.27489 11.3561C6.28322 11.0453 6.39301 10.7842 6.60424 10.573C6.81547 10.3618 7.08069 10.2561 7.39989 10.2561C7.71909 10.2561 7.9843 10.3618 8.19554 10.573L11.9999 14.3773L15.8292 10.548C16.0405 10.3368 16.3015 10.2353 16.6124 10.2436C16.9233 10.252 17.1843 10.3618 17.3955 10.573C17.6068 10.7842 17.7124 11.0494 17.7124 11.3686C17.7124 11.6878 17.6068 11.9531 17.3955 12.1643L12.7955 16.7643C12.6836 16.8762 12.5603 16.957 12.4257 17.0067C12.2911 17.0563 12.1492 17.0811 11.9999 17.0811Z" fill="black"/>
3545
+ </g>
3546
+ </svg>
3547
+ </label>
3548
+
3549
+ <!-- Content to show/hide -->
3550
+ <ul class="mobile-wallet-adapter-embedded-modal-details-collapsible-content">
3551
+ <li>{{PERMISSION_INSTRUCTION_DETAIL}}</li>
3552
+ <li>Allow "Apps on Device"</li>
3553
+ </ul>
3554
+ </div>
3555
+ </div>
3556
+ <div>
3557
+ <button data-modal-action id="mobile-wallet-adapter-launch-action" class="mobile-wallet-adapter-embedded-modal-launch-action">
3558
+ Got it
3559
+ </button>
3560
+ </div>
3561
+ `;
3562
+ const css$2 = `
3563
+ .mobile-wallet-adapter-embedded-modal-close {
3564
+ display: none;
3565
+ }
3566
+ .mobile-wallet-adapter-embedded-modal-content {
3567
+ text-align: center;
3568
+ }
3569
+ .mobile-wallet-adapter-embedded-modal-header {
3570
+ margin: 18px auto 30px auto;
3571
+ color: #7D9093;
3572
+ font-size: 1.0em;
3573
+ font-weight: 500;
3574
+ }
3575
+ .mobile-wallet-adapter-embedded-modal-title {
3576
+ margin: 18px 100px auto 100px;
3577
+ color: #000000;
3578
+ font-size: 2.75em;
3579
+ font-weight: 600;
3580
+ }
3581
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3582
+ margin: 12px 60px 30px 60px;
3583
+ color: #7D9093;
3584
+ font-size: 1.25em;
3585
+ font-weight: 400;
3586
+ }
3587
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header {
3588
+ display: flex;
3589
+ flex-direction: row;
3590
+ justify-content: space-between;
3591
+ margin: 10px auto 10px auto;
3592
+ color: #000000;
3593
+ font-size: 1.5em;
3594
+ font-weight: 600;
3595
+ cursor: pointer; /* Show pointer on hover */
3596
+ transition: background 0.2s ease; /* Smooth background change */
3597
+ }
3598
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header-icon {
3599
+ transition: rotate 0.3s ease;
3600
+ }
3601
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-input {
3602
+ display: none; /* Hide the checkbox */
3603
+ }
3604
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-content {
3605
+ margin: 0px auto 40px auto;
3606
+ max-height: 0px; /* Collapse content */
3607
+ overflow: hidden; /* Hide overflow when collapsed */
3608
+ transition: max-height 0.3s ease; /* Smooth transition */
3609
+ }
3610
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-content li {
3611
+ margin: 20px auto;
3612
+ color: #000000;
3613
+ font-size: 1.25em;
3614
+ font-weight: 400;
3615
+ text-align: left;
3616
+ }
3617
+ /* When checkbox is checked, show content */
3618
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header:has(> input:checked) ~ .mobile-wallet-adapter-embedded-modal-details-collapsible-content {
3619
+ max-height: 300px;
3620
+ }
3621
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header:has(> input:checked) > .mobile-wallet-adapter-embedded-modal-details-collapsible-header-icon {
3622
+ rotate: 180deg;
3623
+ }
3624
+ .mobile-wallet-adapter-embedded-modal-launch-action {
3625
+ display: block;
3626
+ width: 100%;
3627
+ height: 56px;
3628
+ /*margin-top: 40px;*/
3629
+ font-size: 1.25em;
3630
+ /*line-height: 24px;*/
3631
+ /*letter-spacing: -1%;*/
3632
+ background: #000000;
3633
+ color: #FFFFFF;
3634
+ border-radius: 18px;
3635
+ }
3636
+ /* Smaller screens */
3637
+ @media all and (max-width: 600px) {
3638
+ .mobile-wallet-adapter-embedded-modal-title {
3639
+ font-size: 1.75em;
3640
+ margin-right: 12px;
3641
+ margin-left: 12px;
3642
+ }
3643
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3644
+ margin-right: 12px;
3645
+ margin-left: 12px;
3646
+ }
3647
+ }
3648
+ `;
3649
+ //#endregion
3650
+ //#region src/embedded-modal/loopbackPermissionModal.ts
3651
+ var LoopbackPermissionModal = class extends EmbeddedModal {
3652
+ contentStyles = css$1;
3653
+ contentHtml = ErrorDialogHtml$1;
3654
+ async init() {
3655
+ super.init();
3656
+ this.#prepareLaunchAction();
3657
+ }
3658
+ #prepareLaunchAction() {
3659
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
3660
+ const listener = async () => {
3661
+ launchButton?.removeEventListener("click", listener);
3662
+ try {
3663
+ await fetch("http://localhost");
3664
+ } catch {}
3665
+ this.close();
3666
+ };
3667
+ launchButton?.addEventListener("click", listener);
3668
+ }
3669
+ };
3670
+ const ErrorDialogHtml$1 = `
3671
+ <div class="mobile-wallet-adapter-embedded-modal-title">Allow connections to your wallet</div>
3672
+ <div id="mobile-wallet-adapter-local-launch-message" class="mobile-wallet-adapter-embedded-modal-subtitle">
3673
+ Tap "Allow" on the next screen
3674
+ </div>
3675
+ <svg class="mobile-wallet-adapter-embedded-modal-permission-prompt-mock" xmlns="http://www.w3.org/2000/svg" width="281" height="83" viewBox="0 0 281 83" fill="none">
3676
+ <rect width="281" height="83" rx="22" fill="#F0F3F5"/>
3677
+ <path d="M254.194 64L252.626 56.657H254.047L254.866 61.452L254.985 62.278H255.02L255.146 61.452L255.993 57.497H257.4L258.254 61.431L258.373 62.278H258.415L258.534 61.431L259.346 56.657H260.718L259.143 64H257.673L256.826 59.961L256.693 59.093H256.651L256.511 59.961L255.664 64H254.194Z" fill="black"/>
3678
+ <path d="M248.837 64.231C248.147 64.231 247.54 64.07 247.017 63.748C246.495 63.426 246.086 62.978 245.792 62.404C245.498 61.83 245.351 61.1673 245.351 60.416V60.241C245.351 59.4897 245.498 58.827 245.792 58.253C246.086 57.679 246.495 57.2333 247.017 56.916C247.54 56.594 248.147 56.433 248.837 56.433C249.528 56.433 250.135 56.594 250.657 56.916C251.18 57.2333 251.588 57.679 251.882 58.253C252.176 58.827 252.323 59.4897 252.323 60.241V60.416C252.323 61.1673 252.176 61.83 251.882 62.404C251.588 62.978 251.18 63.426 250.657 63.748C250.135 64.07 249.528 64.231 248.837 64.231ZM248.837 62.824C249.43 62.824 249.897 62.607 250.237 62.173C250.583 61.7343 250.755 61.1417 250.755 60.395V60.262C250.755 59.5107 250.583 58.918 250.237 58.484C249.897 58.05 249.43 57.833 248.837 57.833C248.249 57.833 247.783 58.05 247.437 58.484C247.092 58.918 246.919 59.5107 246.919 60.262V60.395C246.919 61.1417 247.092 61.7343 247.437 62.173C247.783 62.607 248.249 62.824 248.837 62.824Z" fill="black"/>
3679
+ <path d="M242.298 64.231C241.467 64.231 240.814 63.993 240.338 63.517C239.866 63.0364 239.631 62.3737 239.631 61.529V53.78H241.178V61.389C241.178 62.3317 241.591 62.803 242.417 62.803C242.65 62.803 242.865 62.7587 243.061 62.67C243.257 62.5814 243.464 62.4367 243.684 62.236L244.538 63.377C244.225 63.6664 243.884 63.881 243.516 64.021C243.152 64.161 242.746 64.231 242.298 64.231ZM237.51 55.061V53.78H240.611V55.061H237.51Z" fill="black"/>
3680
+ <path d="M234.463 64.231C233.633 64.231 232.979 63.993 232.503 63.517C232.032 63.0364 231.796 62.3737 231.796 61.529V53.78H233.343V61.389C233.343 62.3317 233.756 62.803 234.582 62.803C234.816 62.803 235.03 62.7587 235.226 62.67C235.422 62.5814 235.63 62.4367 235.849 62.236L236.703 63.377C236.391 63.6664 236.05 63.881 235.681 64.021C235.317 64.161 234.911 64.231 234.463 64.231ZM229.675 55.061V53.78H232.776V55.061H229.675Z" fill="black"/>
3681
+ <path d="M221.442 64L224.557 53.976H226.132L229.233 64H227.581L225.642 56.972L225.341 55.761H225.299L225.005 56.972L223.073 64H221.442ZM222.835 61.634L223.255 60.29H227.371L227.805 61.634H222.835Z" fill="black"/>
3682
+ <path d="M178.261 64L175.034 60.066V60.024L178.121 56.657H180.011L176.504 60.423V59.632L180.165 64H178.261ZM173.543 64V53.78H175.097V64H173.543Z" fill="#7D9093" fill-opacity="0.5"/>
3683
+ <path d="M169.306 64.224C168.588 64.224 167.958 64.0653 167.416 63.748C166.88 63.426 166.462 62.9803 166.163 62.411C165.865 61.837 165.715 61.1673 165.715 60.402V60.248C165.715 59.4873 165.862 58.8223 166.156 58.253C166.45 57.679 166.863 57.2333 167.395 56.916C167.927 56.594 168.546 56.433 169.25 56.433C169.978 56.433 170.59 56.6056 171.084 56.951C171.579 57.2917 171.955 57.777 172.211 58.407L170.874 58.995C170.72 58.6123 170.508 58.323 170.237 58.127C169.967 57.9263 169.633 57.826 169.236 57.826C168.63 57.826 168.149 58.0383 167.794 58.463C167.444 58.883 167.269 59.4616 167.269 60.199V60.465C167.269 61.1837 167.454 61.7577 167.822 62.187C168.196 62.6163 168.69 62.831 169.306 62.831C169.712 62.831 170.06 62.733 170.349 62.537C170.639 62.341 170.877 62.0423 171.063 61.641L172.379 62.285C172.188 62.6957 171.941 63.0457 171.637 63.335C171.334 63.6243 170.986 63.846 170.594 64C170.202 64.1493 169.773 64.224 169.306 64.224Z" fill="#7D9093" fill-opacity="0.5"/>
3684
+ <path d="M161.003 64.231C160.312 64.231 159.706 64.07 159.183 63.748C158.66 63.426 158.252 62.978 157.958 62.404C157.664 61.83 157.517 61.1673 157.517 60.416V60.241C157.517 59.4897 157.664 58.827 157.958 58.253C158.252 57.679 158.66 57.2333 159.183 56.916C159.706 56.594 160.312 56.433 161.003 56.433C161.694 56.433 162.3 56.594 162.823 56.916C163.346 57.2333 163.754 57.679 164.048 58.253C164.342 58.827 164.489 59.4897 164.489 60.241V60.416C164.489 61.1673 164.342 61.83 164.048 62.404C163.754 62.978 163.346 63.426 162.823 63.748C162.3 64.07 161.694 64.231 161.003 64.231ZM161.003 62.824C161.596 62.824 162.062 62.607 162.403 62.173C162.748 61.7343 162.921 61.1417 162.921 60.395V60.262C162.921 59.5107 162.748 58.918 162.403 58.484C162.062 58.05 161.596 57.833 161.003 57.833C160.415 57.833 159.948 58.05 159.603 58.484C159.258 58.918 159.085 59.5107 159.085 60.262V60.395C159.085 61.1417 159.258 61.7343 159.603 62.173C159.948 62.607 160.415 62.824 161.003 62.824Z" fill="#7D9093" fill-opacity="0.5"/>
3685
+ <path d="M154.463 64.231C153.633 64.231 152.979 63.993 152.503 63.517C152.032 63.0364 151.796 62.3737 151.796 61.529V53.78H153.343V61.389C153.343 62.3317 153.756 62.803 154.582 62.803C154.816 62.803 155.03 62.7587 155.226 62.67C155.422 62.5814 155.63 62.4367 155.849 62.236L156.703 63.377C156.391 63.6664 156.05 63.881 155.681 64.021C155.317 64.161 154.911 64.231 154.463 64.231ZM149.675 55.061V53.78H152.776V55.061H149.675Z" fill="#7D9093" fill-opacity="0.5"/>
3686
+ <path d="M142.24 64V53.976H145.544C146.421 53.976 147.112 54.1953 147.616 54.634C148.12 55.0726 148.372 55.6583 148.372 56.391V56.566C148.372 57.0886 148.246 57.5366 147.994 57.91C147.742 58.2833 147.38 58.5586 146.909 58.736V58.792C147.492 58.9226 147.947 59.2003 148.274 59.625C148.605 60.045 148.771 60.5606 148.771 61.172V61.361C148.771 61.893 148.645 62.3573 148.393 62.754C148.145 63.1506 147.795 63.4586 147.343 63.678C146.895 63.8926 146.365 64 145.754 64H142.24ZM143.794 62.656H145.572C146.085 62.656 146.482 62.5253 146.762 62.264C147.042 62.0026 147.182 61.6293 147.182 61.144V60.99C147.182 60.5046 147.037 60.1313 146.748 59.87C146.463 59.604 146.05 59.471 145.509 59.471H143.36V58.183H145.32C145.791 58.183 146.153 58.064 146.405 57.826C146.657 57.588 146.783 57.2496 146.783 56.811V56.685C146.783 56.2416 146.657 55.9033 146.405 55.67C146.157 55.4366 145.796 55.32 145.32 55.32H143.794V62.656Z" fill="#7D9093" fill-opacity="0.5"/>
3687
+ <rect x="18" y="17" width="246" height="7" rx="3.5" fill="#7D9093" fill-opacity="0.26"/>
3688
+ <rect x="18" y="33" width="82" height="7" rx="3.5" fill="#7D9093" fill-opacity="0.26"/>
3689
+ </svg>
3690
+ <div>
3691
+ <button data-modal-action id="mobile-wallet-adapter-launch-action" class="mobile-wallet-adapter-embedded-modal-launch-action">
3692
+ Continue to Allow
3693
+ </button>
3694
+ </div>
3695
+ `;
3696
+ const css$1 = `
3697
+ .mobile-wallet-adapter-embedded-modal-close {
3698
+ display: none;
3699
+ }
3700
+ .mobile-wallet-adapter-embedded-modal-content {
3701
+ text-align: center;
3702
+ }
3703
+ .mobile-wallet-adapter-embedded-modal-title {
3704
+ margin: 18px 100px auto 100px;
3705
+ color: #000000;
3706
+ font-size: 2.75em;
3707
+ font-weight: 600;
3708
+ }
3709
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3710
+ margin: 20px 60px 40px 60px;
3711
+ color: #7D9093;
3712
+ font-size: 1.25em;
3713
+ font-weight: 400;
3714
+ }
3715
+ .mobile-wallet-adapter-embedded-modal-permission-prompt-mock {
3716
+ width: 90%;
3717
+ height: auto;
3718
+ margin: 0 auto 30px auto;
3719
+ display: block;
3720
+ }
3721
+ .mobile-wallet-adapter-embedded-modal-launch-action {
3722
+ display: block;
3723
+ width: 100%;
3724
+ height: 56px;
3725
+ font-size: 1.25em;
3726
+ background: #000000;
3727
+ color: #FFFFFF;
3728
+ border-radius: 18px;
3729
+ }
3730
+ /* Smaller screens */
3731
+ @media all and (max-width: 600px) {
3732
+ .mobile-wallet-adapter-embedded-modal-title {
3733
+ font-size: 1.5em;
3734
+ margin-right: 12px;
3735
+ margin-left: 12px;
3736
+ }
3737
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3738
+ margin-right: 12px;
3739
+ margin-left: 12px;
3740
+ }
3741
+ }
3742
+ `;
3743
+ function isSolanaMobileWebShell(userAgentString) {
3744
+ return userAgentString.includes("Solana Mobile Web Shell");
3745
+ }
3746
+ function getIsPwaLaunchedAsApp() {
3747
+ const isAndroidTwa = typeof document !== "undefined" && document.referrer.startsWith("android-app://");
3748
+ if (typeof window == "undefined") return isAndroidTwa;
3749
+ const isStandalone = window.matchMedia("(display-mode: standalone)").matches;
3750
+ const isFullscreen = window.matchMedia("(display-mode: fullscreen)").matches;
3751
+ const isMinimalUI = window.matchMedia("(display-mode: minimal-ui)").matches;
3752
+ return isAndroidTwa || isStandalone || isFullscreen || isMinimalUI;
3753
+ }
3754
+ async function checkLocalNetworkAccessPermission() {
3755
+ if (typeof navigator !== "undefined" && isSolanaMobileWebShell(navigator.userAgent)) return;
3756
+ try {
3757
+ const lnaPermission = await navigator.permissions.query({ name: "loopback-network" });
3758
+ if (lnaPermission.state === "granted") return;
3759
+ else if (lnaPermission.state === "denied") {
3760
+ const modal = new LoopbackPermissionBlockedModal();
3761
+ modal.init();
3762
+ modal.open();
3763
+ throw new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, "Local Network Access permission denied");
3764
+ } else if (lnaPermission.state === "prompt") {
3765
+ const modal = new LoopbackPermissionModal();
3766
+ if (await new Promise((resolve, reject) => {
3767
+ modal.addEventListener("close", (event) => {
3768
+ if (event) reject(new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection cancelled by user", { event }));
3769
+ });
3770
+ lnaPermission.onchange = () => {
3771
+ lnaPermission.onchange = null;
3772
+ resolve(lnaPermission.state);
3773
+ };
3774
+ modal.init();
3775
+ modal.open();
3776
+ }) === "granted") {
3777
+ const modal = new LocalConnectionModal();
3778
+ await new Promise((resolve, reject) => {
3779
+ modal.addEventListener("close", (event) => {
3780
+ if (event) reject(new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection cancelled by user", { event }));
3781
+ });
3782
+ modal.initWithCallback(async () => {
3783
+ resolve(true);
3784
+ });
3785
+ modal.open();
3786
+ });
3787
+ return;
3788
+ } else return await checkLocalNetworkAccessPermission();
3789
+ }
3790
+ throw new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, "Local Network Access permission unknown");
3791
+ } catch (e) {
3792
+ if (e instanceof TypeError && (e.message.includes("loopback-network") || e.message.includes("local-network-access"))) return;
3793
+ if (e instanceof mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError) throw e;
3794
+ throw new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, e instanceof Error ? e.message : "Local Network Access permission unknown");
3795
+ }
3796
+ }
3797
+ //#endregion
3798
+ //#region src/icon.ts
3799
+ const icon = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDIuNUgxN0MxNy44Mjg0IDIuNSAxOC41IDMuMTcxNTcgMTguNSA0VjIwQzE4LjUgMjAuODI4NCAxNy44Mjg0IDIxLjUgMTcgMjEuNUg3QzYuMTcxNTcgMjEuNSA1LjUgMjAuODI4NCA1LjUgMjBWNEM1LjUgMy4xNzE1NyA2LjE3MTU3IDIuNSA3IDIuNVpNMyA0QzMgMS43OTA4NiA0Ljc5MDg2IDAgNyAwSDE3QzE5LjIwOTEgMCAyMSAxLjc5MDg2IDIxIDRWMjBDMjEgMjIuMjA5MSAxOS4yMDkxIDI0IDE3IDI0SDdDNC43OTA4NiAyNCAzIDIyLjIwOTEgMyAyMFY0Wk0xMSA0LjYxNTM4QzEwLjQ0NzcgNC42MTUzOCAxMCA1LjA2MzEgMTAgNS42MTUzOFY2LjM4NDYyQzEwIDYuOTM2OSAxMC40NDc3IDcuMzg0NjIgMTEgNy4zODQ2MkgxM0MxMy41NTIzIDcuMzg0NjIgMTQgNi45MzY5IDE0IDYuMzg0NjJWNS42MTUzOEMxNCA1LjA2MzEgMTMuNTUyMyA0LjYxNTM4IDEzIDQuNjE1MzhIMTFaIiBmaWxsPSIjRENCOEZGIi8+Cjwvc3ZnPgo=";
3800
+ //#endregion
3801
+ //#region src/wallet.ts
3802
+ const SolanaMobileWalletAdapterWalletName = "Mobile Wallet Adapter";
3803
+ const SIGNATURE_LENGTH_IN_BYTES = 64;
3804
+ const DEFAULT_FEATURES = [
3805
+ SolanaSignAndSendTransaction,
3806
+ SolanaSignTransaction,
3807
+ SolanaSignMessage,
3808
+ SolanaSignIn
3809
+ ];
3810
+ const WALLET_ASSOCIATION_TIMEOUT = 3e4;
3811
+ function getErrorMessage(error) {
3812
+ return error instanceof Error ? error.message : "Unknown error";
3813
+ }
3814
+ var LocalSolanaMobileWalletAdapterWallet = class {
3815
+ #listeners = {};
3816
+ #version = "1.0.0";
3817
+ #name = SolanaMobileWalletAdapterWalletName;
3818
+ #url = "https://solanamobile.com/wallets";
3819
+ #icon = icon;
3820
+ #appIdentity;
3821
+ #authorization;
3822
+ #authorizationCache;
3823
+ #connecting = false;
3824
+ /**
3825
+ * Every time the connection is recycled in some way (eg. `disconnect()` is called)
3826
+ * increment this and use it to make sure that `transact` calls from the previous
3827
+ * 'generation' don't continue to do work and throw exceptions.
3828
+ */
3829
+ #connectionGeneration = 0;
3830
+ #chains = [];
3831
+ #chainSelector;
3832
+ #optionalFeatures;
3833
+ #onWalletNotFound;
3834
+ get version() {
3835
+ return this.#version;
3836
+ }
3837
+ get name() {
3838
+ return this.#name;
3839
+ }
3840
+ get url() {
3841
+ return this.#url;
3842
+ }
3843
+ get icon() {
3844
+ return this.#icon;
3845
+ }
3846
+ get chains() {
3847
+ return this.#chains;
3848
+ }
3849
+ get features() {
3850
+ return {
3851
+ [StandardConnect]: {
3852
+ version: "1.0.0",
3853
+ connect: this.#connect
3854
+ },
3855
+ [StandardDisconnect]: {
3856
+ version: "1.0.0",
3857
+ disconnect: this.#disconnect
3858
+ },
3859
+ [StandardEvents]: {
3860
+ version: "1.0.0",
3861
+ on: this.#on
3862
+ },
3863
+ [SolanaSignMessage]: {
3864
+ version: "1.0.0",
3865
+ signMessage: this.#signMessage
3866
+ },
3867
+ [SolanaSignIn]: {
3868
+ version: "1.0.0",
3869
+ signIn: this.#signIn
3870
+ },
3871
+ ...this.#optionalFeatures
3872
+ };
3873
+ }
3874
+ get accounts() {
3875
+ return this.#authorization?.accounts ?? [];
3876
+ }
3877
+ constructor(config) {
3878
+ this.#authorizationCache = config.authorizationCache;
3879
+ this.#appIdentity = config.appIdentity;
3880
+ this.#chains = config.chains;
3881
+ this.#chainSelector = config.chainSelector;
3882
+ this.#onWalletNotFound = config.onWalletNotFound;
3883
+ this.#optionalFeatures = {
3884
+ [SolanaSignAndSendTransaction]: {
3885
+ version: "1.0.0",
3886
+ supportedTransactionVersions: ["legacy", 0],
3887
+ signAndSendTransaction: this.#signAndSendTransaction
3888
+ },
3889
+ [SolanaSignTransaction]: {
3890
+ version: "1.0.0",
3891
+ supportedTransactionVersions: ["legacy", 0],
3892
+ signTransaction: this.#signTransaction
3893
+ }
3894
+ };
3895
+ }
3896
+ get connected() {
3897
+ return !!this.#authorization;
3898
+ }
3899
+ get isAuthorized() {
3900
+ return !!this.#authorization;
3901
+ }
3902
+ get currentAuthorization() {
3903
+ return this.#authorization;
3904
+ }
3905
+ get cachedAuthorizationResult() {
3906
+ return this.#authorizationCache.get();
3907
+ }
3908
+ #on = (event, listener) => {
3909
+ this.#listeners[event]?.push(listener) || (this.#listeners[event] = [listener]);
3910
+ return () => this.#off(event, listener);
3911
+ };
3912
+ #emit(event, ...args) {
3913
+ this.#listeners[event]?.forEach((listener) => listener.apply(null, args));
3914
+ }
3915
+ #off(event, listener) {
3916
+ this.#listeners[event] = this.#listeners[event]?.filter((existingListener) => listener !== existingListener);
3917
+ }
3918
+ #connect = async ({ silent } = {}) => {
3919
+ if (this.#connecting || this.connected) return { accounts: this.accounts };
3920
+ this.#connecting = true;
3921
+ try {
3922
+ if (silent) {
3923
+ const cachedAuthorization = await this.#authorizationCache.get();
3924
+ if (cachedAuthorization) {
3925
+ await this.#handleWalletCapabilitiesResult(cachedAuthorization.capabilities);
3926
+ await this.#handleAuthorizationResult(cachedAuthorization);
3927
+ } else return { accounts: this.accounts };
3928
+ } else await this.#performAuthorization();
3929
+ } catch (e) {
3930
+ throw new Error(getErrorMessage(e), { cause: e });
3931
+ } finally {
3932
+ this.#connecting = false;
3933
+ }
3934
+ return { accounts: this.accounts };
3935
+ };
3936
+ #performAuthorization = async (signInPayload) => {
3937
+ try {
3938
+ const cachedAuthorizationResult = await this.#authorizationCache.get();
3939
+ if (cachedAuthorizationResult) {
3940
+ this.#handleAuthorizationResult(cachedAuthorizationResult);
3941
+ return cachedAuthorizationResult;
3942
+ }
3943
+ const selectedChain = await this.#chainSelector.select(this.#chains);
3944
+ return await this.#transact(async (wallet) => {
3945
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([wallet.getCapabilities(), wallet.authorize({
3946
+ chain: selectedChain,
3947
+ identity: this.#appIdentity,
3948
+ sign_in_payload: signInPayload
3949
+ })]);
3950
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
3951
+ const authorization = {
3952
+ ...mwaAuthorizationResult,
3953
+ accounts,
3954
+ chain: selectedChain,
3955
+ capabilities
3956
+ };
3957
+ Promise.all([
3958
+ this.#handleWalletCapabilitiesResult(capabilities),
3959
+ this.#authorizationCache.set(authorization),
3960
+ this.#handleAuthorizationResult(authorization)
3961
+ ]);
3962
+ return authorization;
3963
+ });
3964
+ } catch (e) {
3965
+ throw new Error(getErrorMessage(e), { cause: e });
3966
+ }
3967
+ };
3968
+ #handleAuthorizationResult = async (authorization) => {
3969
+ const didPublicKeysChange = this.#authorization == null || this.#authorization?.accounts.length !== authorization.accounts.length || this.#authorization.accounts.some((account, ii) => account.address !== authorization.accounts[ii].address);
3970
+ this.#authorization = authorization;
3971
+ if (didPublicKeysChange) this.#emit("change", { accounts: this.accounts });
3972
+ };
3973
+ #handleWalletCapabilitiesResult = async (capabilities) => {
3974
+ const supportsSignTransaction = capabilities.features.includes("solana:signTransactions");
3975
+ const supportsSignAndSendTransaction = capabilities.supports_sign_and_send_transactions;
3976
+ const didCapabilitiesChange = SolanaSignAndSendTransaction in this.features !== supportsSignAndSendTransaction || SolanaSignTransaction in this.features !== supportsSignTransaction;
3977
+ this.#optionalFeatures = {
3978
+ ...(supportsSignAndSendTransaction || !supportsSignAndSendTransaction && !supportsSignTransaction) && { [SolanaSignAndSendTransaction]: {
3979
+ version: "1.0.0",
3980
+ supportedTransactionVersions: ["legacy", 0],
3981
+ signAndSendTransaction: this.#signAndSendTransaction
3982
+ } },
3983
+ ...supportsSignTransaction && { [SolanaSignTransaction]: {
3984
+ version: "1.0.0",
3985
+ supportedTransactionVersions: ["legacy", 0],
3986
+ signTransaction: this.#signTransaction
3987
+ } }
3988
+ };
3989
+ if (didCapabilitiesChange) this.#emit("change", { features: this.features });
3990
+ };
3991
+ #performReauthorization = async (wallet, authToken, chain) => {
3992
+ try {
3993
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([this.#authorization?.capabilities ?? await wallet.getCapabilities(), wallet.authorize({
3994
+ auth_token: authToken,
3995
+ identity: this.#appIdentity,
3996
+ chain
3997
+ })]);
3998
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
3999
+ const authorization = {
4000
+ ...mwaAuthorizationResult,
4001
+ accounts,
4002
+ chain,
4003
+ capabilities
4004
+ };
4005
+ Promise.all([this.#authorizationCache.set(authorization), this.#handleAuthorizationResult(authorization)]);
4006
+ } catch (e) {
4007
+ this.#disconnect();
4008
+ throw new Error(getErrorMessage(e), { cause: e });
4009
+ }
4010
+ };
4011
+ #disconnect = async () => {
4012
+ this.#authorizationCache.clear();
4013
+ this.#connecting = false;
4014
+ this.#connectionGeneration++;
4015
+ this.#authorization = void 0;
4016
+ this.#emit("change", { accounts: this.accounts });
4017
+ };
4018
+ #transact = async (callback) => {
4019
+ const walletUriBase = this.#authorization?.wallet_uri_base;
4020
+ const config = walletUriBase ? { baseUri: walletUriBase } : void 0;
4021
+ const currentConnectionGeneration = this.#connectionGeneration;
4022
+ const loadingSpinner = new EmbeddedLoadingSpinner();
4023
+ try {
4024
+ let associating = true;
4025
+ let timeout = void 0;
4026
+ const result = await Promise.race([checkLocalNetworkAccessPermission().then(async () => {
4027
+ loadingSpinner.init();
4028
+ const { wallet, close } = await mobileWalletAdapterProtocol.startScenario(config);
4029
+ associating = false;
4030
+ loadingSpinner.addEventListener("close", (event) => {
4031
+ if (event) close();
4032
+ });
4033
+ loadingSpinner.open();
4034
+ const result = await callback(await wallet);
4035
+ loadingSpinner.close();
4036
+ close();
4037
+ return result;
4038
+ }), new Promise((_, reject) => {
4039
+ timeout = setTimeout(() => {
4040
+ if (associating) reject(new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection timed out", { event: void 0 }));
4041
+ }, WALLET_ASSOCIATION_TIMEOUT);
4042
+ })]);
4043
+ clearTimeout(timeout);
4044
+ return result;
4045
+ } catch (e) {
4046
+ loadingSpinner.close();
4047
+ if (this.#connectionGeneration !== currentConnectionGeneration) await new Promise(() => {});
4048
+ if (e instanceof Error && e.name === "SolanaMobileWalletAdapterError" && e.code === "ERROR_WALLET_NOT_FOUND") await this.#onWalletNotFound(this);
4049
+ throw e;
4050
+ }
4051
+ };
4052
+ #assertIsAuthorized = () => {
4053
+ if (!this.#authorization) throw new Error("Wallet not connected");
4054
+ return {
4055
+ authToken: this.#authorization.auth_token,
4056
+ chain: this.#authorization.chain
4057
+ };
4058
+ };
4059
+ #accountsToWalletStandardAccounts = (accounts) => {
4060
+ return accounts.map((account) => {
4061
+ const publicKey = toUint8Array(account.address);
4062
+ return {
4063
+ address: index_native.base58.encode(publicKey),
4064
+ publicKey,
4065
+ label: account.label,
4066
+ icon: account.icon,
4067
+ chains: account.chains ?? this.#chains,
4068
+ features: account.features ?? DEFAULT_FEATURES
4069
+ };
4070
+ });
4071
+ };
4072
+ #performSignTransactions = async (transactions) => {
4073
+ const { authToken, chain } = this.#assertIsAuthorized();
4074
+ try {
4075
+ const base64Transactions = transactions.map((tx) => {
4076
+ return fromUint8Array(tx);
4077
+ });
4078
+ return await this.#transact(async (wallet) => {
4079
+ await this.#performReauthorization(wallet, authToken, chain);
4080
+ return (await wallet.signTransactions({ payloads: base64Transactions })).signed_payloads.map(toUint8Array);
4081
+ });
4082
+ } catch (e) {
4083
+ throw new Error(getErrorMessage(e), { cause: e });
4084
+ }
4085
+ };
4086
+ #performSignAndSendTransaction = async (transaction, options) => {
4087
+ const { authToken, chain } = this.#assertIsAuthorized();
4088
+ try {
4089
+ return await this.#transact(async (wallet) => {
4090
+ const [capabilities] = await Promise.all([wallet.getCapabilities(), this.#performReauthorization(wallet, authToken, chain)]);
4091
+ if (capabilities.supports_sign_and_send_transactions) {
4092
+ const base64Transaction = fromUint8Array(transaction);
4093
+ return (await wallet.signAndSendTransactions({
4094
+ ...options,
4095
+ payloads: [base64Transaction]
4096
+ })).signatures.map(toUint8Array)[0];
4097
+ } else throw new Error("connected wallet does not support signAndSendTransaction");
4098
+ });
4099
+ } catch (e) {
4100
+ throw new Error(getErrorMessage(e), { cause: e });
4101
+ }
4102
+ };
4103
+ #signAndSendTransaction = async (...inputs) => {
4104
+ const outputs = [];
4105
+ for (const input of inputs) {
4106
+ const signature = await this.#performSignAndSendTransaction(input.transaction, input.options);
4107
+ outputs.push({ signature });
4108
+ }
4109
+ return outputs;
4110
+ };
4111
+ #signTransaction = async (...inputs) => {
4112
+ return (await this.#performSignTransactions(inputs.map(({ transaction }) => transaction))).map((signedTransaction) => {
4113
+ return { signedTransaction };
4114
+ });
4115
+ };
4116
+ #signMessage = async (...inputs) => {
4117
+ const { authToken, chain } = this.#assertIsAuthorized();
4118
+ const addresses = inputs.map(({ account }) => fromUint8Array(new Uint8Array(account.publicKey)));
4119
+ const messages = inputs.map(({ message }) => fromUint8Array(message));
4120
+ try {
4121
+ return await this.#transact(async (wallet) => {
4122
+ await this.#performReauthorization(wallet, authToken, chain);
4123
+ return (await wallet.signMessages({
4124
+ addresses,
4125
+ payloads: messages
4126
+ })).signed_payloads.map(toUint8Array).map((signedMessage) => {
4127
+ return {
4128
+ signedMessage,
4129
+ signature: signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES)
4130
+ };
4131
+ });
4132
+ });
4133
+ } catch (e) {
4134
+ throw new Error(getErrorMessage(e), { cause: e });
4135
+ }
4136
+ };
4137
+ #signIn = async (...inputs) => {
4138
+ const outputs = [];
4139
+ if (inputs.length > 1) for (const input of inputs) outputs.push(await this.#performSignIn(input));
4140
+ else return [await this.#performSignIn(inputs[0])];
4141
+ return outputs;
4142
+ };
4143
+ #performSignIn = async (input) => {
4144
+ this.#connecting = true;
4145
+ try {
4146
+ const authorizationResult = await this.#performAuthorization({
4147
+ ...input,
4148
+ domain: input?.domain ?? window.location.host
4149
+ });
4150
+ if (!authorizationResult.sign_in_result) throw new Error("Sign in failed, no sign in result returned by wallet");
4151
+ const signedInAddress = authorizationResult.sign_in_result.address;
4152
+ const signedInAccount = authorizationResult.accounts.find((acc) => acc.address == signedInAddress);
4153
+ return {
4154
+ account: {
4155
+ ...signedInAccount ?? { address: index_native.base58.encode(toUint8Array(signedInAddress)) },
4156
+ publicKey: toUint8Array(signedInAddress),
4157
+ chains: signedInAccount?.chains ?? this.#chains,
4158
+ features: signedInAccount?.features ?? authorizationResult.capabilities.features
4159
+ },
4160
+ signedMessage: toUint8Array(authorizationResult.sign_in_result.signed_message),
4161
+ signature: toUint8Array(authorizationResult.sign_in_result.signature)
4162
+ };
4163
+ } catch (e) {
4164
+ throw new Error(getErrorMessage(e), { cause: e });
4165
+ } finally {
4166
+ this.#connecting = false;
4167
+ }
4168
+ };
4169
+ };
4170
+ //#endregion
4171
+ //#region src/createDefaultAuthorizationCache.ts
4172
+ const CACHE_KEY = "SolanaMobileWalletAdapterDefaultAuthorizationCache";
4173
+ function createDefaultAuthorizationCache() {
4174
+ let storage;
4175
+ try {
4176
+ storage = window.localStorage;
4177
+ } catch {}
4178
+ return {
4179
+ async clear() {
4180
+ if (!storage) return;
4181
+ try {
4182
+ storage.removeItem(CACHE_KEY);
4183
+ } catch {}
4184
+ },
4185
+ async get() {
4186
+ if (!storage) return;
4187
+ try {
4188
+ const parsed = JSON.parse(storage.getItem(CACHE_KEY));
4189
+ if (parsed && parsed.accounts) {
4190
+ const parsedAccounts = parsed.accounts.map((account) => {
4191
+ return {
4192
+ ...account,
4193
+ publicKey: "publicKey" in account ? new Uint8Array(Object.values(account.publicKey)) : index_native.base58.decode(account.address)
4194
+ };
4195
+ });
4196
+ return {
4197
+ ...parsed,
4198
+ accounts: parsedAccounts
4199
+ };
4200
+ } else return parsed || void 0;
4201
+ } catch {}
4202
+ },
4203
+ async set(authorization) {
4204
+ if (!storage) return;
4205
+ try {
4206
+ storage.setItem(CACHE_KEY, JSON.stringify(authorization));
4207
+ } catch {}
4208
+ }
4209
+ };
4210
+ }
4211
+ //#endregion
4212
+ //#region src/createDefaultChainSelector.ts
4213
+ function createDefaultChainSelector() {
4214
+ return { async select(chains) {
4215
+ if (chains.length === 1) return chains[0];
4216
+ else if (chains.includes(SOLANA_MAINNET_CHAIN)) return SOLANA_MAINNET_CHAIN;
4217
+ else return chains[0];
4218
+ } };
4219
+ }
4220
+
4221
+ exports.LocalSolanaMobileWalletAdapterWallet = LocalSolanaMobileWalletAdapterWallet;
4222
+ exports.SolanaMobileWalletAdapterWalletName = SolanaMobileWalletAdapterWalletName;
4223
+ exports.createDefaultAuthorizationCache = createDefaultAuthorizationCache;
4224
+ exports.createDefaultChainSelector = createDefaultChainSelector;
4225
+ //# sourceMappingURL=index.browser-utVKQsEC.js.map