@ticketlayer/elements 0.2.0

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 (195) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -0
  3. package/dist/cjs/index-DfzcrE9-.js +3598 -0
  4. package/dist/cjs/index.cjs.js +16 -0
  5. package/dist/cjs/loader.cjs.js +12 -0
  6. package/dist/cjs/order-summary-ZMkJ5bez.js +116 -0
  7. package/dist/cjs/sdk-connector-ClDF3013.js +108 -0
  8. package/dist/cjs/ticketlayer-elements.cjs.js +24 -0
  9. package/dist/cjs/tl-buy-modal.cjs.entry.js +127 -0
  10. package/dist/cjs/tl-buy-tickets-button.cjs.entry.js +131 -0
  11. package/dist/cjs/tl-buy-tickets-wrapper.cjs.entry.js +58 -0
  12. package/dist/cjs/tl-cart-badge.cjs.entry.js +109 -0
  13. package/dist/cjs/tl-cart-drawer.cjs.entry.js +67 -0
  14. package/dist/cjs/tl-cart.cjs.entry.js +148 -0
  15. package/dist/cjs/tl-checkout-wrapper.cjs.entry.js +57 -0
  16. package/dist/cjs/tl-event-card.cjs.entry.js +140 -0
  17. package/dist/cjs/tl-event-list.cjs.entry.js +80 -0
  18. package/dist/cjs/tl-login.cjs.entry.js +184 -0
  19. package/dist/cjs/tl-my-orders.cjs.entry.js +123 -0
  20. package/dist/cjs/tl-occurrence-selector_2.cjs.entry.js +754 -0
  21. package/dist/cjs/tl-order-confirmation.cjs.entry.js +146 -0
  22. package/dist/cjs/tl-order-tickets_2.cjs.entry.js +3198 -0
  23. package/dist/cjs/tl-promo-code.cjs.entry.js +75 -0
  24. package/dist/cjs/tl-seat-map.cjs.entry.js +147 -0
  25. package/dist/collection/collection-manifest.json +29 -0
  26. package/dist/collection/components/tl-buy-modal/tl-buy-modal.css +264 -0
  27. package/dist/collection/components/tl-buy-modal/tl-buy-modal.js +249 -0
  28. package/dist/collection/components/tl-buy-tickets-button/tl-buy-tickets-button.css +120 -0
  29. package/dist/collection/components/tl-buy-tickets-button/tl-buy-tickets-button.js +412 -0
  30. package/dist/collection/components/tl-buy-tickets-wrapper/tl-buy-tickets-wrapper.css +23 -0
  31. package/dist/collection/components/tl-buy-tickets-wrapper/tl-buy-tickets-wrapper.js +192 -0
  32. package/dist/collection/components/tl-cart/tl-cart.css +251 -0
  33. package/dist/collection/components/tl-cart/tl-cart.js +314 -0
  34. package/dist/collection/components/tl-cart-badge/tl-cart-badge.css +138 -0
  35. package/dist/collection/components/tl-cart-badge/tl-cart-badge.js +217 -0
  36. package/dist/collection/components/tl-cart-drawer/tl-cart-drawer.css +98 -0
  37. package/dist/collection/components/tl-cart-drawer/tl-cart-drawer.js +185 -0
  38. package/dist/collection/components/tl-checkout-wrapper/tl-checkout-wrapper.css +23 -0
  39. package/dist/collection/components/tl-checkout-wrapper/tl-checkout-wrapper.js +148 -0
  40. package/dist/collection/components/tl-event-card/event-card-adapter.js +23 -0
  41. package/dist/collection/components/tl-event-card/tl-event-card.css +175 -0
  42. package/dist/collection/components/tl-event-card/tl-event-card.js +205 -0
  43. package/dist/collection/components/tl-event-list/tl-event-list.css +134 -0
  44. package/dist/collection/components/tl-event-list/tl-event-list.js +171 -0
  45. package/dist/collection/components/tl-login/tl-login.css +133 -0
  46. package/dist/collection/components/tl-login/tl-login.js +309 -0
  47. package/dist/collection/components/tl-my-orders/tl-my-orders.css +204 -0
  48. package/dist/collection/components/tl-my-orders/tl-my-orders.js +221 -0
  49. package/dist/collection/components/tl-occurrence-selector/tl-occurrence-selector.css +658 -0
  50. package/dist/collection/components/tl-occurrence-selector/tl-occurrence-selector.js +707 -0
  51. package/dist/collection/components/tl-order-confirmation/tl-order-confirmation.css +176 -0
  52. package/dist/collection/components/tl-order-confirmation/tl-order-confirmation.js +298 -0
  53. package/dist/collection/components/tl-order-tickets/tl-order-tickets.css +30 -0
  54. package/dist/collection/components/tl-order-tickets/tl-order-tickets.js +122 -0
  55. package/dist/collection/components/tl-promo-code/tl-promo-code.css +106 -0
  56. package/dist/collection/components/tl-promo-code/tl-promo-code.js +181 -0
  57. package/dist/collection/components/tl-seat-map/tl-seat-map.css +85 -0
  58. package/dist/collection/components/tl-seat-map/tl-seat-map.js +366 -0
  59. package/dist/collection/components/tl-ticket/tl-ticket.css +90 -0
  60. package/dist/collection/components/tl-ticket/tl-ticket.js +129 -0
  61. package/dist/collection/components/tl-ticket-selector/tl-ticket-selector.css +205 -0
  62. package/dist/collection/components/tl-ticket-selector/tl-ticket-selector.js +332 -0
  63. package/dist/collection/index.js +10 -0
  64. package/dist/collection/utils/order-summary.js +101 -0
  65. package/dist/collection/utils/sdk-connector.js +100 -0
  66. package/dist/collection/utils/testing/mock-sdk.js +95 -0
  67. package/dist/components/index.d.ts +35 -0
  68. package/dist/components/index.js +1 -0
  69. package/dist/components/order-summary.js +1 -0
  70. package/dist/components/sdk-connector.js +1 -0
  71. package/dist/components/tl-buy-modal.d.ts +11 -0
  72. package/dist/components/tl-buy-modal.js +1 -0
  73. package/dist/components/tl-buy-tickets-button.d.ts +11 -0
  74. package/dist/components/tl-buy-tickets-button.js +1 -0
  75. package/dist/components/tl-buy-tickets-wrapper.d.ts +11 -0
  76. package/dist/components/tl-buy-tickets-wrapper.js +1 -0
  77. package/dist/components/tl-buy-tickets-wrapper2.js +1 -0
  78. package/dist/components/tl-cart-badge.d.ts +11 -0
  79. package/dist/components/tl-cart-badge.js +1 -0
  80. package/dist/components/tl-cart-drawer.d.ts +11 -0
  81. package/dist/components/tl-cart-drawer.js +1 -0
  82. package/dist/components/tl-cart.d.ts +11 -0
  83. package/dist/components/tl-cart.js +1 -0
  84. package/dist/components/tl-cart2.js +1 -0
  85. package/dist/components/tl-checkout-wrapper.d.ts +11 -0
  86. package/dist/components/tl-checkout-wrapper.js +1 -0
  87. package/dist/components/tl-checkout-wrapper2.js +1 -0
  88. package/dist/components/tl-event-card.d.ts +11 -0
  89. package/dist/components/tl-event-card.js +1 -0
  90. package/dist/components/tl-event-card2.js +1 -0
  91. package/dist/components/tl-event-list.d.ts +11 -0
  92. package/dist/components/tl-event-list.js +1 -0
  93. package/dist/components/tl-login.d.ts +11 -0
  94. package/dist/components/tl-login.js +1 -0
  95. package/dist/components/tl-login2.js +1 -0
  96. package/dist/components/tl-my-orders.d.ts +11 -0
  97. package/dist/components/tl-my-orders.js +1 -0
  98. package/dist/components/tl-occurrence-selector.d.ts +11 -0
  99. package/dist/components/tl-occurrence-selector.js +1 -0
  100. package/dist/components/tl-occurrence-selector2.js +1 -0
  101. package/dist/components/tl-order-confirmation.d.ts +11 -0
  102. package/dist/components/tl-order-confirmation.js +1 -0
  103. package/dist/components/tl-order-tickets.d.ts +11 -0
  104. package/dist/components/tl-order-tickets.js +1 -0
  105. package/dist/components/tl-order-tickets2.js +1 -0
  106. package/dist/components/tl-promo-code.d.ts +11 -0
  107. package/dist/components/tl-promo-code.js +1 -0
  108. package/dist/components/tl-seat-map.d.ts +11 -0
  109. package/dist/components/tl-seat-map.js +1 -0
  110. package/dist/components/tl-ticket-selector.d.ts +11 -0
  111. package/dist/components/tl-ticket-selector.js +1 -0
  112. package/dist/components/tl-ticket-selector2.js +1 -0
  113. package/dist/components/tl-ticket.d.ts +11 -0
  114. package/dist/components/tl-ticket.js +1 -0
  115. package/dist/components/tl-ticket2.js +1 -0
  116. package/dist/elements.docs.d.ts +454 -0
  117. package/dist/elements.docs.json +3008 -0
  118. package/dist/esm/index-Ba-RZTFI.js +3588 -0
  119. package/dist/esm/index.js +4 -0
  120. package/dist/esm/loader.js +10 -0
  121. package/dist/esm/order-summary-BGekdjN9.js +103 -0
  122. package/dist/esm/sdk-connector-CqhvfyKV.js +102 -0
  123. package/dist/esm/ticketlayer-elements.js +20 -0
  124. package/dist/esm/tl-buy-modal.entry.js +125 -0
  125. package/dist/esm/tl-buy-tickets-button.entry.js +129 -0
  126. package/dist/esm/tl-buy-tickets-wrapper.entry.js +56 -0
  127. package/dist/esm/tl-cart-badge.entry.js +107 -0
  128. package/dist/esm/tl-cart-drawer.entry.js +65 -0
  129. package/dist/esm/tl-cart.entry.js +146 -0
  130. package/dist/esm/tl-checkout-wrapper.entry.js +55 -0
  131. package/dist/esm/tl-event-card.entry.js +138 -0
  132. package/dist/esm/tl-event-list.entry.js +78 -0
  133. package/dist/esm/tl-login.entry.js +182 -0
  134. package/dist/esm/tl-my-orders.entry.js +121 -0
  135. package/dist/esm/tl-occurrence-selector_2.entry.js +751 -0
  136. package/dist/esm/tl-order-confirmation.entry.js +144 -0
  137. package/dist/esm/tl-order-tickets_2.entry.js +3195 -0
  138. package/dist/esm/tl-promo-code.entry.js +73 -0
  139. package/dist/esm/tl-seat-map.entry.js +145 -0
  140. package/dist/index.cjs.js +1 -0
  141. package/dist/index.js +1 -0
  142. package/dist/ticketlayer-elements/index.esm.js +1 -0
  143. package/dist/ticketlayer-elements/p-0291df4c.entry.js +1 -0
  144. package/dist/ticketlayer-elements/p-10f01a1f.entry.js +1 -0
  145. package/dist/ticketlayer-elements/p-11273f8f.entry.js +1 -0
  146. package/dist/ticketlayer-elements/p-340ab4f5.entry.js +1 -0
  147. package/dist/ticketlayer-elements/p-41d22d7c.entry.js +1 -0
  148. package/dist/ticketlayer-elements/p-82752e3b.entry.js +1 -0
  149. package/dist/ticketlayer-elements/p-976770f3.entry.js +1 -0
  150. package/dist/ticketlayer-elements/p-9a903ff6.entry.js +1 -0
  151. package/dist/ticketlayer-elements/p-9c9072c8.entry.js +1 -0
  152. package/dist/ticketlayer-elements/p-9d8163d6.entry.js +1 -0
  153. package/dist/ticketlayer-elements/p-BGekdjN9.js +1 -0
  154. package/dist/ticketlayer-elements/p-Ba-RZTFI.js +2 -0
  155. package/dist/ticketlayer-elements/p-CqhvfyKV.js +1 -0
  156. package/dist/ticketlayer-elements/p-a5c90b68.entry.js +1 -0
  157. package/dist/ticketlayer-elements/p-b6d479ad.entry.js +1 -0
  158. package/dist/ticketlayer-elements/p-dd43f015.entry.js +1 -0
  159. package/dist/ticketlayer-elements/p-eb640760.entry.js +1 -0
  160. package/dist/ticketlayer-elements/p-ee3aa227.entry.js +1 -0
  161. package/dist/ticketlayer-elements/p-fb9444c4.entry.js +1 -0
  162. package/dist/ticketlayer-elements/ticketlayer-elements.css +1 -0
  163. package/dist/ticketlayer-elements/ticketlayer-elements.esm.js +1 -0
  164. package/dist/types/components/tl-buy-modal/tl-buy-modal.d.ts +54 -0
  165. package/dist/types/components/tl-buy-tickets-button/tl-buy-tickets-button.d.ts +61 -0
  166. package/dist/types/components/tl-buy-tickets-wrapper/tl-buy-tickets-wrapper.d.ts +52 -0
  167. package/dist/types/components/tl-cart/tl-cart.d.ts +80 -0
  168. package/dist/types/components/tl-cart-badge/tl-cart-badge.d.ts +36 -0
  169. package/dist/types/components/tl-cart-drawer/tl-cart-drawer.d.ts +35 -0
  170. package/dist/types/components/tl-checkout-wrapper/tl-checkout-wrapper.d.ts +39 -0
  171. package/dist/types/components/tl-event-card/event-card-adapter.d.ts +23 -0
  172. package/dist/types/components/tl-event-card/tl-event-card.d.ts +55 -0
  173. package/dist/types/components/tl-event-list/tl-event-list.d.ts +30 -0
  174. package/dist/types/components/tl-login/tl-login.d.ts +59 -0
  175. package/dist/types/components/tl-my-orders/tl-my-orders.d.ts +39 -0
  176. package/dist/types/components/tl-occurrence-selector/tl-occurrence-selector.d.ts +208 -0
  177. package/dist/types/components/tl-order-confirmation/tl-order-confirmation.d.ts +54 -0
  178. package/dist/types/components/tl-order-tickets/tl-order-tickets.d.ts +21 -0
  179. package/dist/types/components/tl-promo-code/tl-promo-code.d.ts +39 -0
  180. package/dist/types/components/tl-seat-map/tl-seat-map.d.ts +68 -0
  181. package/dist/types/components/tl-ticket/tl-ticket.d.ts +28 -0
  182. package/dist/types/components/tl-ticket-selector/tl-ticket-selector.d.ts +78 -0
  183. package/dist/types/components.d.ts +1629 -0
  184. package/dist/types/index.d.ts +14 -0
  185. package/dist/types/stencil-public-runtime.d.ts +1839 -0
  186. package/dist/types/utils/order-summary.d.ts +67 -0
  187. package/dist/types/utils/sdk-connector.d.ts +113 -0
  188. package/dist/types/utils/testing/mock-sdk.d.ts +36 -0
  189. package/elements.catalogue.json +968 -0
  190. package/loader/cdn.js +1 -0
  191. package/loader/index.cjs.js +1 -0
  192. package/loader/index.d.ts +24 -0
  193. package/loader/index.es2017.js +1 -0
  194. package/loader/index.js +2 -0
  195. package/package.json +101 -0
