@bounded-sh/client 0.0.5 → 0.0.7

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