@bounded-sh/client 0.0.6 → 0.0.8

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