@@ -0,0 +1,3198 @@
1
+ 'use strict';
2
+
3
+ var index = require('./index-DfzcrE9-.js');
4
+ var sdkConnector = require('./sdk-connector-ClDF3013.js');
5
+
6
+ const tlOrderTicketsCss = () => `:host{display:block;font-family:var(--tl-font-family, system-ui, sans-serif)}.grid{display:grid;gap:var(--tl-spacing-4, 1rem);grid-template-columns:1fr}@media (min-width: 480px){.grid.cols-2{grid-template-columns:repeat(2, 1fr)}.grid.cols-3{grid-template-columns:repeat(3, 1fr)}}.state{padding:var(--tl-spacing-6, 1.5rem);text-align:center;color:var(--tl-muted-foreground, #6b7280);font-size:0.875rem}.state.error{color:var(--tl-error, #dc2626)}`;
7
+
8
+ const TlOrderTickets = class {
9
+ constructor(hostRef) {
10
+ index.registerInstance(this, hostRef);
11
+ /** Columns in the grid (default 2). */
12
+ this.columns = 2;
13
+ this.tickets = [];
14
+ this.loading = true;
15
+ this.error = null;
16
+ }
17
+ watchOrder() {
18
+ this.load();
19
+ }
20
+ async componentWillLoad() {
21
+ await this.load();
22
+ }
23
+ async load() {
24
+ try {
25
+ this.loading = true;
26
+ this.error = null;
27
+ const sdk = await sdkConnector.whenSDK();
28
+ const orders = sdk.getOrdersManager?.();
29
+ if (!orders)
30
+ throw new Error('Tickets are not available');
31
+ const order = (await orders.get(this.orderId));
32
+ this.tickets = order?.tickets ?? [];
33
+ }
34
+ catch (err) {
35
+ this.error = err instanceof Error ? err.message : 'Failed to load tickets';
36
+ }
37
+ finally {
38
+ this.loading = false;
39
+ }
40
+ }
41
+ render() {
42
+ if (this.loading) {
43
+ return index.h("div", { class: "state" }, "Loading tickets\u2026");
44
+ }
45
+ if (this.error) {
46
+ return index.h("div", { class: "state error" }, this.error);
47
+ }
48
+ if (this.tickets.length === 0) {
49
+ return index.h("div", { class: "state" }, "No tickets for this order yet.");
50
+ }
51
+ return (index.h("div", { class: `grid cols-${this.columns}` }, this.tickets.map((t) => (index.h("tl-ticket", { key: t.id, ticket: t, orderId: this.orderId })))));
52
+ }
53
+ static get watchers() { return {
54
+ "orderId": [{
55
+ "watchOrder": 0
56
+ }]
57
+ }; }
58
+ };
59
+ TlOrderTickets.style = tlOrderTicketsCss();
60
+
61
+ function getDefaultExportFromCjs (x) {
62
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
63
+ }
64
+
65
+ var browser = {};
66
+
67
+ var canPromise;
68
+ var hasRequiredCanPromise;
69
+
70
+ function requireCanPromise () {
71
+ if (hasRequiredCanPromise) return canPromise;
72
+ hasRequiredCanPromise = 1;
73
+ // can-promise has a crash in some versions of react native that dont have
74
+ // standard global objects
75
+ // https://github.com/soldair/node-qrcode/issues/157
76
+
77
+ canPromise = function () {
78
+ return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
79
+ };
80
+ return canPromise;
81
+ }
82
+
83
+ var qrcode = {};
84
+
85
+ var utils$1 = {};
86
+
87
+ var hasRequiredUtils$1;
88
+
89
+ function requireUtils$1 () {
90
+ if (hasRequiredUtils$1) return utils$1;
91
+ hasRequiredUtils$1 = 1;
92
+ let toSJISFunction;
93
+ const CODEWORDS_COUNT = [
94
+ 0, // Not used
95
+ 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
96
+ 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
97
+ 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
98
+ 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
99
+ ];
100
+
101
+ /**
102
+ * Returns the QR Code size for the specified version
103
+ *
104
+ * @param {Number} version QR Code version
105
+ * @return {Number} size of QR code
106
+ */
107
+ utils$1.getSymbolSize = function getSymbolSize (version) {
108
+ if (!version) throw new Error('"version" cannot be null or undefined')
109
+ if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
110
+ return version * 4 + 17
111
+ };
112
+
113
+ /**
114
+ * Returns the total number of codewords used to store data and EC information.
115
+ *
116
+ * @param {Number} version QR Code version
117
+ * @return {Number} Data length in bits
118
+ */
119
+ utils$1.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
120
+ return CODEWORDS_COUNT[version]
121
+ };
122
+
123
+ /**
124
+ * Encode data with Bose-Chaudhuri-Hocquenghem
125
+ *
126
+ * @param {Number} data Value to encode
127
+ * @return {Number} Encoded value
128
+ */
129
+ utils$1.getBCHDigit = function (data) {
130
+ let digit = 0;
131
+
132
+ while (data !== 0) {
133
+ digit++;
134
+ data >>>= 1;
135
+ }
136
+
137
+ return digit
138
+ };
139
+
140
+ utils$1.setToSJISFunction = function setToSJISFunction (f) {
141
+ if (typeof f !== 'function') {
142
+ throw new Error('"toSJISFunc" is not a valid function.')
143
+ }
144
+
145
+ toSJISFunction = f;
146
+ };
147
+
148
+ utils$1.isKanjiModeEnabled = function () {
149
+ return typeof toSJISFunction !== 'undefined'
150
+ };
151
+
152
+ utils$1.toSJIS = function toSJIS (kanji) {
153
+ return toSJISFunction(kanji)
154
+ };
155
+ return utils$1;
156
+ }
157
+
158
+ var errorCorrectionLevel = {};
159
+
160
+ var hasRequiredErrorCorrectionLevel;
161
+
162
+ function requireErrorCorrectionLevel () {
163
+ if (hasRequiredErrorCorrectionLevel) return errorCorrectionLevel;
164
+ hasRequiredErrorCorrectionLevel = 1;
165
+ (function (exports) {
166
+ exports.L = { bit: 1 };
167
+ exports.M = { bit: 0 };
168
+ exports.Q = { bit: 3 };
169
+ exports.H = { bit: 2 };
170
+
171
+ function fromString (string) {
172
+ if (typeof string !== 'string') {
173
+ throw new Error('Param is not a string')
174
+ }
175
+
176
+ const lcStr = string.toLowerCase();
177
+
178
+ switch (lcStr) {
179
+ case 'l':
180
+ case 'low':
181
+ return exports.L
182
+
183
+ case 'm':
184
+ case 'medium':
185
+ return exports.M
186
+
187
+ case 'q':
188
+ case 'quartile':
189
+ return exports.Q
190
+
191
+ case 'h':
192
+ case 'high':
193
+ return exports.H
194
+
195
+ default:
196
+ throw new Error('Unknown EC Level: ' + string)
197
+ }
198
+ }
199
+
200
+ exports.isValid = function isValid (level) {
201
+ return level && typeof level.bit !== 'undefined' &&
202
+ level.bit >= 0 && level.bit < 4
203
+ };
204
+
205
+ exports.from = function from (value, defaultValue) {
206
+ if (exports.isValid(value)) {
207
+ return value
208
+ }
209
+
210
+ try {
211
+ return fromString(value)
212
+ } catch (e) {
213
+ return defaultValue
214
+ }
215
+ };
216
+ } (errorCorrectionLevel));
217
+ return errorCorrectionLevel;
218
+ }
219
+
220
+ var bitBuffer;
221
+ var hasRequiredBitBuffer;
222
+
223
+ function requireBitBuffer () {
224
+ if (hasRequiredBitBuffer) return bitBuffer;
225
+ hasRequiredBitBuffer = 1;
226
+ function BitBuffer () {
227
+ this.buffer = [];
228
+ this.length = 0;
229
+ }
230
+
231
+ BitBuffer.prototype = {
232
+
233
+ get: function (index) {
234
+ const bufIndex = Math.floor(index / 8);
235
+ return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
236
+ },
237
+
238
+ put: function (num, length) {
239
+ for (let i = 0; i < length; i++) {
240
+ this.putBit(((num >>> (length - i - 1)) & 1) === 1);
241
+ }
242
+ },
243
+
244
+ getLengthInBits: function () {
245
+ return this.length
246
+ },
247
+
248
+ putBit: function (bit) {
249
+ const bufIndex = Math.floor(this.length / 8);
250
+ if (this.buffer.length <= bufIndex) {
251
+ this.buffer.push(0);
252
+ }
253
+
254
+ if (bit) {
255
+ this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
256
+ }
257
+
258
+ this.length++;
259
+ }
260
+ };
261
+
262
+ bitBuffer = BitBuffer;
263
+ return bitBuffer;
264
+ }
265
+
266
+ /**
267
+ * Helper class to handle QR Code symbol modules
268
+ *
269
+ * @param {Number} size Symbol size
270
+ */
271
+
272
+ var bitMatrix;
273
+ var hasRequiredBitMatrix;
274
+
275
+ function requireBitMatrix () {
276
+ if (hasRequiredBitMatrix) return bitMatrix;
277
+ hasRequiredBitMatrix = 1;
278
+ function BitMatrix (size) {
279
+ if (!size || size < 1) {
280
+ throw new Error('BitMatrix size must be defined and greater than 0')
281
+ }
282
+
283
+ this.size = size;
284
+ this.data = new Uint8Array(size * size);
285
+ this.reservedBit = new Uint8Array(size * size);
286
+ }
287
+
288
+ /**
289
+ * Set bit value at specified location
290
+ * If reserved flag is set, this bit will be ignored during masking process
291
+ *
292
+ * @param {Number} row
293
+ * @param {Number} col
294
+ * @param {Boolean} value
295
+ * @param {Boolean} reserved
296
+ */
297
+ BitMatrix.prototype.set = function (row, col, value, reserved) {
298
+ const index = row * this.size + col;
299
+ this.data[index] = value;
300
+ if (reserved) this.reservedBit[index] = true;
301
+ };
302
+
303
+ /**
304
+ * Returns bit value at specified location
305
+ *
306
+ * @param {Number} row
307
+ * @param {Number} col
308
+ * @return {Boolean}
309
+ */
310
+ BitMatrix.prototype.get = function (row, col) {
311
+ return this.data[row * this.size + col]
312
+ };
313
+
314
+ /**
315
+ * Applies xor operator at specified location
316
+ * (used during masking process)
317
+ *
318
+ * @param {Number} row
319
+ * @param {Number} col
320
+ * @param {Boolean} value
321
+ */
322
+ BitMatrix.prototype.xor = function (row, col, value) {
323
+ this.data[row * this.size + col] ^= value;
324
+ };
325
+
326
+ /**
327
+ * Check if bit at specified location is reserved
328
+ *
329
+ * @param {Number} row
330
+ * @param {Number} col
331
+ * @return {Boolean}
332
+ */
333
+ BitMatrix.prototype.isReserved = function (row, col) {
334
+ return this.reservedBit[row * this.size + col]
335
+ };
336
+
337
+ bitMatrix = BitMatrix;
338
+ return bitMatrix;
339
+ }
340
+
341
+ var alignmentPattern = {};
342
+
343
+ /**
344
+ * Alignment pattern are fixed reference pattern in defined positions
345
+ * in a matrix symbology, which enables the decode software to re-synchronise
346
+ * the coordinate mapping of the image modules in the event of moderate amounts
347
+ * of distortion of the image.
348
+ *
349
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
350
+ * and their number depends on the symbol version.
351
+ */
352
+
353
+ var hasRequiredAlignmentPattern;
354
+
355
+ function requireAlignmentPattern () {
356
+ if (hasRequiredAlignmentPattern) return alignmentPattern;
357
+ hasRequiredAlignmentPattern = 1;
358
+ (function (exports) {
359
+ const getSymbolSize = requireUtils$1().getSymbolSize;
360
+
361
+ /**
362
+ * Calculate the row/column coordinates of the center module of each alignment pattern
363
+ * for the specified QR Code version.
364
+ *
365
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
366
+ * running from the top left corner of the symbol to the bottom right corner.
367
+ *
368
+ * Since positions are simmetrical only half of the coordinates are returned.
369
+ * Each item of the array will represent in turn the x and y coordinate.
370
+ * @see {@link getPositions}
371
+ *
372
+ * @param {Number} version QR Code version
373
+ * @return {Array} Array of coordinate
374
+ */
375
+ exports.getRowColCoords = function getRowColCoords (version) {
376
+ if (version === 1) return []
377
+
378
+ const posCount = Math.floor(version / 7) + 2;
379
+ const size = getSymbolSize(version);
380
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
381
+ const positions = [size - 7]; // Last coord is always (size - 7)
382
+
383
+ for (let i = 1; i < posCount - 1; i++) {
384
+ positions[i] = positions[i - 1] - intervals;
385
+ }
386
+
387
+ positions.push(6); // First coord is always 6
388
+
389
+ return positions.reverse()
390
+ };
391
+
392
+ /**
393
+ * Returns an array containing the positions of each alignment pattern.
394
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
395
+ *
396
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
397
+ * and filtering out the items that overlaps with finder pattern
398
+ *
399
+ * @example
400
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
401
+ * The alignment patterns, therefore, are to be centered on (row, column)
402
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
403
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
404
+ * and are not therefore used for alignment patterns.
405
+ *
406
+ * let pos = getPositions(7)
407
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
408
+ *
409
+ * @param {Number} version QR Code version
410
+ * @return {Array} Array of coordinates
411
+ */
412
+ exports.getPositions = function getPositions (version) {
413
+ const coords = [];
414
+ const pos = exports.getRowColCoords(version);
415
+ const posLength = pos.length;
416
+
417
+ for (let i = 0; i < posLength; i++) {
418
+ for (let j = 0; j < posLength; j++) {
419
+ // Skip if position is occupied by finder patterns
420
+ if ((i === 0 && j === 0) || // top-left
421
+ (i === 0 && j === posLength - 1) || // bottom-left
422
+ (i === posLength - 1 && j === 0)) { // top-right
423
+ continue
424
+ }
425
+
426
+ coords.push([pos[i], pos[j]]);
427
+ }
428
+ }
429
+
430
+ return coords
431
+ };
432
+ } (alignmentPattern));
433
+ return alignmentPattern;
434
+ }
435
+
436
+ var finderPattern = {};
437
+
438
+ var hasRequiredFinderPattern;
439
+
440
+ function requireFinderPattern () {
441
+ if (hasRequiredFinderPattern) return finderPattern;
442
+ hasRequiredFinderPattern = 1;
443
+ const getSymbolSize = requireUtils$1().getSymbolSize;
444
+ const FINDER_PATTERN_SIZE = 7;
445
+
446
+ /**
447
+ * Returns an array containing the positions of each finder pattern.
448
+ * Each array's element represent the top-left point of the pattern as (x, y) coordinates
449
+ *
450
+ * @param {Number} version QR Code version
451
+ * @return {Array} Array of coordinates
452
+ */
453
+ finderPattern.getPositions = function getPositions (version) {
454
+ const size = getSymbolSize(version);
455
+
456
+ return [
457
+ // top-left
458
+ [0, 0],
459
+ // top-right
460
+ [size - FINDER_PATTERN_SIZE, 0],
461
+ // bottom-left
462
+ [0, size - FINDER_PATTERN_SIZE]
463
+ ]
464
+ };
465
+ return finderPattern;
466
+ }
467
+
468
+ var maskPattern = {};
469
+
470
+ /**
471
+ * Data mask pattern reference
472
+ * @type {Object}
473
+ */
474
+
475
+ var hasRequiredMaskPattern;
476
+
477
+ function requireMaskPattern () {
478
+ if (hasRequiredMaskPattern) return maskPattern;
479
+ hasRequiredMaskPattern = 1;
480
+ (function (exports) {
481
+ exports.Patterns = {
482
+ PATTERN000: 0,
483
+ PATTERN001: 1,
484
+ PATTERN010: 2,
485
+ PATTERN011: 3,
486
+ PATTERN100: 4,
487
+ PATTERN101: 5,
488
+ PATTERN110: 6,
489
+ PATTERN111: 7
490
+ };
491
+
492
+ /**
493
+ * Weighted penalty scores for the undesirable features
494
+ * @type {Object}
495
+ */
496
+ const PenaltyScores = {
497
+ N1: 3,
498
+ N2: 3,
499
+ N3: 40,
500
+ N4: 10
501
+ };
502
+
503
+ /**
504
+ * Check if mask pattern value is valid
505
+ *
506
+ * @param {Number} mask Mask pattern
507
+ * @return {Boolean} true if valid, false otherwise
508
+ */
509
+ exports.isValid = function isValid (mask) {
510
+ return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
511
+ };
512
+
513
+ /**
514
+ * Returns mask pattern from a value.
515
+ * If value is not valid, returns undefined
516
+ *
517
+ * @param {Number|String} value Mask pattern value
518
+ * @return {Number} Valid mask pattern or undefined
519
+ */
520
+ exports.from = function from (value) {
521
+ return exports.isValid(value) ? parseInt(value, 10) : undefined
522
+ };
523
+
524
+ /**
525
+ * Find adjacent modules in row/column with the same color
526
+ * and assign a penalty value.
527
+ *
528
+ * Points: N1 + i
529
+ * i is the amount by which the number of adjacent modules of the same color exceeds 5
530
+ */
531
+ exports.getPenaltyN1 = function getPenaltyN1 (data) {
532
+ const size = data.size;
533
+ let points = 0;
534
+ let sameCountCol = 0;
535
+ let sameCountRow = 0;
536
+ let lastCol = null;
537
+ let lastRow = null;
538
+
539
+ for (let row = 0; row < size; row++) {
540
+ sameCountCol = sameCountRow = 0;
541
+ lastCol = lastRow = null;
542
+
543
+ for (let col = 0; col < size; col++) {
544
+ let module = data.get(row, col);
545
+ if (module === lastCol) {
546
+ sameCountCol++;
547
+ } else {
548
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
549
+ lastCol = module;
550
+ sameCountCol = 1;
551
+ }
552
+
553
+ module = data.get(col, row);
554
+ if (module === lastRow) {
555
+ sameCountRow++;
556
+ } else {
557
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
558
+ lastRow = module;
559
+ sameCountRow = 1;
560
+ }
561
+ }
562
+
563
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
564
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
565
+ }
566
+
567
+ return points
568
+ };
569
+
570
+ /**
571
+ * Find 2x2 blocks with the same color and assign a penalty value
572
+ *
573
+ * Points: N2 * (m - 1) * (n - 1)
574
+ */
575
+ exports.getPenaltyN2 = function getPenaltyN2 (data) {
576
+ const size = data.size;
577
+ let points = 0;
578
+
579
+ for (let row = 0; row < size - 1; row++) {
580
+ for (let col = 0; col < size - 1; col++) {
581
+ const last = data.get(row, col) +
582
+ data.get(row, col + 1) +
583
+ data.get(row + 1, col) +
584
+ data.get(row + 1, col + 1);
585
+
586
+ if (last === 4 || last === 0) points++;
587
+ }
588
+ }
589
+
590
+ return points * PenaltyScores.N2
591
+ };
592
+
593
+ /**
594
+ * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
595
+ * preceded or followed by light area 4 modules wide
596
+ *
597
+ * Points: N3 * number of pattern found
598
+ */
599
+ exports.getPenaltyN3 = function getPenaltyN3 (data) {
600
+ const size = data.size;
601
+ let points = 0;
602
+ let bitsCol = 0;
603
+ let bitsRow = 0;
604
+
605
+ for (let row = 0; row < size; row++) {
606
+ bitsCol = bitsRow = 0;
607
+ for (let col = 0; col < size; col++) {
608
+ bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col);
609
+ if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++;
610
+
611
+ bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row);
612
+ if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++;
613
+ }
614
+ }
615
+
616
+ return points * PenaltyScores.N3
617
+ };
618
+
619
+ /**
620
+ * Calculate proportion of dark modules in entire symbol
621
+ *
622
+ * Points: N4 * k
623
+ *
624
+ * k is the rating of the deviation of the proportion of dark modules
625
+ * in the symbol from 50% in steps of 5%
626
+ */
627
+ exports.getPenaltyN4 = function getPenaltyN4 (data) {
628
+ let darkCount = 0;
629
+ const modulesCount = data.data.length;
630
+
631
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
632
+
633
+ const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10);
634
+
635
+ return k * PenaltyScores.N4
636
+ };
637
+
638
+ /**
639
+ * Return mask value at given position
640
+ *
641
+ * @param {Number} maskPattern Pattern reference value
642
+ * @param {Number} i Row
643
+ * @param {Number} j Column
644
+ * @return {Boolean} Mask value
645
+ */
646
+ function getMaskAt (maskPattern, i, j) {
647
+ switch (maskPattern) {
648
+ case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
649
+ case exports.Patterns.PATTERN001: return i % 2 === 0
650
+ case exports.Patterns.PATTERN010: return j % 3 === 0
651
+ case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
652
+ case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
653
+ case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
654
+ case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
655
+ case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
656
+
657
+ default: throw new Error('bad maskPattern:' + maskPattern)
658
+ }
659
+ }
660
+
661
+ /**
662
+ * Apply a mask pattern to a BitMatrix
663
+ *
664
+ * @param {Number} pattern Pattern reference number
665
+ * @param {BitMatrix} data BitMatrix data
666
+ */
667
+ exports.applyMask = function applyMask (pattern, data) {
668
+ const size = data.size;
669
+
670
+ for (let col = 0; col < size; col++) {
671
+ for (let row = 0; row < size; row++) {
672
+ if (data.isReserved(row, col)) continue
673
+ data.xor(row, col, getMaskAt(pattern, row, col));
674
+ }
675
+ }
676
+ };
677
+
678
+ /**
679
+ * Returns the best mask pattern for data
680
+ *
681
+ * @param {BitMatrix} data
682
+ * @return {Number} Mask pattern reference number
683
+ */
684
+ exports.getBestMask = function getBestMask (data, setupFormatFunc) {
685
+ const numPatterns = Object.keys(exports.Patterns).length;
686
+ let bestPattern = 0;
687
+ let lowerPenalty = Infinity;
688
+
689
+ for (let p = 0; p < numPatterns; p++) {
690
+ setupFormatFunc(p);
691
+ exports.applyMask(p, data);
692
+
693
+ // Calculate penalty
694
+ const penalty =
695
+ exports.getPenaltyN1(data) +
696
+ exports.getPenaltyN2(data) +
697
+ exports.getPenaltyN3(data) +
698
+ exports.getPenaltyN4(data);
699
+
700
+ // Undo previously applied mask
701
+ exports.applyMask(p, data);
702
+
703
+ if (penalty < lowerPenalty) {
704
+ lowerPenalty = penalty;
705
+ bestPattern = p;
706
+ }
707
+ }
708
+
709
+ return bestPattern
710
+ };
711
+ } (maskPattern));
712
+ return maskPattern;
713
+ }
714
+
715
+ var errorCorrectionCode = {};
716
+
717
+ var hasRequiredErrorCorrectionCode;
718
+
719
+ function requireErrorCorrectionCode () {
720
+ if (hasRequiredErrorCorrectionCode) return errorCorrectionCode;
721
+ hasRequiredErrorCorrectionCode = 1;
722
+ const ECLevel = requireErrorCorrectionLevel();
723
+
724
+ const EC_BLOCKS_TABLE = [
725
+ // L M Q H
726
+ 1, 1, 1, 1,
727
+ 1, 1, 1, 1,
728
+ 1, 1, 2, 2,
729
+ 1, 2, 2, 4,
730
+ 1, 2, 4, 4,
731
+ 2, 4, 4, 4,
732
+ 2, 4, 6, 5,
733
+ 2, 4, 6, 6,
734
+ 2, 5, 8, 8,
735
+ 4, 5, 8, 8,
736
+ 4, 5, 8, 11,
737
+ 4, 8, 10, 11,
738
+ 4, 9, 12, 16,
739
+ 4, 9, 16, 16,
740
+ 6, 10, 12, 18,
741
+ 6, 10, 17, 16,
742
+ 6, 11, 16, 19,
743
+ 6, 13, 18, 21,
744
+ 7, 14, 21, 25,
745
+ 8, 16, 20, 25,
746
+ 8, 17, 23, 25,
747
+ 9, 17, 23, 34,
748
+ 9, 18, 25, 30,
749
+ 10, 20, 27, 32,
750
+ 12, 21, 29, 35,
751
+ 12, 23, 34, 37,
752
+ 12, 25, 34, 40,
753
+ 13, 26, 35, 42,
754
+ 14, 28, 38, 45,
755
+ 15, 29, 40, 48,
756
+ 16, 31, 43, 51,
757
+ 17, 33, 45, 54,
758
+ 18, 35, 48, 57,
759
+ 19, 37, 51, 60,
760
+ 19, 38, 53, 63,
761
+ 20, 40, 56, 66,
762
+ 21, 43, 59, 70,
763
+ 22, 45, 62, 74,
764
+ 24, 47, 65, 77,
765
+ 25, 49, 68, 81
766
+ ];
767
+
768
+ const EC_CODEWORDS_TABLE = [
769
+ // L M Q H
770
+ 7, 10, 13, 17,
771
+ 10, 16, 22, 28,
772
+ 15, 26, 36, 44,
773
+ 20, 36, 52, 64,
774
+ 26, 48, 72, 88,
775
+ 36, 64, 96, 112,
776
+ 40, 72, 108, 130,
777
+ 48, 88, 132, 156,
778
+ 60, 110, 160, 192,
779
+ 72, 130, 192, 224,
780
+ 80, 150, 224, 264,
781
+ 96, 176, 260, 308,
782
+ 104, 198, 288, 352,
783
+ 120, 216, 320, 384,
784
+ 132, 240, 360, 432,
785
+ 144, 280, 408, 480,
786
+ 168, 308, 448, 532,
787
+ 180, 338, 504, 588,
788
+ 196, 364, 546, 650,
789
+ 224, 416, 600, 700,
790
+ 224, 442, 644, 750,
791
+ 252, 476, 690, 816,
792
+ 270, 504, 750, 900,
793
+ 300, 560, 810, 960,
794
+ 312, 588, 870, 1050,
795
+ 336, 644, 952, 1110,
796
+ 360, 700, 1020, 1200,
797
+ 390, 728, 1050, 1260,
798
+ 420, 784, 1140, 1350,
799
+ 450, 812, 1200, 1440,
800
+ 480, 868, 1290, 1530,
801
+ 510, 924, 1350, 1620,
802
+ 540, 980, 1440, 1710,
803
+ 570, 1036, 1530, 1800,
804
+ 570, 1064, 1590, 1890,
805
+ 600, 1120, 1680, 1980,
806
+ 630, 1204, 1770, 2100,
807
+ 660, 1260, 1860, 2220,
808
+ 720, 1316, 1950, 2310,
809
+ 750, 1372, 2040, 2430
810
+ ];
811
+
812
+ /**
813
+ * Returns the number of error correction block that the QR Code should contain
814
+ * for the specified version and error correction level.
815
+ *
816
+ * @param {Number} version QR Code version
817
+ * @param {Number} errorCorrectionLevel Error correction level
818
+ * @return {Number} Number of error correction blocks
819
+ */
820
+ errorCorrectionCode.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
821
+ switch (errorCorrectionLevel) {
822
+ case ECLevel.L:
823
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
824
+ case ECLevel.M:
825
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
826
+ case ECLevel.Q:
827
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
828
+ case ECLevel.H:
829
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
830
+ default:
831
+ return undefined
832
+ }
833
+ };
834
+
835
+ /**
836
+ * Returns the number of error correction codewords to use for the specified
837
+ * version and error correction level.
838
+ *
839
+ * @param {Number} version QR Code version
840
+ * @param {Number} errorCorrectionLevel Error correction level
841
+ * @return {Number} Number of error correction codewords
842
+ */
843
+ errorCorrectionCode.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
844
+ switch (errorCorrectionLevel) {
845
+ case ECLevel.L:
846
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
847
+ case ECLevel.M:
848
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
849
+ case ECLevel.Q:
850
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
851
+ case ECLevel.H:
852
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
853
+ default:
854
+ return undefined
855
+ }
856
+ };
857
+ return errorCorrectionCode;
858
+ }
859
+
860
+ var polynomial = {};
861
+
862
+ var galoisField = {};
863
+
864
+ var hasRequiredGaloisField;
865
+
866
+ function requireGaloisField () {
867
+ if (hasRequiredGaloisField) return galoisField;
868
+ hasRequiredGaloisField = 1;
869
+ const EXP_TABLE = new Uint8Array(512);
870
+ const LOG_TABLE = new Uint8Array(256)
871
+ /**
872
+ * Precompute the log and anti-log tables for faster computation later
873
+ *
874
+ * For each possible value in the galois field 2^8, we will pre-compute
875
+ * the logarithm and anti-logarithm (exponential) of this value
876
+ *
877
+ * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
878
+ */
879
+ ;(function initTables () {
880
+ let x = 1;
881
+ for (let i = 0; i < 255; i++) {
882
+ EXP_TABLE[i] = x;
883
+ LOG_TABLE[x] = i;
884
+
885
+ x <<= 1; // multiply by 2
886
+
887
+ // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
888
+ // This means that when a number is 256 or larger, it should be XORed with 0x11D.
889
+ if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
890
+ x ^= 0x11D;
891
+ }
892
+ }
893
+
894
+ // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
895
+ // stay inside the bounds (because we will mainly use this table for the multiplication of
896
+ // two GF numbers, no more).
897
+ // @see {@link mul}
898
+ for (let i = 255; i < 512; i++) {
899
+ EXP_TABLE[i] = EXP_TABLE[i - 255];
900
+ }
901
+ }());
902
+
903
+ /**
904
+ * Returns log value of n inside Galois Field
905
+ *
906
+ * @param {Number} n
907
+ * @return {Number}
908
+ */
909
+ galoisField.log = function log (n) {
910
+ if (n < 1) throw new Error('log(' + n + ')')
911
+ return LOG_TABLE[n]
912
+ };
913
+
914
+ /**
915
+ * Returns anti-log value of n inside Galois Field
916
+ *
917
+ * @param {Number} n
918
+ * @return {Number}
919
+ */
920
+ galoisField.exp = function exp (n) {
921
+ return EXP_TABLE[n]
922
+ };
923
+
924
+ /**
925
+ * Multiplies two number inside Galois Field
926
+ *
927
+ * @param {Number} x
928
+ * @param {Number} y
929
+ * @return {Number}
930
+ */
931
+ galoisField.mul = function mul (x, y) {
932
+ if (x === 0 || y === 0) return 0
933
+
934
+ // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
935
+ // @see {@link initTables}
936
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
937
+ };
938
+ return galoisField;
939
+ }
940
+
941
+ var hasRequiredPolynomial;
942
+
943
+ function requirePolynomial () {
944
+ if (hasRequiredPolynomial) return polynomial;
945
+ hasRequiredPolynomial = 1;
946
+ (function (exports) {
947
+ const GF = requireGaloisField();
948
+
949
+ /**
950
+ * Multiplies two polynomials inside Galois Field
951
+ *
952
+ * @param {Uint8Array} p1 Polynomial
953
+ * @param {Uint8Array} p2 Polynomial
954
+ * @return {Uint8Array} Product of p1 and p2
955
+ */
956
+ exports.mul = function mul (p1, p2) {
957
+ const coeff = new Uint8Array(p1.length + p2.length - 1);
958
+
959
+ for (let i = 0; i < p1.length; i++) {
960
+ for (let j = 0; j < p2.length; j++) {
961
+ coeff[i + j] ^= GF.mul(p1[i], p2[j]);
962
+ }
963
+ }
964
+
965
+ return coeff
966
+ };
967
+
968
+ /**
969
+ * Calculate the remainder of polynomials division
970
+ *
971
+ * @param {Uint8Array} divident Polynomial
972
+ * @param {Uint8Array} divisor Polynomial
973
+ * @return {Uint8Array} Remainder
974
+ */
975
+ exports.mod = function mod (divident, divisor) {
976
+ let result = new Uint8Array(divident);
977
+
978
+ while ((result.length - divisor.length) >= 0) {
979
+ const coeff = result[0];
980
+
981
+ for (let i = 0; i < divisor.length; i++) {
982
+ result[i] ^= GF.mul(divisor[i], coeff);
983
+ }
984
+
985
+ // remove all zeros from buffer head
986
+ let offset = 0;
987
+ while (offset < result.length && result[offset] === 0) offset++;
988
+ result = result.slice(offset);
989
+ }
990
+
991
+ return result
992
+ };
993
+
994
+ /**
995
+ * Generate an irreducible generator polynomial of specified degree
996
+ * (used by Reed-Solomon encoder)
997
+ *
998
+ * @param {Number} degree Degree of the generator polynomial
999
+ * @return {Uint8Array} Buffer containing polynomial coefficients
1000
+ */
1001
+ exports.generateECPolynomial = function generateECPolynomial (degree) {
1002
+ let poly = new Uint8Array([1]);
1003
+ for (let i = 0; i < degree; i++) {
1004
+ poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]));
1005
+ }
1006
+
1007
+ return poly
1008
+ };
1009
+ } (polynomial));
1010
+ return polynomial;
1011
+ }
1012
+
1013
+ var reedSolomonEncoder;
1014
+ var hasRequiredReedSolomonEncoder;
1015
+
1016
+ function requireReedSolomonEncoder () {
1017
+ if (hasRequiredReedSolomonEncoder) return reedSolomonEncoder;
1018
+ hasRequiredReedSolomonEncoder = 1;
1019
+ const Polynomial = requirePolynomial();
1020
+
1021
+ function ReedSolomonEncoder (degree) {
1022
+ this.genPoly = undefined;
1023
+ this.degree = degree;
1024
+
1025
+ if (this.degree) this.initialize(this.degree);
1026
+ }
1027
+
1028
+ /**
1029
+ * Initialize the encoder.
1030
+ * The input param should correspond to the number of error correction codewords.
1031
+ *
1032
+ * @param {Number} degree
1033
+ */
1034
+ ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
1035
+ // create an irreducible generator polynomial
1036
+ this.degree = degree;
1037
+ this.genPoly = Polynomial.generateECPolynomial(this.degree);
1038
+ };
1039
+
1040
+ /**
1041
+ * Encodes a chunk of data
1042
+ *
1043
+ * @param {Uint8Array} data Buffer containing input data
1044
+ * @return {Uint8Array} Buffer containing encoded data
1045
+ */
1046
+ ReedSolomonEncoder.prototype.encode = function encode (data) {
1047
+ if (!this.genPoly) {
1048
+ throw new Error('Encoder not initialized')
1049
+ }
1050
+
1051
+ // Calculate EC for this data block
1052
+ // extends data size to data+genPoly size
1053
+ const paddedData = new Uint8Array(data.length + this.degree);
1054
+ paddedData.set(data);
1055
+
1056
+ // The error correction codewords are the remainder after dividing the data codewords
1057
+ // by a generator polynomial
1058
+ const remainder = Polynomial.mod(paddedData, this.genPoly);
1059
+
1060
+ // return EC data blocks (last n byte, where n is the degree of genPoly)
1061
+ // If coefficients number in remainder are less than genPoly degree,
1062
+ // pad with 0s to the left to reach the needed number of coefficients
1063
+ const start = this.degree - remainder.length;
1064
+ if (start > 0) {
1065
+ const buff = new Uint8Array(this.degree);
1066
+ buff.set(remainder, start);
1067
+
1068
+ return buff
1069
+ }
1070
+
1071
+ return remainder
1072
+ };
1073
+
1074
+ reedSolomonEncoder = ReedSolomonEncoder;
1075
+ return reedSolomonEncoder;
1076
+ }
1077
+
1078
+ var version = {};
1079
+
1080
+ var mode = {};
1081
+
1082
+ var versionCheck = {};
1083
+
1084
+ /**
1085
+ * Check if QR Code version is valid
1086
+ *
1087
+ * @param {Number} version QR Code version
1088
+ * @return {Boolean} true if valid version, false otherwise
1089
+ */
1090
+
1091
+ var hasRequiredVersionCheck;
1092
+
1093
+ function requireVersionCheck () {
1094
+ if (hasRequiredVersionCheck) return versionCheck;
1095
+ hasRequiredVersionCheck = 1;
1096
+ versionCheck.isValid = function isValid (version) {
1097
+ return !isNaN(version) && version >= 1 && version <= 40
1098
+ };
1099
+ return versionCheck;
1100
+ }
1101
+
1102
+ var regex = {};
1103
+
1104
+ var hasRequiredRegex;
1105
+
1106
+ function requireRegex () {
1107
+ if (hasRequiredRegex) return regex;
1108
+ hasRequiredRegex = 1;
1109
+ const numeric = '[0-9]+';
1110
+ const alphanumeric = '[A-Z $%*+\\-./:]+';
1111
+ let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
1112
+ '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
1113
+ '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
1114
+ '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+';
1115
+ kanji = kanji.replace(/u/g, '\\u');
1116
+
1117
+ const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+';
1118
+
1119
+ regex.KANJI = new RegExp(kanji, 'g');
1120
+ regex.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g');
1121
+ regex.BYTE = new RegExp(byte, 'g');
1122
+ regex.NUMERIC = new RegExp(numeric, 'g');
1123
+ regex.ALPHANUMERIC = new RegExp(alphanumeric, 'g');
1124
+
1125
+ const TEST_KANJI = new RegExp('^' + kanji + '$');
1126
+ const TEST_NUMERIC = new RegExp('^' + numeric + '$');
1127
+ const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$');
1128
+
1129
+ regex.testKanji = function testKanji (str) {
1130
+ return TEST_KANJI.test(str)
1131
+ };
1132
+
1133
+ regex.testNumeric = function testNumeric (str) {
1134
+ return TEST_NUMERIC.test(str)
1135
+ };
1136
+
1137
+ regex.testAlphanumeric = function testAlphanumeric (str) {
1138
+ return TEST_ALPHANUMERIC.test(str)
1139
+ };
1140
+ return regex;
1141
+ }
1142
+
1143
+ var hasRequiredMode;
1144
+
1145
+ function requireMode () {
1146
+ if (hasRequiredMode) return mode;
1147
+ hasRequiredMode = 1;
1148
+ (function (exports) {
1149
+ const VersionCheck = requireVersionCheck();
1150
+ const Regex = requireRegex();
1151
+
1152
+ /**
1153
+ * Numeric mode encodes data from the decimal digit set (0 - 9)
1154
+ * (byte values 30HEX to 39HEX).
1155
+ * Normally, 3 data characters are represented by 10 bits.
1156
+ *
1157
+ * @type {Object}
1158
+ */
1159
+ exports.NUMERIC = {
1160
+ id: 'Numeric',
1161
+ bit: 1 << 0,
1162
+ ccBits: [10, 12, 14]
1163
+ };
1164
+
1165
+ /**
1166
+ * Alphanumeric mode encodes data from a set of 45 characters,
1167
+ * i.e. 10 numeric digits (0 - 9),
1168
+ * 26 alphabetic characters (A - Z),
1169
+ * and 9 symbols (SP, $, %, *, +, -, ., /, :).
1170
+ * Normally, two input characters are represented by 11 bits.
1171
+ *
1172
+ * @type {Object}
1173
+ */
1174
+ exports.ALPHANUMERIC = {
1175
+ id: 'Alphanumeric',
1176
+ bit: 1 << 1,
1177
+ ccBits: [9, 11, 13]
1178
+ };
1179
+
1180
+ /**
1181
+ * In byte mode, data is encoded at 8 bits per character.
1182
+ *
1183
+ * @type {Object}
1184
+ */
1185
+ exports.BYTE = {
1186
+ id: 'Byte',
1187
+ bit: 1 << 2,
1188
+ ccBits: [8, 16, 16]
1189
+ };
1190
+
1191
+ /**
1192
+ * The Kanji mode efficiently encodes Kanji characters in accordance with
1193
+ * the Shift JIS system based on JIS X 0208.
1194
+ * The Shift JIS values are shifted from the JIS X 0208 values.
1195
+ * JIS X 0208 gives details of the shift coded representation.
1196
+ * Each two-byte character value is compacted to a 13-bit binary codeword.
1197
+ *
1198
+ * @type {Object}
1199
+ */
1200
+ exports.KANJI = {
1201
+ id: 'Kanji',
1202
+ bit: 1 << 3,
1203
+ ccBits: [8, 10, 12]
1204
+ };
1205
+
1206
+ /**
1207
+ * Mixed mode will contain a sequences of data in a combination of any of
1208
+ * the modes described above
1209
+ *
1210
+ * @type {Object}
1211
+ */
1212
+ exports.MIXED = {
1213
+ bit: -1
1214
+ };
1215
+
1216
+ /**
1217
+ * Returns the number of bits needed to store the data length
1218
+ * according to QR Code specifications.
1219
+ *
1220
+ * @param {Mode} mode Data mode
1221
+ * @param {Number} version QR Code version
1222
+ * @return {Number} Number of bits
1223
+ */
1224
+ exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
1225
+ if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
1226
+
1227
+ if (!VersionCheck.isValid(version)) {
1228
+ throw new Error('Invalid version: ' + version)
1229
+ }
1230
+
1231
+ if (version >= 1 && version < 10) return mode.ccBits[0]
1232
+ else if (version < 27) return mode.ccBits[1]
1233
+ return mode.ccBits[2]
1234
+ };
1235
+
1236
+ /**
1237
+ * Returns the most efficient mode to store the specified data
1238
+ *
1239
+ * @param {String} dataStr Input data string
1240
+ * @return {Mode} Best mode
1241
+ */
1242
+ exports.getBestModeForData = function getBestModeForData (dataStr) {
1243
+ if (Regex.testNumeric(dataStr)) return exports.NUMERIC
1244
+ else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
1245
+ else if (Regex.testKanji(dataStr)) return exports.KANJI
1246
+ else return exports.BYTE
1247
+ };
1248
+
1249
+ /**
1250
+ * Return mode name as string
1251
+ *
1252
+ * @param {Mode} mode Mode object
1253
+ * @returns {String} Mode name
1254
+ */
1255
+ exports.toString = function toString (mode) {
1256
+ if (mode && mode.id) return mode.id
1257
+ throw new Error('Invalid mode')
1258
+ };
1259
+
1260
+ /**
1261
+ * Check if input param is a valid mode object
1262
+ *
1263
+ * @param {Mode} mode Mode object
1264
+ * @returns {Boolean} True if valid mode, false otherwise
1265
+ */
1266
+ exports.isValid = function isValid (mode) {
1267
+ return mode && mode.bit && mode.ccBits
1268
+ };
1269
+
1270
+ /**
1271
+ * Get mode object from its name
1272
+ *
1273
+ * @param {String} string Mode name
1274
+ * @returns {Mode} Mode object
1275
+ */
1276
+ function fromString (string) {
1277
+ if (typeof string !== 'string') {
1278
+ throw new Error('Param is not a string')
1279
+ }
1280
+
1281
+ const lcStr = string.toLowerCase();
1282
+
1283
+ switch (lcStr) {
1284
+ case 'numeric':
1285
+ return exports.NUMERIC
1286
+ case 'alphanumeric':
1287
+ return exports.ALPHANUMERIC
1288
+ case 'kanji':
1289
+ return exports.KANJI
1290
+ case 'byte':
1291
+ return exports.BYTE
1292
+ default:
1293
+ throw new Error('Unknown mode: ' + string)
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * Returns mode from a value.
1299
+ * If value is not a valid mode, returns defaultValue
1300
+ *
1301
+ * @param {Mode|String} value Encoding mode
1302
+ * @param {Mode} defaultValue Fallback value
1303
+ * @return {Mode} Encoding mode
1304
+ */
1305
+ exports.from = function from (value, defaultValue) {
1306
+ if (exports.isValid(value)) {
1307
+ return value
1308
+ }
1309
+
1310
+ try {
1311
+ return fromString(value)
1312
+ } catch (e) {
1313
+ return defaultValue
1314
+ }
1315
+ };
1316
+ } (mode));
1317
+ return mode;
1318
+ }
1319
+
1320
+ var hasRequiredVersion;
1321
+
1322
+ function requireVersion () {
1323
+ if (hasRequiredVersion) return version;
1324
+ hasRequiredVersion = 1;
1325
+ (function (exports) {
1326
+ const Utils = requireUtils$1();
1327
+ const ECCode = requireErrorCorrectionCode();
1328
+ const ECLevel = requireErrorCorrectionLevel();
1329
+ const Mode = requireMode();
1330
+ const VersionCheck = requireVersionCheck();
1331
+
1332
+ // Generator polynomial used to encode version information
1333
+ const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
1334
+ const G18_BCH = Utils.getBCHDigit(G18);
1335
+
1336
+ function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
1337
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
1338
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
1339
+ return currentVersion
1340
+ }
1341
+ }
1342
+
1343
+ return undefined
1344
+ }
1345
+
1346
+ function getReservedBitsCount (mode, version) {
1347
+ // Character count indicator + mode indicator bits
1348
+ return Mode.getCharCountIndicator(mode, version) + 4
1349
+ }
1350
+
1351
+ function getTotalBitsFromDataArray (segments, version) {
1352
+ let totalBits = 0;
1353
+
1354
+ segments.forEach(function (data) {
1355
+ const reservedBits = getReservedBitsCount(data.mode, version);
1356
+ totalBits += reservedBits + data.getBitsLength();
1357
+ });
1358
+
1359
+ return totalBits
1360
+ }
1361
+
1362
+ function getBestVersionForMixedData (segments, errorCorrectionLevel) {
1363
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
1364
+ const length = getTotalBitsFromDataArray(segments, currentVersion);
1365
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
1366
+ return currentVersion
1367
+ }
1368
+ }
1369
+
1370
+ return undefined
1371
+ }
1372
+
1373
+ /**
1374
+ * Returns version number from a value.
1375
+ * If value is not a valid version, returns defaultValue
1376
+ *
1377
+ * @param {Number|String} value QR Code version
1378
+ * @param {Number} defaultValue Fallback value
1379
+ * @return {Number} QR Code version number
1380
+ */
1381
+ exports.from = function from (value, defaultValue) {
1382
+ if (VersionCheck.isValid(value)) {
1383
+ return parseInt(value, 10)
1384
+ }
1385
+
1386
+ return defaultValue
1387
+ };
1388
+
1389
+ /**
1390
+ * Returns how much data can be stored with the specified QR code version
1391
+ * and error correction level
1392
+ *
1393
+ * @param {Number} version QR Code version (1-40)
1394
+ * @param {Number} errorCorrectionLevel Error correction level
1395
+ * @param {Mode} mode Data mode
1396
+ * @return {Number} Quantity of storable data
1397
+ */
1398
+ exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
1399
+ if (!VersionCheck.isValid(version)) {
1400
+ throw new Error('Invalid QR Code version')
1401
+ }
1402
+
1403
+ // Use Byte mode as default
1404
+ if (typeof mode === 'undefined') mode = Mode.BYTE;
1405
+
1406
+ // Total codewords for this QR code version (Data + Error correction)
1407
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
1408
+
1409
+ // Total number of error correction codewords
1410
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
1411
+
1412
+ // Total number of data codewords
1413
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
1414
+
1415
+ if (mode === Mode.MIXED) return dataTotalCodewordsBits
1416
+
1417
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
1418
+
1419
+ // Return max number of storable codewords
1420
+ switch (mode) {
1421
+ case Mode.NUMERIC:
1422
+ return Math.floor((usableBits / 10) * 3)
1423
+
1424
+ case Mode.ALPHANUMERIC:
1425
+ return Math.floor((usableBits / 11) * 2)
1426
+
1427
+ case Mode.KANJI:
1428
+ return Math.floor(usableBits / 13)
1429
+
1430
+ case Mode.BYTE:
1431
+ default:
1432
+ return Math.floor(usableBits / 8)
1433
+ }
1434
+ };
1435
+
1436
+ /**
1437
+ * Returns the minimum version needed to contain the amount of data
1438
+ *
1439
+ * @param {Segment} data Segment of data
1440
+ * @param {Number} [errorCorrectionLevel=H] Error correction level
1441
+ * @param {Mode} mode Data mode
1442
+ * @return {Number} QR Code version
1443
+ */
1444
+ exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
1445
+ let seg;
1446
+
1447
+ const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
1448
+
1449
+ if (Array.isArray(data)) {
1450
+ if (data.length > 1) {
1451
+ return getBestVersionForMixedData(data, ecl)
1452
+ }
1453
+
1454
+ if (data.length === 0) {
1455
+ return 1
1456
+ }
1457
+
1458
+ seg = data[0];
1459
+ } else {
1460
+ seg = data;
1461
+ }
1462
+
1463
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
1464
+ };
1465
+
1466
+ /**
1467
+ * Returns version information with relative error correction bits
1468
+ *
1469
+ * The version information is included in QR Code symbols of version 7 or larger.
1470
+ * It consists of an 18-bit sequence containing 6 data bits,
1471
+ * with 12 error correction bits calculated using the (18, 6) Golay code.
1472
+ *
1473
+ * @param {Number} version QR Code version
1474
+ * @return {Number} Encoded version info bits
1475
+ */
1476
+ exports.getEncodedBits = function getEncodedBits (version) {
1477
+ if (!VersionCheck.isValid(version) || version < 7) {
1478
+ throw new Error('Invalid QR Code version')
1479
+ }
1480
+
1481
+ let d = version << 12;
1482
+
1483
+ while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
1484
+ d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH));
1485
+ }
1486
+
1487
+ return (version << 12) | d
1488
+ };
1489
+ } (version));
1490
+ return version;
1491
+ }
1492
+
1493
+ var formatInfo = {};
1494
+
1495
+ var hasRequiredFormatInfo;
1496
+
1497
+ function requireFormatInfo () {
1498
+ if (hasRequiredFormatInfo) return formatInfo;
1499
+ hasRequiredFormatInfo = 1;
1500
+ const Utils = requireUtils$1();
1501
+
1502
+ const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
1503
+ const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
1504
+ const G15_BCH = Utils.getBCHDigit(G15);
1505
+
1506
+ /**
1507
+ * Returns format information with relative error correction bits
1508
+ *
1509
+ * The format information is a 15-bit sequence containing 5 data bits,
1510
+ * with 10 error correction bits calculated using the (15, 5) BCH code.
1511
+ *
1512
+ * @param {Number} errorCorrectionLevel Error correction level
1513
+ * @param {Number} mask Mask pattern
1514
+ * @return {Number} Encoded format information bits
1515
+ */
1516
+ formatInfo.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
1517
+ const data = ((errorCorrectionLevel.bit << 3) | mask);
1518
+ let d = data << 10;
1519
+
1520
+ while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
1521
+ d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH));
1522
+ }
1523
+
1524
+ // xor final data with mask pattern in order to ensure that
1525
+ // no combination of Error Correction Level and data mask pattern
1526
+ // will result in an all-zero data string
1527
+ return ((data << 10) | d) ^ G15_MASK
1528
+ };
1529
+ return formatInfo;
1530
+ }
1531
+
1532
+ var segments = {};
1533
+
1534
+ var numericData;
1535
+ var hasRequiredNumericData;
1536
+
1537
+ function requireNumericData () {
1538
+ if (hasRequiredNumericData) return numericData;
1539
+ hasRequiredNumericData = 1;
1540
+ const Mode = requireMode();
1541
+
1542
+ function NumericData (data) {
1543
+ this.mode = Mode.NUMERIC;
1544
+ this.data = data.toString();
1545
+ }
1546
+
1547
+ NumericData.getBitsLength = function getBitsLength (length) {
1548
+ return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
1549
+ };
1550
+
1551
+ NumericData.prototype.getLength = function getLength () {
1552
+ return this.data.length
1553
+ };
1554
+
1555
+ NumericData.prototype.getBitsLength = function getBitsLength () {
1556
+ return NumericData.getBitsLength(this.data.length)
1557
+ };
1558
+
1559
+ NumericData.prototype.write = function write (bitBuffer) {
1560
+ let i, group, value;
1561
+
1562
+ // The input data string is divided into groups of three digits,
1563
+ // and each group is converted to its 10-bit binary equivalent.
1564
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
1565
+ group = this.data.substr(i, 3);
1566
+ value = parseInt(group, 10);
1567
+
1568
+ bitBuffer.put(value, 10);
1569
+ }
1570
+
1571
+ // If the number of input digits is not an exact multiple of three,
1572
+ // the final one or two digits are converted to 4 or 7 bits respectively.
1573
+ const remainingNum = this.data.length - i;
1574
+ if (remainingNum > 0) {
1575
+ group = this.data.substr(i);
1576
+ value = parseInt(group, 10);
1577
+
1578
+ bitBuffer.put(value, remainingNum * 3 + 1);
1579
+ }
1580
+ };
1581
+
1582
+ numericData = NumericData;
1583
+ return numericData;
1584
+ }
1585
+
1586
+ var alphanumericData;
1587
+ var hasRequiredAlphanumericData;
1588
+
1589
+ function requireAlphanumericData () {
1590
+ if (hasRequiredAlphanumericData) return alphanumericData;
1591
+ hasRequiredAlphanumericData = 1;
1592
+ const Mode = requireMode();
1593
+
1594
+ /**
1595
+ * Array of characters available in alphanumeric mode
1596
+ *
1597
+ * As per QR Code specification, to each character
1598
+ * is assigned a value from 0 to 44 which in this case coincides
1599
+ * with the array index
1600
+ *
1601
+ * @type {Array}
1602
+ */
1603
+ const ALPHA_NUM_CHARS = [
1604
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1605
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
1606
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
1607
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'
1608
+ ];
1609
+
1610
+ function AlphanumericData (data) {
1611
+ this.mode = Mode.ALPHANUMERIC;
1612
+ this.data = data;
1613
+ }
1614
+
1615
+ AlphanumericData.getBitsLength = function getBitsLength (length) {
1616
+ return 11 * Math.floor(length / 2) + 6 * (length % 2)
1617
+ };
1618
+
1619
+ AlphanumericData.prototype.getLength = function getLength () {
1620
+ return this.data.length
1621
+ };
1622
+
1623
+ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
1624
+ return AlphanumericData.getBitsLength(this.data.length)
1625
+ };
1626
+
1627
+ AlphanumericData.prototype.write = function write (bitBuffer) {
1628
+ let i;
1629
+
1630
+ // Input data characters are divided into groups of two characters
1631
+ // and encoded as 11-bit binary codes.
1632
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
1633
+ // The character value of the first character is multiplied by 45
1634
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
1635
+
1636
+ // The character value of the second digit is added to the product
1637
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
1638
+
1639
+ // The sum is then stored as 11-bit binary number
1640
+ bitBuffer.put(value, 11);
1641
+ }
1642
+
1643
+ // If the number of input data characters is not a multiple of two,
1644
+ // the character value of the final character is encoded as a 6-bit binary number.
1645
+ if (this.data.length % 2) {
1646
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
1647
+ }
1648
+ };
1649
+
1650
+ alphanumericData = AlphanumericData;
1651
+ return alphanumericData;
1652
+ }
1653
+
1654
+ var byteData;
1655
+ var hasRequiredByteData;
1656
+
1657
+ function requireByteData () {
1658
+ if (hasRequiredByteData) return byteData;
1659
+ hasRequiredByteData = 1;
1660
+ const Mode = requireMode();
1661
+
1662
+ function ByteData (data) {
1663
+ this.mode = Mode.BYTE;
1664
+ if (typeof (data) === 'string') {
1665
+ this.data = new TextEncoder().encode(data);
1666
+ } else {
1667
+ this.data = new Uint8Array(data);
1668
+ }
1669
+ }
1670
+
1671
+ ByteData.getBitsLength = function getBitsLength (length) {
1672
+ return length * 8
1673
+ };
1674
+
1675
+ ByteData.prototype.getLength = function getLength () {
1676
+ return this.data.length
1677
+ };
1678
+
1679
+ ByteData.prototype.getBitsLength = function getBitsLength () {
1680
+ return ByteData.getBitsLength(this.data.length)
1681
+ };
1682
+
1683
+ ByteData.prototype.write = function (bitBuffer) {
1684
+ for (let i = 0, l = this.data.length; i < l; i++) {
1685
+ bitBuffer.put(this.data[i], 8);
1686
+ }
1687
+ };
1688
+
1689
+ byteData = ByteData;
1690
+ return byteData;
1691
+ }
1692
+
1693
+ var kanjiData;
1694
+ var hasRequiredKanjiData;
1695
+
1696
+ function requireKanjiData () {
1697
+ if (hasRequiredKanjiData) return kanjiData;
1698
+ hasRequiredKanjiData = 1;
1699
+ const Mode = requireMode();
1700
+ const Utils = requireUtils$1();
1701
+
1702
+ function KanjiData (data) {
1703
+ this.mode = Mode.KANJI;
1704
+ this.data = data;
1705
+ }
1706
+
1707
+ KanjiData.getBitsLength = function getBitsLength (length) {
1708
+ return length * 13
1709
+ };
1710
+
1711
+ KanjiData.prototype.getLength = function getLength () {
1712
+ return this.data.length
1713
+ };
1714
+
1715
+ KanjiData.prototype.getBitsLength = function getBitsLength () {
1716
+ return KanjiData.getBitsLength(this.data.length)
1717
+ };
1718
+
1719
+ KanjiData.prototype.write = function (bitBuffer) {
1720
+ let i;
1721
+
1722
+ // In the Shift JIS system, Kanji characters are represented by a two byte combination.
1723
+ // These byte values are shifted from the JIS X 0208 values.
1724
+ // JIS X 0208 gives details of the shift coded representation.
1725
+ for (i = 0; i < this.data.length; i++) {
1726
+ let value = Utils.toSJIS(this.data[i]);
1727
+
1728
+ // For characters with Shift JIS values from 0x8140 to 0x9FFC:
1729
+ if (value >= 0x8140 && value <= 0x9FFC) {
1730
+ // Subtract 0x8140 from Shift JIS value
1731
+ value -= 0x8140;
1732
+
1733
+ // For characters with Shift JIS values from 0xE040 to 0xEBBF
1734
+ } else if (value >= 0xE040 && value <= 0xEBBF) {
1735
+ // Subtract 0xC140 from Shift JIS value
1736
+ value -= 0xC140;
1737
+ } else {
1738
+ throw new Error(
1739
+ 'Invalid SJIS character: ' + this.data[i] + '\n' +
1740
+ 'Make sure your charset is UTF-8')
1741
+ }
1742
+
1743
+ // Multiply most significant byte of result by 0xC0
1744
+ // and add least significant byte to product
1745
+ value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff);
1746
+
1747
+ // Convert result to a 13-bit binary string
1748
+ bitBuffer.put(value, 13);
1749
+ }
1750
+ };
1751
+
1752
+ kanjiData = KanjiData;
1753
+ return kanjiData;
1754
+ }
1755
+
1756
+ var dijkstra = {exports: {}};
1757
+
1758
+ var hasRequiredDijkstra;
1759
+
1760
+ function requireDijkstra () {
1761
+ if (hasRequiredDijkstra) return dijkstra.exports;
1762
+ hasRequiredDijkstra = 1;
1763
+ (function (module) {
1764
+
1765
+ /******************************************************************************
1766
+ * Created 2008-08-19.
1767
+ *
1768
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
1769
+ *
1770
+ * Copyright (C) 2008
1771
+ * Wyatt Baldwin <self@wyattbaldwin.com>
1772
+ * All rights reserved
1773
+ *
1774
+ * Licensed under the MIT license.
1775
+ *
1776
+ * http://www.opensource.org/licenses/mit-license.php
1777
+ *
1778
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1779
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1780
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1781
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1782
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1783
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1784
+ * THE SOFTWARE.
1785
+ *****************************************************************************/
1786
+ var dijkstra = {
1787
+ single_source_shortest_paths: function(graph, s, d) {
1788
+ // Predecessor map for each node that has been encountered.
1789
+ // node ID => predecessor node ID
1790
+ var predecessors = {};
1791
+
1792
+ // Costs of shortest paths from s to all nodes encountered.
1793
+ // node ID => cost
1794
+ var costs = {};
1795
+ costs[s] = 0;
1796
+
1797
+ // Costs of shortest paths from s to all nodes encountered; differs from
1798
+ // `costs` in that it provides easy access to the node that currently has
1799
+ // the known shortest path from s.
1800
+ // XXX: Do we actually need both `costs` and `open`?
1801
+ var open = dijkstra.PriorityQueue.make();
1802
+ open.push(s, 0);
1803
+
1804
+ var closest,
1805
+ u, v,
1806
+ cost_of_s_to_u,
1807
+ adjacent_nodes,
1808
+ cost_of_e,
1809
+ cost_of_s_to_u_plus_cost_of_e,
1810
+ cost_of_s_to_v,
1811
+ first_visit;
1812
+ while (!open.empty()) {
1813
+ // In the nodes remaining in graph that have a known cost from s,
1814
+ // find the node, u, that currently has the shortest path from s.
1815
+ closest = open.pop();
1816
+ u = closest.value;
1817
+ cost_of_s_to_u = closest.cost;
1818
+
1819
+ // Get nodes adjacent to u...
1820
+ adjacent_nodes = graph[u] || {};
1821
+
1822
+ // ...and explore the edges that connect u to those nodes, updating
1823
+ // the cost of the shortest paths to any or all of those nodes as
1824
+ // necessary. v is the node across the current edge from u.
1825
+ for (v in adjacent_nodes) {
1826
+ if (adjacent_nodes.hasOwnProperty(v)) {
1827
+ // Get the cost of the edge running from u to v.
1828
+ cost_of_e = adjacent_nodes[v];
1829
+
1830
+ // Cost of s to u plus the cost of u to v across e--this is *a*
1831
+ // cost from s to v that may or may not be less than the current
1832
+ // known cost to v.
1833
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
1834
+
1835
+ // If we haven't visited v yet OR if the current known cost from s to
1836
+ // v is greater than the new cost we just found (cost of s to u plus
1837
+ // cost of u to v across e), update v's cost in the cost list and
1838
+ // update v's predecessor in the predecessor list (it's now u).
1839
+ cost_of_s_to_v = costs[v];
1840
+ first_visit = (typeof costs[v] === 'undefined');
1841
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
1842
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
1843
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
1844
+ predecessors[v] = u;
1845
+ }
1846
+ }
1847
+ }
1848
+ }
1849
+
1850
+ if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
1851
+ var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
1852
+ throw new Error(msg);
1853
+ }
1854
+
1855
+ return predecessors;
1856
+ },
1857
+
1858
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
1859
+ var nodes = [];
1860
+ var u = d;
1861
+ while (u) {
1862
+ nodes.push(u);
1863
+ u = predecessors[u];
1864
+ }
1865
+ nodes.reverse();
1866
+ return nodes;
1867
+ },
1868
+
1869
+ find_path: function(graph, s, d) {
1870
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
1871
+ return dijkstra.extract_shortest_path_from_predecessor_list(
1872
+ predecessors, d);
1873
+ },
1874
+
1875
+ /**
1876
+ * A very naive priority queue implementation.
1877
+ */
1878
+ PriorityQueue: {
1879
+ make: function (opts) {
1880
+ var T = dijkstra.PriorityQueue,
1881
+ t = {},
1882
+ key;
1883
+ opts = opts || {};
1884
+ for (key in T) {
1885
+ if (T.hasOwnProperty(key)) {
1886
+ t[key] = T[key];
1887
+ }
1888
+ }
1889
+ t.queue = [];
1890
+ t.sorter = opts.sorter || T.default_sorter;
1891
+ return t;
1892
+ },
1893
+
1894
+ default_sorter: function (a, b) {
1895
+ return a.cost - b.cost;
1896
+ },
1897
+
1898
+ /**
1899
+ * Add a new item to the queue and ensure the highest priority element
1900
+ * is at the front of the queue.
1901
+ */
1902
+ push: function (value, cost) {
1903
+ var item = {value: value, cost: cost};
1904
+ this.queue.push(item);
1905
+ this.queue.sort(this.sorter);
1906
+ },
1907
+
1908
+ /**
1909
+ * Return the highest priority element in the queue.
1910
+ */
1911
+ pop: function () {
1912
+ return this.queue.shift();
1913
+ },
1914
+
1915
+ empty: function () {
1916
+ return this.queue.length === 0;
1917
+ }
1918
+ }
1919
+ };
1920
+
1921
+
1922
+ // node.js module exports
1923
+ {
1924
+ module.exports = dijkstra;
1925
+ }
1926
+ } (dijkstra));
1927
+ return dijkstra.exports;
1928
+ }
1929
+
1930
+ var hasRequiredSegments;
1931
+
1932
+ function requireSegments () {
1933
+ if (hasRequiredSegments) return segments;
1934
+ hasRequiredSegments = 1;
1935
+ (function (exports) {
1936
+ const Mode = requireMode();
1937
+ const NumericData = requireNumericData();
1938
+ const AlphanumericData = requireAlphanumericData();
1939
+ const ByteData = requireByteData();
1940
+ const KanjiData = requireKanjiData();
1941
+ const Regex = requireRegex();
1942
+ const Utils = requireUtils$1();
1943
+ const dijkstra = requireDijkstra();
1944
+
1945
+ /**
1946
+ * Returns UTF8 byte length
1947
+ *
1948
+ * @param {String} str Input string
1949
+ * @return {Number} Number of byte
1950
+ */
1951
+ function getStringByteLength (str) {
1952
+ return unescape(encodeURIComponent(str)).length
1953
+ }
1954
+
1955
+ /**
1956
+ * Get a list of segments of the specified mode
1957
+ * from a string
1958
+ *
1959
+ * @param {Mode} mode Segment mode
1960
+ * @param {String} str String to process
1961
+ * @return {Array} Array of object with segments data
1962
+ */
1963
+ function getSegments (regex, mode, str) {
1964
+ const segments = [];
1965
+ let result;
1966
+
1967
+ while ((result = regex.exec(str)) !== null) {
1968
+ segments.push({
1969
+ data: result[0],
1970
+ index: result.index,
1971
+ mode: mode,
1972
+ length: result[0].length
1973
+ });
1974
+ }
1975
+
1976
+ return segments
1977
+ }
1978
+
1979
+ /**
1980
+ * Extracts a series of segments with the appropriate
1981
+ * modes from a string
1982
+ *
1983
+ * @param {String} dataStr Input string
1984
+ * @return {Array} Array of object with segments data
1985
+ */
1986
+ function getSegmentsFromString (dataStr) {
1987
+ const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
1988
+ const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
1989
+ let byteSegs;
1990
+ let kanjiSegs;
1991
+
1992
+ if (Utils.isKanjiModeEnabled()) {
1993
+ byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
1994
+ kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
1995
+ } else {
1996
+ byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
1997
+ kanjiSegs = [];
1998
+ }
1999
+
2000
+ const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
2001
+
2002
+ return segs
2003
+ .sort(function (s1, s2) {
2004
+ return s1.index - s2.index
2005
+ })
2006
+ .map(function (obj) {
2007
+ return {
2008
+ data: obj.data,
2009
+ mode: obj.mode,
2010
+ length: obj.length
2011
+ }
2012
+ })
2013
+ }
2014
+
2015
+ /**
2016
+ * Returns how many bits are needed to encode a string of
2017
+ * specified length with the specified mode
2018
+ *
2019
+ * @param {Number} length String length
2020
+ * @param {Mode} mode Segment mode
2021
+ * @return {Number} Bit length
2022
+ */
2023
+ function getSegmentBitsLength (length, mode) {
2024
+ switch (mode) {
2025
+ case Mode.NUMERIC:
2026
+ return NumericData.getBitsLength(length)
2027
+ case Mode.ALPHANUMERIC:
2028
+ return AlphanumericData.getBitsLength(length)
2029
+ case Mode.KANJI:
2030
+ return KanjiData.getBitsLength(length)
2031
+ case Mode.BYTE:
2032
+ return ByteData.getBitsLength(length)
2033
+ }
2034
+ }
2035
+
2036
+ /**
2037
+ * Merges adjacent segments which have the same mode
2038
+ *
2039
+ * @param {Array} segs Array of object with segments data
2040
+ * @return {Array} Array of object with segments data
2041
+ */
2042
+ function mergeSegments (segs) {
2043
+ return segs.reduce(function (acc, curr) {
2044
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
2045
+ if (prevSeg && prevSeg.mode === curr.mode) {
2046
+ acc[acc.length - 1].data += curr.data;
2047
+ return acc
2048
+ }
2049
+
2050
+ acc.push(curr);
2051
+ return acc
2052
+ }, [])
2053
+ }
2054
+
2055
+ /**
2056
+ * Generates a list of all possible nodes combination which
2057
+ * will be used to build a segments graph.
2058
+ *
2059
+ * Nodes are divided by groups. Each group will contain a list of all the modes
2060
+ * in which is possible to encode the given text.
2061
+ *
2062
+ * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
2063
+ * The group for '12345' will contain then 3 objects, one for each
2064
+ * possible encoding mode.
2065
+ *
2066
+ * Each node represents a possible segment.
2067
+ *
2068
+ * @param {Array} segs Array of object with segments data
2069
+ * @return {Array} Array of object with segments data
2070
+ */
2071
+ function buildNodes (segs) {
2072
+ const nodes = [];
2073
+ for (let i = 0; i < segs.length; i++) {
2074
+ const seg = segs[i];
2075
+
2076
+ switch (seg.mode) {
2077
+ case Mode.NUMERIC:
2078
+ nodes.push([seg,
2079
+ { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
2080
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2081
+ ]);
2082
+ break
2083
+ case Mode.ALPHANUMERIC:
2084
+ nodes.push([seg,
2085
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2086
+ ]);
2087
+ break
2088
+ case Mode.KANJI:
2089
+ nodes.push([seg,
2090
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2091
+ ]);
2092
+ break
2093
+ case Mode.BYTE:
2094
+ nodes.push([
2095
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2096
+ ]);
2097
+ }
2098
+ }
2099
+
2100
+ return nodes
2101
+ }
2102
+
2103
+ /**
2104
+ * Builds a graph from a list of nodes.
2105
+ * All segments in each node group will be connected with all the segments of
2106
+ * the next group and so on.
2107
+ *
2108
+ * At each connection will be assigned a weight depending on the
2109
+ * segment's byte length.
2110
+ *
2111
+ * @param {Array} nodes Array of object with segments data
2112
+ * @param {Number} version QR Code version
2113
+ * @return {Object} Graph of all possible segments
2114
+ */
2115
+ function buildGraph (nodes, version) {
2116
+ const table = {};
2117
+ const graph = { start: {} };
2118
+ let prevNodeIds = ['start'];
2119
+
2120
+ for (let i = 0; i < nodes.length; i++) {
2121
+ const nodeGroup = nodes[i];
2122
+ const currentNodeIds = [];
2123
+
2124
+ for (let j = 0; j < nodeGroup.length; j++) {
2125
+ const node = nodeGroup[j];
2126
+ const key = '' + i + j;
2127
+
2128
+ currentNodeIds.push(key);
2129
+ table[key] = { node: node, lastCount: 0 };
2130
+ graph[key] = {};
2131
+
2132
+ for (let n = 0; n < prevNodeIds.length; n++) {
2133
+ const prevNodeId = prevNodeIds[n];
2134
+
2135
+ if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
2136
+ graph[prevNodeId][key] =
2137
+ getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
2138
+ getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
2139
+
2140
+ table[prevNodeId].lastCount += node.length;
2141
+ } else {
2142
+ if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
2143
+
2144
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
2145
+ 4 + Mode.getCharCountIndicator(node.mode, version); // switch cost
2146
+ }
2147
+ }
2148
+ }
2149
+
2150
+ prevNodeIds = currentNodeIds;
2151
+ }
2152
+
2153
+ for (let n = 0; n < prevNodeIds.length; n++) {
2154
+ graph[prevNodeIds[n]].end = 0;
2155
+ }
2156
+
2157
+ return { map: graph, table: table }
2158
+ }
2159
+
2160
+ /**
2161
+ * Builds a segment from a specified data and mode.
2162
+ * If a mode is not specified, the more suitable will be used.
2163
+ *
2164
+ * @param {String} data Input data
2165
+ * @param {Mode | String} modesHint Data mode
2166
+ * @return {Segment} Segment
2167
+ */
2168
+ function buildSingleSegment (data, modesHint) {
2169
+ let mode;
2170
+ const bestMode = Mode.getBestModeForData(data);
2171
+
2172
+ mode = Mode.from(modesHint, bestMode);
2173
+
2174
+ // Make sure data can be encoded
2175
+ if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
2176
+ throw new Error('"' + data + '"' +
2177
+ ' cannot be encoded with mode ' + Mode.toString(mode) +
2178
+ '.\n Suggested mode is: ' + Mode.toString(bestMode))
2179
+ }
2180
+
2181
+ // Use Mode.BYTE if Kanji support is disabled
2182
+ if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
2183
+ mode = Mode.BYTE;
2184
+ }
2185
+
2186
+ switch (mode) {
2187
+ case Mode.NUMERIC:
2188
+ return new NumericData(data)
2189
+
2190
+ case Mode.ALPHANUMERIC:
2191
+ return new AlphanumericData(data)
2192
+
2193
+ case Mode.KANJI:
2194
+ return new KanjiData(data)
2195
+
2196
+ case Mode.BYTE:
2197
+ return new ByteData(data)
2198
+ }
2199
+ }
2200
+
2201
+ /**
2202
+ * Builds a list of segments from an array.
2203
+ * Array can contain Strings or Objects with segment's info.
2204
+ *
2205
+ * For each item which is a string, will be generated a segment with the given
2206
+ * string and the more appropriate encoding mode.
2207
+ *
2208
+ * For each item which is an object, will be generated a segment with the given
2209
+ * data and mode.
2210
+ * Objects must contain at least the property "data".
2211
+ * If property "mode" is not present, the more suitable mode will be used.
2212
+ *
2213
+ * @param {Array} array Array of objects with segments data
2214
+ * @return {Array} Array of Segments
2215
+ */
2216
+ exports.fromArray = function fromArray (array) {
2217
+ return array.reduce(function (acc, seg) {
2218
+ if (typeof seg === 'string') {
2219
+ acc.push(buildSingleSegment(seg, null));
2220
+ } else if (seg.data) {
2221
+ acc.push(buildSingleSegment(seg.data, seg.mode));
2222
+ }
2223
+
2224
+ return acc
2225
+ }, [])
2226
+ };
2227
+
2228
+ /**
2229
+ * Builds an optimized sequence of segments from a string,
2230
+ * which will produce the shortest possible bitstream.
2231
+ *
2232
+ * @param {String} data Input string
2233
+ * @param {Number} version QR Code version
2234
+ * @return {Array} Array of segments
2235
+ */
2236
+ exports.fromString = function fromString (data, version) {
2237
+ const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
2238
+
2239
+ const nodes = buildNodes(segs);
2240
+ const graph = buildGraph(nodes, version);
2241
+ const path = dijkstra.find_path(graph.map, 'start', 'end');
2242
+
2243
+ const optimizedSegs = [];
2244
+ for (let i = 1; i < path.length - 1; i++) {
2245
+ optimizedSegs.push(graph.table[path[i]].node);
2246
+ }
2247
+
2248
+ return exports.fromArray(mergeSegments(optimizedSegs))
2249
+ };
2250
+
2251
+ /**
2252
+ * Splits a string in various segments with the modes which
2253
+ * best represent their content.
2254
+ * The produced segments are far from being optimized.
2255
+ * The output of this function is only used to estimate a QR Code version
2256
+ * which may contain the data.
2257
+ *
2258
+ * @param {string} data Input string
2259
+ * @return {Array} Array of segments
2260
+ */
2261
+ exports.rawSplit = function rawSplit (data) {
2262
+ return exports.fromArray(
2263
+ getSegmentsFromString(data, Utils.isKanjiModeEnabled())
2264
+ )
2265
+ };
2266
+ } (segments));
2267
+ return segments;
2268
+ }
2269
+
2270
+ var hasRequiredQrcode;
2271
+
2272
+ function requireQrcode () {
2273
+ if (hasRequiredQrcode) return qrcode;
2274
+ hasRequiredQrcode = 1;
2275
+ const Utils = requireUtils$1();
2276
+ const ECLevel = requireErrorCorrectionLevel();
2277
+ const BitBuffer = requireBitBuffer();
2278
+ const BitMatrix = requireBitMatrix();
2279
+ const AlignmentPattern = requireAlignmentPattern();
2280
+ const FinderPattern = requireFinderPattern();
2281
+ const MaskPattern = requireMaskPattern();
2282
+ const ECCode = requireErrorCorrectionCode();
2283
+ const ReedSolomonEncoder = requireReedSolomonEncoder();
2284
+ const Version = requireVersion();
2285
+ const FormatInfo = requireFormatInfo();
2286
+ const Mode = requireMode();
2287
+ const Segments = requireSegments();
2288
+
2289
+ /**
2290
+ * QRCode for JavaScript
2291
+ *
2292
+ * modified by Ryan Day for nodejs support
2293
+ * Copyright (c) 2011 Ryan Day
2294
+ *
2295
+ * Licensed under the MIT license:
2296
+ * http://www.opensource.org/licenses/mit-license.php
2297
+ *
2298
+ //---------------------------------------------------------------------
2299
+ // QRCode for JavaScript
2300
+ //
2301
+ // Copyright (c) 2009 Kazuhiko Arase
2302
+ //
2303
+ // URL: http://www.d-project.com/
2304
+ //
2305
+ // Licensed under the MIT license:
2306
+ // http://www.opensource.org/licenses/mit-license.php
2307
+ //
2308
+ // The word "QR Code" is registered trademark of
2309
+ // DENSO WAVE INCORPORATED
2310
+ // http://www.denso-wave.com/qrcode/faqpatent-e.html
2311
+ //
2312
+ //---------------------------------------------------------------------
2313
+ */
2314
+
2315
+ /**
2316
+ * Add finder patterns bits to matrix
2317
+ *
2318
+ * @param {BitMatrix} matrix Modules matrix
2319
+ * @param {Number} version QR Code version
2320
+ */
2321
+ function setupFinderPattern (matrix, version) {
2322
+ const size = matrix.size;
2323
+ const pos = FinderPattern.getPositions(version);
2324
+
2325
+ for (let i = 0; i < pos.length; i++) {
2326
+ const row = pos[i][0];
2327
+ const col = pos[i][1];
2328
+
2329
+ for (let r = -1; r <= 7; r++) {
2330
+ if (row + r <= -1 || size <= row + r) continue
2331
+
2332
+ for (let c = -1; c <= 7; c++) {
2333
+ if (col + c <= -1 || size <= col + c) continue
2334
+
2335
+ if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
2336
+ (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
2337
+ (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
2338
+ matrix.set(row + r, col + c, true, true);
2339
+ } else {
2340
+ matrix.set(row + r, col + c, false, true);
2341
+ }
2342
+ }
2343
+ }
2344
+ }
2345
+ }
2346
+
2347
+ /**
2348
+ * Add timing pattern bits to matrix
2349
+ *
2350
+ * Note: this function must be called before {@link setupAlignmentPattern}
2351
+ *
2352
+ * @param {BitMatrix} matrix Modules matrix
2353
+ */
2354
+ function setupTimingPattern (matrix) {
2355
+ const size = matrix.size;
2356
+
2357
+ for (let r = 8; r < size - 8; r++) {
2358
+ const value = r % 2 === 0;
2359
+ matrix.set(r, 6, value, true);
2360
+ matrix.set(6, r, value, true);
2361
+ }
2362
+ }
2363
+
2364
+ /**
2365
+ * Add alignment patterns bits to matrix
2366
+ *
2367
+ * Note: this function must be called after {@link setupTimingPattern}
2368
+ *
2369
+ * @param {BitMatrix} matrix Modules matrix
2370
+ * @param {Number} version QR Code version
2371
+ */
2372
+ function setupAlignmentPattern (matrix, version) {
2373
+ const pos = AlignmentPattern.getPositions(version);
2374
+
2375
+ for (let i = 0; i < pos.length; i++) {
2376
+ const row = pos[i][0];
2377
+ const col = pos[i][1];
2378
+
2379
+ for (let r = -2; r <= 2; r++) {
2380
+ for (let c = -2; c <= 2; c++) {
2381
+ if (r === -2 || r === 2 || c === -2 || c === 2 ||
2382
+ (r === 0 && c === 0)) {
2383
+ matrix.set(row + r, col + c, true, true);
2384
+ } else {
2385
+ matrix.set(row + r, col + c, false, true);
2386
+ }
2387
+ }
2388
+ }
2389
+ }
2390
+ }
2391
+
2392
+ /**
2393
+ * Add version info bits to matrix
2394
+ *
2395
+ * @param {BitMatrix} matrix Modules matrix
2396
+ * @param {Number} version QR Code version
2397
+ */
2398
+ function setupVersionInfo (matrix, version) {
2399
+ const size = matrix.size;
2400
+ const bits = Version.getEncodedBits(version);
2401
+ let row, col, mod;
2402
+
2403
+ for (let i = 0; i < 18; i++) {
2404
+ row = Math.floor(i / 3);
2405
+ col = i % 3 + size - 8 - 3;
2406
+ mod = ((bits >> i) & 1) === 1;
2407
+
2408
+ matrix.set(row, col, mod, true);
2409
+ matrix.set(col, row, mod, true);
2410
+ }
2411
+ }
2412
+
2413
+ /**
2414
+ * Add format info bits to matrix
2415
+ *
2416
+ * @param {BitMatrix} matrix Modules matrix
2417
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2418
+ * @param {Number} maskPattern Mask pattern reference value
2419
+ */
2420
+ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
2421
+ const size = matrix.size;
2422
+ const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
2423
+ let i, mod;
2424
+
2425
+ for (i = 0; i < 15; i++) {
2426
+ mod = ((bits >> i) & 1) === 1;
2427
+
2428
+ // vertical
2429
+ if (i < 6) {
2430
+ matrix.set(i, 8, mod, true);
2431
+ } else if (i < 8) {
2432
+ matrix.set(i + 1, 8, mod, true);
2433
+ } else {
2434
+ matrix.set(size - 15 + i, 8, mod, true);
2435
+ }
2436
+
2437
+ // horizontal
2438
+ if (i < 8) {
2439
+ matrix.set(8, size - i - 1, mod, true);
2440
+ } else if (i < 9) {
2441
+ matrix.set(8, 15 - i - 1 + 1, mod, true);
2442
+ } else {
2443
+ matrix.set(8, 15 - i - 1, mod, true);
2444
+ }
2445
+ }
2446
+
2447
+ // fixed module
2448
+ matrix.set(size - 8, 8, 1, true);
2449
+ }
2450
+
2451
+ /**
2452
+ * Add encoded data bits to matrix
2453
+ *
2454
+ * @param {BitMatrix} matrix Modules matrix
2455
+ * @param {Uint8Array} data Data codewords
2456
+ */
2457
+ function setupData (matrix, data) {
2458
+ const size = matrix.size;
2459
+ let inc = -1;
2460
+ let row = size - 1;
2461
+ let bitIndex = 7;
2462
+ let byteIndex = 0;
2463
+
2464
+ for (let col = size - 1; col > 0; col -= 2) {
2465
+ if (col === 6) col--;
2466
+
2467
+ while (true) {
2468
+ for (let c = 0; c < 2; c++) {
2469
+ if (!matrix.isReserved(row, col - c)) {
2470
+ let dark = false;
2471
+
2472
+ if (byteIndex < data.length) {
2473
+ dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
2474
+ }
2475
+
2476
+ matrix.set(row, col - c, dark);
2477
+ bitIndex--;
2478
+
2479
+ if (bitIndex === -1) {
2480
+ byteIndex++;
2481
+ bitIndex = 7;
2482
+ }
2483
+ }
2484
+ }
2485
+
2486
+ row += inc;
2487
+
2488
+ if (row < 0 || size <= row) {
2489
+ row -= inc;
2490
+ inc = -inc;
2491
+ break
2492
+ }
2493
+ }
2494
+ }
2495
+ }
2496
+
2497
+ /**
2498
+ * Create encoded codewords from data input
2499
+ *
2500
+ * @param {Number} version QR Code version
2501
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2502
+ * @param {ByteData} data Data input
2503
+ * @return {Uint8Array} Buffer containing encoded codewords
2504
+ */
2505
+ function createData (version, errorCorrectionLevel, segments) {
2506
+ // Prepare data buffer
2507
+ const buffer = new BitBuffer();
2508
+
2509
+ segments.forEach(function (data) {
2510
+ // prefix data with mode indicator (4 bits)
2511
+ buffer.put(data.mode.bit, 4);
2512
+
2513
+ // Prefix data with character count indicator.
2514
+ // The character count indicator is a string of bits that represents the
2515
+ // number of characters that are being encoded.
2516
+ // The character count indicator must be placed after the mode indicator
2517
+ // and must be a certain number of bits long, depending on the QR version
2518
+ // and data mode
2519
+ // @see {@link Mode.getCharCountIndicator}.
2520
+ buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
2521
+
2522
+ // add binary data sequence to buffer
2523
+ data.write(buffer);
2524
+ });
2525
+
2526
+ // Calculate required number of bits
2527
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2528
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2529
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
2530
+
2531
+ // Add a terminator.
2532
+ // If the bit string is shorter than the total number of required bits,
2533
+ // a terminator of up to four 0s must be added to the right side of the string.
2534
+ // If the bit string is more than four bits shorter than the required number of bits,
2535
+ // add four 0s to the end.
2536
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
2537
+ buffer.put(0, 4);
2538
+ }
2539
+
2540
+ // If the bit string is fewer than four bits shorter, add only the number of 0s that
2541
+ // are needed to reach the required number of bits.
2542
+
2543
+ // After adding the terminator, if the number of bits in the string is not a multiple of 8,
2544
+ // pad the string on the right with 0s to make the string's length a multiple of 8.
2545
+ while (buffer.getLengthInBits() % 8 !== 0) {
2546
+ buffer.putBit(0);
2547
+ }
2548
+
2549
+ // Add pad bytes if the string is still shorter than the total number of required bits.
2550
+ // Extend the buffer to fill the data capacity of the symbol corresponding to
2551
+ // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
2552
+ // and 00010001 (0x11) alternately.
2553
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
2554
+ for (let i = 0; i < remainingByte; i++) {
2555
+ buffer.put(i % 2 ? 0x11 : 0xEC, 8);
2556
+ }
2557
+
2558
+ return createCodewords(buffer, version, errorCorrectionLevel)
2559
+ }
2560
+
2561
+ /**
2562
+ * Encode input data with Reed-Solomon and return codewords with
2563
+ * relative error correction bits
2564
+ *
2565
+ * @param {BitBuffer} bitBuffer Data to encode
2566
+ * @param {Number} version QR Code version
2567
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2568
+ * @return {Uint8Array} Buffer containing encoded codewords
2569
+ */
2570
+ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
2571
+ // Total codewords for this QR code version (Data + Error correction)
2572
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2573
+
2574
+ // Total number of error correction codewords
2575
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2576
+
2577
+ // Total number of data codewords
2578
+ const dataTotalCodewords = totalCodewords - ecTotalCodewords;
2579
+
2580
+ // Total number of blocks
2581
+ const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
2582
+
2583
+ // Calculate how many blocks each group should contain
2584
+ const blocksInGroup2 = totalCodewords % ecTotalBlocks;
2585
+ const blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
2586
+
2587
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
2588
+
2589
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
2590
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
2591
+
2592
+ // Number of EC codewords is the same for both groups
2593
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
2594
+
2595
+ // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
2596
+ const rs = new ReedSolomonEncoder(ecCount);
2597
+
2598
+ let offset = 0;
2599
+ const dcData = new Array(ecTotalBlocks);
2600
+ const ecData = new Array(ecTotalBlocks);
2601
+ let maxDataSize = 0;
2602
+ const buffer = new Uint8Array(bitBuffer.buffer);
2603
+
2604
+ // Divide the buffer into the required number of blocks
2605
+ for (let b = 0; b < ecTotalBlocks; b++) {
2606
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
2607
+
2608
+ // extract a block of data from buffer
2609
+ dcData[b] = buffer.slice(offset, offset + dataSize);
2610
+
2611
+ // Calculate EC codewords for this data block
2612
+ ecData[b] = rs.encode(dcData[b]);
2613
+
2614
+ offset += dataSize;
2615
+ maxDataSize = Math.max(maxDataSize, dataSize);
2616
+ }
2617
+
2618
+ // Create final data
2619
+ // Interleave the data and error correction codewords from each block
2620
+ const data = new Uint8Array(totalCodewords);
2621
+ let index = 0;
2622
+ let i, r;
2623
+
2624
+ // Add data codewords
2625
+ for (i = 0; i < maxDataSize; i++) {
2626
+ for (r = 0; r < ecTotalBlocks; r++) {
2627
+ if (i < dcData[r].length) {
2628
+ data[index++] = dcData[r][i];
2629
+ }
2630
+ }
2631
+ }
2632
+
2633
+ // Apped EC codewords
2634
+ for (i = 0; i < ecCount; i++) {
2635
+ for (r = 0; r < ecTotalBlocks; r++) {
2636
+ data[index++] = ecData[r][i];
2637
+ }
2638
+ }
2639
+
2640
+ return data
2641
+ }
2642
+
2643
+ /**
2644
+ * Build QR Code symbol
2645
+ *
2646
+ * @param {String} data Input string
2647
+ * @param {Number} version QR Code version
2648
+ * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
2649
+ * @param {MaskPattern} maskPattern Mask pattern
2650
+ * @return {Object} Object containing symbol data
2651
+ */
2652
+ function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
2653
+ let segments;
2654
+
2655
+ if (Array.isArray(data)) {
2656
+ segments = Segments.fromArray(data);
2657
+ } else if (typeof data === 'string') {
2658
+ let estimatedVersion = version;
2659
+
2660
+ if (!estimatedVersion) {
2661
+ const rawSegments = Segments.rawSplit(data);
2662
+
2663
+ // Estimate best version that can contain raw splitted segments
2664
+ estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel);
2665
+ }
2666
+
2667
+ // Build optimized segments
2668
+ // If estimated version is undefined, try with the highest version
2669
+ segments = Segments.fromString(data, estimatedVersion || 40);
2670
+ } else {
2671
+ throw new Error('Invalid data')
2672
+ }
2673
+
2674
+ // Get the min version that can contain data
2675
+ const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel);
2676
+
2677
+ // If no version is found, data cannot be stored
2678
+ if (!bestVersion) {
2679
+ throw new Error('The amount of data is too big to be stored in a QR Code')
2680
+ }
2681
+
2682
+ // If not specified, use min version as default
2683
+ if (!version) {
2684
+ version = bestVersion;
2685
+
2686
+ // Check if the specified version can contain the data
2687
+ } else if (version < bestVersion) {
2688
+ throw new Error('\n' +
2689
+ 'The chosen QR Code version cannot contain this amount of data.\n' +
2690
+ 'Minimum version required to store current data is: ' + bestVersion + '.\n'
2691
+ )
2692
+ }
2693
+
2694
+ const dataBits = createData(version, errorCorrectionLevel, segments);
2695
+
2696
+ // Allocate matrix buffer
2697
+ const moduleCount = Utils.getSymbolSize(version);
2698
+ const modules = new BitMatrix(moduleCount);
2699
+
2700
+ // Add function modules
2701
+ setupFinderPattern(modules, version);
2702
+ setupTimingPattern(modules);
2703
+ setupAlignmentPattern(modules, version);
2704
+
2705
+ // Add temporary dummy bits for format info just to set them as reserved.
2706
+ // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
2707
+ // since the masking operation must be performed only on the encoding region.
2708
+ // These blocks will be replaced with correct values later in code.
2709
+ setupFormatInfo(modules, errorCorrectionLevel, 0);
2710
+
2711
+ if (version >= 7) {
2712
+ setupVersionInfo(modules, version);
2713
+ }
2714
+
2715
+ // Add data codewords
2716
+ setupData(modules, dataBits);
2717
+
2718
+ if (isNaN(maskPattern)) {
2719
+ // Find best mask pattern
2720
+ maskPattern = MaskPattern.getBestMask(modules,
2721
+ setupFormatInfo.bind(null, modules, errorCorrectionLevel));
2722
+ }
2723
+
2724
+ // Apply mask pattern
2725
+ MaskPattern.applyMask(maskPattern, modules);
2726
+
2727
+ // Replace format info bits with correct values
2728
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
2729
+
2730
+ return {
2731
+ modules: modules,
2732
+ version: version,
2733
+ errorCorrectionLevel: errorCorrectionLevel,
2734
+ maskPattern: maskPattern,
2735
+ segments: segments
2736
+ }
2737
+ }
2738
+
2739
+ /**
2740
+ * QR Code
2741
+ *
2742
+ * @param {String | Array} data Input data
2743
+ * @param {Object} options Optional configurations
2744
+ * @param {Number} options.version QR Code version
2745
+ * @param {String} options.errorCorrectionLevel Error correction level
2746
+ * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
2747
+ */
2748
+ qrcode.create = function create (data, options) {
2749
+ if (typeof data === 'undefined' || data === '') {
2750
+ throw new Error('No input text')
2751
+ }
2752
+
2753
+ let errorCorrectionLevel = ECLevel.M;
2754
+ let version;
2755
+ let mask;
2756
+
2757
+ if (typeof options !== 'undefined') {
2758
+ // Use higher error correction level as default
2759
+ errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
2760
+ version = Version.from(options.version);
2761
+ mask = MaskPattern.from(options.maskPattern);
2762
+
2763
+ if (options.toSJISFunc) {
2764
+ Utils.setToSJISFunction(options.toSJISFunc);
2765
+ }
2766
+ }
2767
+
2768
+ return createSymbol(data, version, errorCorrectionLevel, mask)
2769
+ };
2770
+ return qrcode;
2771
+ }
2772
+
2773
+ var canvas = {};
2774
+
2775
+ var utils = {};
2776
+
2777
+ var hasRequiredUtils;
2778
+
2779
+ function requireUtils () {
2780
+ if (hasRequiredUtils) return utils;
2781
+ hasRequiredUtils = 1;
2782
+ (function (exports) {
2783
+ function hex2rgba (hex) {
2784
+ if (typeof hex === 'number') {
2785
+ hex = hex.toString();
2786
+ }
2787
+
2788
+ if (typeof hex !== 'string') {
2789
+ throw new Error('Color should be defined as hex string')
2790
+ }
2791
+
2792
+ let hexCode = hex.slice().replace('#', '').split('');
2793
+ if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
2794
+ throw new Error('Invalid hex color: ' + hex)
2795
+ }
2796
+
2797
+ // Convert from short to long form (fff -> ffffff)
2798
+ if (hexCode.length === 3 || hexCode.length === 4) {
2799
+ hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
2800
+ return [c, c]
2801
+ }));
2802
+ }
2803
+
2804
+ // Add default alpha value
2805
+ if (hexCode.length === 6) hexCode.push('F', 'F');
2806
+
2807
+ const hexValue = parseInt(hexCode.join(''), 16);
2808
+
2809
+ return {
2810
+ r: (hexValue >> 24) & 255,
2811
+ g: (hexValue >> 16) & 255,
2812
+ b: (hexValue >> 8) & 255,
2813
+ a: hexValue & 255,
2814
+ hex: '#' + hexCode.slice(0, 6).join('')
2815
+ }
2816
+ }
2817
+
2818
+ exports.getOptions = function getOptions (options) {
2819
+ if (!options) options = {};
2820
+ if (!options.color) options.color = {};
2821
+
2822
+ const margin = typeof options.margin === 'undefined' ||
2823
+ options.margin === null ||
2824
+ options.margin < 0
2825
+ ? 4
2826
+ : options.margin;
2827
+
2828
+ const width = options.width && options.width >= 21 ? options.width : undefined;
2829
+ const scale = options.scale || 4;
2830
+
2831
+ return {
2832
+ width: width,
2833
+ scale: width ? 4 : scale,
2834
+ margin: margin,
2835
+ color: {
2836
+ dark: hex2rgba(options.color.dark || '#000000ff'),
2837
+ light: hex2rgba(options.color.light || '#ffffffff')
2838
+ },
2839
+ type: options.type,
2840
+ rendererOpts: options.rendererOpts || {}
2841
+ }
2842
+ };
2843
+
2844
+ exports.getScale = function getScale (qrSize, opts) {
2845
+ return opts.width && opts.width >= qrSize + opts.margin * 2
2846
+ ? opts.width / (qrSize + opts.margin * 2)
2847
+ : opts.scale
2848
+ };
2849
+
2850
+ exports.getImageWidth = function getImageWidth (qrSize, opts) {
2851
+ const scale = exports.getScale(qrSize, opts);
2852
+ return Math.floor((qrSize + opts.margin * 2) * scale)
2853
+ };
2854
+
2855
+ exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
2856
+ const size = qr.modules.size;
2857
+ const data = qr.modules.data;
2858
+ const scale = exports.getScale(size, opts);
2859
+ const symbolSize = Math.floor((size + opts.margin * 2) * scale);
2860
+ const scaledMargin = opts.margin * scale;
2861
+ const palette = [opts.color.light, opts.color.dark];
2862
+
2863
+ for (let i = 0; i < symbolSize; i++) {
2864
+ for (let j = 0; j < symbolSize; j++) {
2865
+ let posDst = (i * symbolSize + j) * 4;
2866
+ let pxColor = opts.color.light;
2867
+
2868
+ if (i >= scaledMargin && j >= scaledMargin &&
2869
+ i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
2870
+ const iSrc = Math.floor((i - scaledMargin) / scale);
2871
+ const jSrc = Math.floor((j - scaledMargin) / scale);
2872
+ pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
2873
+ }
2874
+
2875
+ imgData[posDst++] = pxColor.r;
2876
+ imgData[posDst++] = pxColor.g;
2877
+ imgData[posDst++] = pxColor.b;
2878
+ imgData[posDst] = pxColor.a;
2879
+ }
2880
+ }
2881
+ };
2882
+ } (utils));
2883
+ return utils;
2884
+ }
2885
+
2886
+ var hasRequiredCanvas;
2887
+
2888
+ function requireCanvas () {
2889
+ if (hasRequiredCanvas) return canvas;
2890
+ hasRequiredCanvas = 1;
2891
+ (function (exports) {
2892
+ const Utils = requireUtils();
2893
+
2894
+ function clearCanvas (ctx, canvas, size) {
2895
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
2896
+
2897
+ if (!canvas.style) canvas.style = {};
2898
+ canvas.height = size;
2899
+ canvas.width = size;
2900
+ canvas.style.height = size + 'px';
2901
+ canvas.style.width = size + 'px';
2902
+ }
2903
+
2904
+ function getCanvasElement () {
2905
+ try {
2906
+ return document.createElement('canvas')
2907
+ } catch (e) {
2908
+ throw new Error('You need to specify a canvas element')
2909
+ }
2910
+ }
2911
+
2912
+ exports.render = function render (qrData, canvas, options) {
2913
+ let opts = options;
2914
+ let canvasEl = canvas;
2915
+
2916
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
2917
+ opts = canvas;
2918
+ canvas = undefined;
2919
+ }
2920
+
2921
+ if (!canvas) {
2922
+ canvasEl = getCanvasElement();
2923
+ }
2924
+
2925
+ opts = Utils.getOptions(opts);
2926
+ const size = Utils.getImageWidth(qrData.modules.size, opts);
2927
+
2928
+ const ctx = canvasEl.getContext('2d');
2929
+ const image = ctx.createImageData(size, size);
2930
+ Utils.qrToImageData(image.data, qrData, opts);
2931
+
2932
+ clearCanvas(ctx, canvasEl, size);
2933
+ ctx.putImageData(image, 0, 0);
2934
+
2935
+ return canvasEl
2936
+ };
2937
+
2938
+ exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
2939
+ let opts = options;
2940
+
2941
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
2942
+ opts = canvas;
2943
+ canvas = undefined;
2944
+ }
2945
+
2946
+ if (!opts) opts = {};
2947
+
2948
+ const canvasEl = exports.render(qrData, canvas, opts);
2949
+
2950
+ const type = opts.type || 'image/png';
2951
+ const rendererOpts = opts.rendererOpts || {};
2952
+
2953
+ return canvasEl.toDataURL(type, rendererOpts.quality)
2954
+ };
2955
+ } (canvas));
2956
+ return canvas;
2957
+ }
2958
+
2959
+ var svgTag = {};
2960
+
2961
+ var hasRequiredSvgTag;
2962
+
2963
+ function requireSvgTag () {
2964
+ if (hasRequiredSvgTag) return svgTag;
2965
+ hasRequiredSvgTag = 1;
2966
+ const Utils = requireUtils();
2967
+
2968
+ function getColorAttrib (color, attrib) {
2969
+ const alpha = color.a / 255;
2970
+ const str = attrib + '="' + color.hex + '"';
2971
+
2972
+ return alpha < 1
2973
+ ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
2974
+ : str
2975
+ }
2976
+
2977
+ function svgCmd (cmd, x, y) {
2978
+ let str = cmd + x;
2979
+ if (typeof y !== 'undefined') str += ' ' + y;
2980
+
2981
+ return str
2982
+ }
2983
+
2984
+ function qrToPath (data, size, margin) {
2985
+ let path = '';
2986
+ let moveBy = 0;
2987
+ let newRow = false;
2988
+ let lineLength = 0;
2989
+
2990
+ for (let i = 0; i < data.length; i++) {
2991
+ const col = Math.floor(i % size);
2992
+ const row = Math.floor(i / size);
2993
+
2994
+ if (!col && !newRow) newRow = true;
2995
+
2996
+ if (data[i]) {
2997
+ lineLength++;
2998
+
2999
+ if (!(i > 0 && col > 0 && data[i - 1])) {
3000
+ path += newRow
3001
+ ? svgCmd('M', col + margin, 0.5 + row + margin)
3002
+ : svgCmd('m', moveBy, 0);
3003
+
3004
+ moveBy = 0;
3005
+ newRow = false;
3006
+ }
3007
+
3008
+ if (!(col + 1 < size && data[i + 1])) {
3009
+ path += svgCmd('h', lineLength);
3010
+ lineLength = 0;
3011
+ }
3012
+ } else {
3013
+ moveBy++;
3014
+ }
3015
+ }
3016
+
3017
+ return path
3018
+ }
3019
+
3020
+ svgTag.render = function render (qrData, options, cb) {
3021
+ const opts = Utils.getOptions(options);
3022
+ const size = qrData.modules.size;
3023
+ const data = qrData.modules.data;
3024
+ const qrcodesize = size + opts.margin * 2;
3025
+
3026
+ const bg = !opts.color.light.a
3027
+ ? ''
3028
+ : '<path ' + getColorAttrib(opts.color.light, 'fill') +
3029
+ ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>';
3030
+
3031
+ const path =
3032
+ '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
3033
+ ' d="' + qrToPath(data, size, opts.margin) + '"/>';
3034
+
3035
+ const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"';
3036
+
3037
+ const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ';
3038
+
3039
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n';
3040
+
3041
+ if (typeof cb === 'function') {
3042
+ cb(null, svgTag);
3043
+ }
3044
+
3045
+ return svgTag
3046
+ };
3047
+ return svgTag;
3048
+ }
3049
+
3050
+ var hasRequiredBrowser;
3051
+
3052
+ function requireBrowser () {
3053
+ if (hasRequiredBrowser) return browser;
3054
+ hasRequiredBrowser = 1;
3055
+ const canPromise = requireCanPromise();
3056
+
3057
+ const QRCode = requireQrcode();
3058
+ const CanvasRenderer = requireCanvas();
3059
+ const SvgRenderer = requireSvgTag();
3060
+
3061
+ function renderCanvas (renderFunc, canvas, text, opts, cb) {
3062
+ const args = [].slice.call(arguments, 1);
3063
+ const argsNum = args.length;
3064
+ const isLastArgCb = typeof args[argsNum - 1] === 'function';
3065
+
3066
+ if (!isLastArgCb && !canPromise()) {
3067
+ throw new Error('Callback required as last argument')
3068
+ }
3069
+
3070
+ if (isLastArgCb) {
3071
+ if (argsNum < 2) {
3072
+ throw new Error('Too few arguments provided')
3073
+ }
3074
+
3075
+ if (argsNum === 2) {
3076
+ cb = text;
3077
+ text = canvas;
3078
+ canvas = opts = undefined;
3079
+ } else if (argsNum === 3) {
3080
+ if (canvas.getContext && typeof cb === 'undefined') {
3081
+ cb = opts;
3082
+ opts = undefined;
3083
+ } else {
3084
+ cb = opts;
3085
+ opts = text;
3086
+ text = canvas;
3087
+ canvas = undefined;
3088
+ }
3089
+ }
3090
+ } else {
3091
+ if (argsNum < 1) {
3092
+ throw new Error('Too few arguments provided')
3093
+ }
3094
+
3095
+ if (argsNum === 1) {
3096
+ text = canvas;
3097
+ canvas = opts = undefined;
3098
+ } else if (argsNum === 2 && !canvas.getContext) {
3099
+ opts = text;
3100
+ text = canvas;
3101
+ canvas = undefined;
3102
+ }
3103
+
3104
+ return new Promise(function (resolve, reject) {
3105
+ try {
3106
+ const data = QRCode.create(text, opts);
3107
+ resolve(renderFunc(data, canvas, opts));
3108
+ } catch (e) {
3109
+ reject(e);
3110
+ }
3111
+ })
3112
+ }
3113
+
3114
+ try {
3115
+ const data = QRCode.create(text, opts);
3116
+ cb(null, renderFunc(data, canvas, opts));
3117
+ } catch (e) {
3118
+ cb(e);
3119
+ }
3120
+ }
3121
+
3122
+ browser.create = QRCode.create;
3123
+ browser.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
3124
+ browser.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
3125
+
3126
+ // only svg for now.
3127
+ browser.toString = renderCanvas.bind(null, function (data, _, opts) {
3128
+ return SvgRenderer.render(data, opts)
3129
+ });
3130
+ return browser;
3131
+ }
3132
+
3133
+ var browserExports = requireBrowser();
3134
+ var QRCode = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
3135
+
3136
+ const tlTicketCss = () => `:host{display:block;font-family:var(--tl-font-family, system-ui, sans-serif)}.ticket{border:1px solid var(--tl-border, #e5e7eb);border-radius:var(--tl-radius-lg, 0.75rem);background:var(--tl-card, #ffffff);padding:var(--tl-spacing-5, 1.25rem);text-align:center}.qr-wrap{position:relative;width:160px;height:160px;margin:0 auto}.qr{width:160px;height:160px}.qr svg{width:100%;height:100%;display:block}.qr.inactive{opacity:0.3}.stamp{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);padding:0.25rem 0.5rem;border-radius:var(--tl-radius-sm, 0.25rem);background:rgba(17, 24, 39, 0.85);color:#ffffff;font-size:0.7rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em}.name{margin:1rem 0 0;font-weight:600;color:var(--tl-foreground, #111827)}.meta{margin:0.125rem 0 0;font-size:0.875rem;color:var(--tl-muted-foreground, #6b7280)}.barcode{margin:0.25rem 0 0;font-family:ui-monospace, monospace;font-size:0.625rem;color:var(--tl-muted-foreground, #9ca3af);word-break:break-all}.download{margin-top:0.75rem;padding:0.375rem 0.75rem;border:1px solid var(--tl-border, #e5e7eb);border-radius:var(--tl-radius-md, 0.5rem);background:transparent;color:var(--tl-foreground, #111827);font-size:0.875rem;font-weight:500;cursor:pointer}.download:hover{background:var(--tl-muted, #f3f4f6)}.download:disabled{opacity:0.5;cursor:default}`;
3137
+
3138
+ const TlTicket = class {
3139
+ constructor(hostRef) {
3140
+ index.registerInstance(this, hostRef);
3141
+ this.qrSvg = '';
3142
+ this.downloading = false;
3143
+ }
3144
+ async generateQr() {
3145
+ if (this.ticket?.barcode) {
3146
+ this.qrSvg = await QRCode.toString(this.ticket.barcode, {
3147
+ type: 'svg',
3148
+ margin: 0,
3149
+ errorCorrectionLevel: 'M',
3150
+ });
3151
+ }
3152
+ }
3153
+ async componentWillLoad() {
3154
+ await this.generateQr();
3155
+ }
3156
+ async download() {
3157
+ try {
3158
+ this.downloading = true;
3159
+ const sdk = await sdkConnector.whenSDK();
3160
+ const orders = sdk.getOrdersManager?.();
3161
+ if (!orders)
3162
+ throw new Error('Ticket downloads are not available');
3163
+ const blob = await orders.ticketPdf(this.orderId, this.ticket.id);
3164
+ const url = URL.createObjectURL(blob);
3165
+ const a = document.createElement('a');
3166
+ a.href = url;
3167
+ a.download = `ticket-${this.ticket.id}.pdf`;
3168
+ document.body.appendChild(a);
3169
+ a.click();
3170
+ a.remove();
3171
+ URL.revokeObjectURL(url);
3172
+ }
3173
+ catch (err) {
3174
+ console.error('[tl-ticket] download failed', err);
3175
+ }
3176
+ finally {
3177
+ this.downloading = false;
3178
+ }
3179
+ }
3180
+ render() {
3181
+ const t = this.ticket;
3182
+ if (!t)
3183
+ return null;
3184
+ const used = t.admissionStatus === 'fully_redeemed';
3185
+ const voided = ['cancelled', 'expired'].includes(t.status);
3186
+ const inactive = used || voided;
3187
+ return (index.h("div", { class: "ticket" }, index.h("div", { class: "qr-wrap" }, index.h("div", { class: { qr: true, inactive }, innerHTML: this.qrSvg }), inactive && index.h("span", { class: "stamp" }, used ? 'Used' : 'Void')), index.h("p", { class: "name" }, t.name), t.seatLabel && index.h("p", { class: "meta" }, "Seat ", t.seatLabel), t.holderName && index.h("p", { class: "meta" }, t.holderName), index.h("p", { class: "barcode" }, t.barcode), index.h("button", { class: "download", disabled: this.downloading, onClick: () => this.download() }, this.downloading ? 'Preparing…' : 'Download PDF')));
3188
+ }
3189
+ static get watchers() { return {
3190
+ "ticket": [{
3191
+ "generateQr": 0
3192
+ }]
3193
+ }; }
3194
+ };
3195
+ TlTicket.style = tlTicketCss();
3196
+
3197
+ exports.tl_order_tickets = TlOrderTickets;
3198
+ exports.tl_ticket = TlTicket;