@segment/analytics-browser-actions-cj 1.1.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 (89) hide show
  1. package/dist/cjs/generated-types.d.ts +4 -0
  2. package/dist/cjs/generated-types.js +3 -0
  3. package/dist/cjs/generated-types.js.map +1 -0
  4. package/dist/cjs/index.d.ts +11 -0
  5. package/dist/cjs/index.js +38 -0
  6. package/dist/cjs/index.js.map +1 -0
  7. package/dist/cjs/order/generated-types.d.ts +141 -0
  8. package/dist/cjs/order/generated-types.js +3 -0
  9. package/dist/cjs/order/generated-types.js.map +1 -0
  10. package/dist/cjs/order/hashing-utils.d.ts +15 -0
  11. package/dist/cjs/order/hashing-utils.js +96 -0
  12. package/dist/cjs/order/hashing-utils.js.map +1 -0
  13. package/dist/cjs/order/index.d.ts +6 -0
  14. package/dist/cjs/order/index.js +58 -0
  15. package/dist/cjs/order/index.js.map +1 -0
  16. package/dist/cjs/order/order-fields.d.ts +6 -0
  17. package/dist/cjs/order/order-fields.js +1091 -0
  18. package/dist/cjs/order/order-fields.js.map +1 -0
  19. package/dist/cjs/order/utils.d.ts +3 -0
  20. package/dist/cjs/order/utils.js +19 -0
  21. package/dist/cjs/order/utils.js.map +1 -0
  22. package/dist/cjs/sitePage/generated-types.d.ts +13 -0
  23. package/dist/cjs/sitePage/generated-types.js +3 -0
  24. package/dist/cjs/sitePage/generated-types.js.map +1 -0
  25. package/dist/cjs/sitePage/index.d.ts +6 -0
  26. package/dist/cjs/sitePage/index.js +125 -0
  27. package/dist/cjs/sitePage/index.js.map +1 -0
  28. package/dist/cjs/sitePage/utils.d.ts +2 -0
  29. package/dist/cjs/sitePage/utils.js +7 -0
  30. package/dist/cjs/sitePage/utils.js.map +1 -0
  31. package/dist/cjs/types.d.ts +34 -0
  32. package/dist/cjs/types.js +3 -0
  33. package/dist/cjs/types.js.map +1 -0
  34. package/dist/cjs/utils.d.ts +1 -0
  35. package/dist/cjs/utils.js +23 -0
  36. package/dist/cjs/utils.js.map +1 -0
  37. package/dist/esm/generated-types.d.ts +4 -0
  38. package/dist/esm/generated-types.js +2 -0
  39. package/dist/esm/generated-types.js.map +1 -0
  40. package/dist/esm/index.d.ts +11 -0
  41. package/dist/esm/index.js +34 -0
  42. package/dist/esm/index.js.map +1 -0
  43. package/dist/esm/order/generated-types.d.ts +141 -0
  44. package/dist/esm/order/generated-types.js +2 -0
  45. package/dist/esm/order/generated-types.js.map +1 -0
  46. package/dist/esm/order/hashing-utils.d.ts +15 -0
  47. package/dist/esm/order/hashing-utils.js +88 -0
  48. package/dist/esm/order/hashing-utils.js.map +1 -0
  49. package/dist/esm/order/index.d.ts +6 -0
  50. package/dist/esm/order/index.js +56 -0
  51. package/dist/esm/order/index.js.map +1 -0
  52. package/dist/esm/order/order-fields.d.ts +6 -0
  53. package/dist/esm/order/order-fields.js +1088 -0
  54. package/dist/esm/order/order-fields.js.map +1 -0
  55. package/dist/esm/order/utils.d.ts +3 -0
  56. package/dist/esm/order/utils.js +15 -0
  57. package/dist/esm/order/utils.js.map +1 -0
  58. package/dist/esm/sitePage/generated-types.d.ts +13 -0
  59. package/dist/esm/sitePage/generated-types.js +2 -0
  60. package/dist/esm/sitePage/generated-types.js.map +1 -0
  61. package/dist/esm/sitePage/index.d.ts +6 -0
  62. package/dist/esm/sitePage/index.js +123 -0
  63. package/dist/esm/sitePage/index.js.map +1 -0
  64. package/dist/esm/sitePage/utils.d.ts +2 -0
  65. package/dist/esm/sitePage/utils.js +4 -0
  66. package/dist/esm/sitePage/utils.js.map +1 -0
  67. package/dist/esm/types.d.ts +34 -0
  68. package/dist/esm/types.js +2 -0
  69. package/dist/esm/types.js.map +1 -0
  70. package/dist/esm/utils.d.ts +1 -0
  71. package/dist/esm/utils.js +20 -0
  72. package/dist/esm/utils.js.map +1 -0
  73. package/dist/tsconfig.tsbuildinfo +1 -0
  74. package/package.json +25 -0
  75. package/src/generated-types.ts +12 -0
  76. package/src/index.ts +46 -0
  77. package/src/order/__tests__/index.test.ts +985 -0
  78. package/src/order/generated-types.ts +545 -0
  79. package/src/order/hashing-utils.ts +141 -0
  80. package/src/order/index.ts +90 -0
  81. package/src/order/order-fields.ts +1117 -0
  82. package/src/order/utils.ts +19 -0
  83. package/src/sitePage/__tests__/index.test.ts +124 -0
  84. package/src/sitePage/generated-types.ts +45 -0
  85. package/src/sitePage/index.ts +128 -0
  86. package/src/sitePage/utils.ts +5 -0
  87. package/src/types.ts +38 -0
  88. package/src/utils.ts +21 -0
  89. package/tsconfig.json +9 -0
@@ -0,0 +1,545 @@
1
+ // Generated file. DO NOT MODIFY IT BY HAND.
2
+
3
+ export interface Payload {
4
+ /**
5
+ * Send additional data relating to travel, finance network services
6
+ */
7
+ verticalType?: string
8
+ /**
9
+ * A unique ID assigned by you to the user.
10
+ */
11
+ userId?: string
12
+ /**
13
+ * Your CJ Enterprise ID.
14
+ */
15
+ enterpriseId: number
16
+ /**
17
+ * Page type to be sent to CJ. Must be set to "conversionConfirmation" for order events.
18
+ */
19
+ pageType: string
20
+ /**
21
+ * Segment will ensure the email address is hashed before sending to CJ.
22
+ */
23
+ emailHash?: string
24
+ /**
25
+ * The orderId is a unique identifier, such as an order identifier or invoice number, which must be populated for each order.
26
+ */
27
+ orderId: string
28
+ /**
29
+ * Required if not specified in Settings. This is a static value provided by CJ. Each account may have multiple actions and each will be referenced by a different actionTrackerId value.
30
+ */
31
+ actionTrackerId?: string
32
+ /**
33
+ * The currency of the order, e.g. USD, EUR.
34
+ */
35
+ currency: string
36
+ /**
37
+ * The total amount of the order. This should exclude shipping or tax.
38
+ */
39
+ amount: number
40
+ /**
41
+ * The total discount applied to the order.
42
+ */
43
+ discount?: number
44
+ /**
45
+ * The coupon code applied to the order.
46
+ */
47
+ coupon?: string
48
+ /**
49
+ * The name of the cookie that stores the CJ Event ID. This is required whenever the advertiser uses their own cookie to store the Event ID.
50
+ */
51
+ cjeventOrderCookieName: string
52
+ /**
53
+ * The items to be sent to CJ.
54
+ */
55
+ items?: {
56
+ /**
57
+ * the price of the item before tax and discount.
58
+ */
59
+ unitPrice: number
60
+ /**
61
+ * The item sku.
62
+ */
63
+ itemId: string
64
+ /**
65
+ * The quantity of the item.
66
+ */
67
+ quantity: number
68
+ /**
69
+ * The discount applied to the item.
70
+ */
71
+ discount?: number
72
+ }[]
73
+ /**
74
+ * This field is used to pass additional parameters specific to the vertical. All vertical parameters listed below can be utilized regardless of the account's vertical.
75
+ */
76
+ allVerticals?: {
77
+ /**
78
+ * Ancillary spend at the time of transaction, but not commissionable.
79
+ */
80
+ ancillarySpend?: number
81
+ /**
82
+ * Brand of items purchased. If there are multiple items with different brands, one brand must be designated for the order.
83
+ */
84
+ brand?: string
85
+ /**
86
+ * Identifier of brand of items purchased. If there are multiple items with different brands, one brand must be designated for the order.
87
+ */
88
+ brandId?: string
89
+ /**
90
+ * Identifies the business unit the customer purchased through. If there are multiple items with different business units, one business unit must be designated for the order.
91
+ */
92
+ businessUnit?: string
93
+ /**
94
+ * Marketing campaign id.
95
+ */
96
+ campaignId?: string
97
+ /**
98
+ * Marketing campaign name.
99
+ */
100
+ campaignName?: string
101
+ /**
102
+ * Category of items purchased. If there are multiple items with different categories, one category must be designated for the order.
103
+ */
104
+ category?: string
105
+ /**
106
+ * Class of item.
107
+ */
108
+ class?: string
109
+ /**
110
+ * Confirmation Number
111
+ */
112
+ confirmationNumber?: number
113
+ /**
114
+ * The value (amount of discount) of the coupon. This should be the number linked to the "coupon_type" parameter
115
+ */
116
+ couponDiscount?: number
117
+ /**
118
+ * The type of coupon used in the order. This should be the number linked to the "coupon_discount" parameter.
119
+ */
120
+ couponType?: string
121
+ /**
122
+ * The customer's country. ISO 3166-1 alpha 2 country code, eg. US, UK, AU, FR.
123
+ */
124
+ customerCountry?: string
125
+ /**
126
+ * Advertiser-specific customer segment definition.
127
+ */
128
+ customerSegment?: string
129
+ /**
130
+ * The status of the customer, e.g. new, returning.
131
+ */
132
+ customerStatus?: string
133
+ /**
134
+ * Indicates the type of individual making the purchase as someone representing a group.
135
+ */
136
+ customerType?: string
137
+ /**
138
+ * The delivery method used for the order.
139
+ */
140
+ delivery?: string
141
+ /**
142
+ * Description of the product.
143
+ */
144
+ description?: string
145
+ /**
146
+ * Duration in days.
147
+ */
148
+ duration?: number
149
+ /**
150
+ * End date and time of the order, in ISO 8601 format.
151
+ */
152
+ endDateTime?: string
153
+ /**
154
+ * Product genre. If there are multiple items with different genres, one genre must be designated for the order.
155
+ */
156
+ genre?: string
157
+ /**
158
+ * Id for the item. (Simple Actions Only).
159
+ */
160
+ itemId?: string
161
+ /**
162
+ * Advertiser assigned item name.
163
+ */
164
+ itemName?: string
165
+ /**
166
+ * Advertiser assigned item type.
167
+ */
168
+ itemType?: string
169
+ /**
170
+ * Advertiser assigned general demographic.
171
+ */
172
+ lifestage?: string
173
+ /**
174
+ * Identifies the customer location if different from customerCountry.
175
+ */
176
+ location?: string
177
+ /**
178
+ * Loyalty points earned on the transaction.
179
+ */
180
+ loyaltyEarned?: number
181
+ /**
182
+ * Indicates whether this order coincided with the consumer joining the loyalty program.
183
+ */
184
+ loyaltyFirstTimeSignup?: string
185
+ /**
186
+ * Indicates the level of the customer's loyalty status.
187
+ */
188
+ loyaltyLevel?: string
189
+ /**
190
+ * Loyalty points used during the transaction.
191
+ */
192
+ loyaltyRedeemed?: number
193
+ /**
194
+ * Indicates if the customer is a loyalty member.
195
+ */
196
+ loyaltyStatus?: string
197
+ /**
198
+ * Margin on total order. Can be a dollar value or a custom indicator.
199
+ */
200
+ margin?: string
201
+ /**
202
+ * Advertiser-defined marketing channel assigned to this transaction.
203
+ */
204
+ marketingChannel?: string
205
+ /**
206
+ * Indicates if the purchase has a no cancellation policy. "Yes" means there is a "no cancellation" policy, "no" means there is no policy.
207
+ */
208
+ noCancellation?: string
209
+ /**
210
+ * Subtotal for order.
211
+ */
212
+ orderSubtotal?: number
213
+ /**
214
+ * Method of payment.
215
+ */
216
+ paymentMethod?: string
217
+ /**
218
+ * Model of payment used; advertiser-specific.
219
+ */
220
+ paymentModel?: string
221
+ /**
222
+ * Device platform customer is using.
223
+ */
224
+ platformId?: string
225
+ /**
226
+ * Point of sale for the transaction.
227
+ */
228
+ pointOfSale?: string
229
+ /**
230
+ * Indicates if the purchase was made prior to the item becoming available.
231
+ */
232
+ preorder?: string
233
+ /**
234
+ * Indicates if the payment was made in advance of the item's consumption.
235
+ */
236
+ prepaid?: string
237
+ /**
238
+ * Promotion applied. If multiple, must be comma-separated.
239
+ */
240
+ promotion?: string
241
+ /**
242
+ * The numeric value associated with the promotion.
243
+ */
244
+ promotionAmount?: number
245
+ /**
246
+ * Threshold needed to qualify for the promotion.
247
+ */
248
+ promotionConditionThreshold?: number
249
+ /**
250
+ * Type of conditions applied to the promotion.
251
+ */
252
+ promotionConditionType?: string
253
+ /**
254
+ * End date of the promotion, in ISO 8601 format.
255
+ */
256
+ promotionEnds?: string
257
+ /**
258
+ * Start date of the promotion, in ISO 8601 format.
259
+ */
260
+ promotionStarts?: string
261
+ /**
262
+ * Category of promotion.
263
+ */
264
+ promotionType?: string
265
+ /**
266
+ * Quantity for a given SKU. (Simple Actions Only).
267
+ */
268
+ quantity?: number
269
+ /**
270
+ * Rating of the product.
271
+ */
272
+ rating?: string
273
+ /**
274
+ * Classification of service offered.
275
+ */
276
+ serviceType?: string
277
+ /**
278
+ * Start of item duration (e.g., check-out or departure date/time). Must be in ISO 8601 format.
279
+ */
280
+ startDateTime?: string
281
+ /**
282
+ * Cost of subscription fee featured when signing up for free trial.
283
+ */
284
+ subscriptionFee?: number
285
+ /**
286
+ * Product duration.
287
+ */
288
+ subscriptionLength?: string
289
+ /**
290
+ * Total tax for the order.
291
+ */
292
+ taxAmount?: number
293
+ /**
294
+ * Type of tax assessed.
295
+ */
296
+ taxType?: string
297
+ /**
298
+ * Indicates if someone converted from a trial to a subscription.
299
+ */
300
+ upsell?: string
301
+ }
302
+ /**
303
+ * This field is used to pass additional parameters specific to the travel vertical.
304
+ */
305
+ travelVerticals?: {
306
+ /**
307
+ * Date the booking was made.
308
+ */
309
+ bookingDate?: string
310
+ /**
311
+ * Booking status at the time of tag firing.
312
+ */
313
+ bookingStatus?: string
314
+ /**
315
+ * Value of booking after taxes.
316
+ */
317
+ bookingValuePostTax?: number
318
+ /**
319
+ * Value of booking before taxes.
320
+ */
321
+ bookingValuePreTax?: number
322
+ /**
323
+ * Other items added to the reservation beyond the vehicle itself (e.g. "insurance", "GPS", "Car Seat").
324
+ */
325
+ carOptions?: string
326
+ /**
327
+ * Class of item (flight, hotel, car, or cruise specific classes).
328
+ */
329
+ class?: string
330
+ /**
331
+ * Type of cruise (Alaskan, Caribbean, etc...).
332
+ */
333
+ cruiseType?: string
334
+ /**
335
+ * Customer service destination city name (New York City, Boston, Atlanta, etc...). If destinationCity is provided, destinationState must also be provided. If there is no Origin/Destination combo, but needs to indicate a location of service (network service, event) use 'destination' set of parameters.
336
+ */
337
+ destinationCity?: string
338
+ /**
339
+ * Customer service destination country code, per ISO 3166-1 alpha 3 country code (USA, GBR, SWE, etc...).
340
+ */
341
+ destinationCountry?: string
342
+ /**
343
+ * Customer service destination state/province code. ISO 3166-2 country subdivision standards. e.g. US-NY, US-CA, US-FL, US-TX
344
+ */
345
+ destinationState?: string
346
+ /**
347
+ * Indicates whether the travel is domestic (Yes) or international (No).
348
+ */
349
+ domestic?: string
350
+ /**
351
+ * Destination location IATA code. 3 letter IATA code.
352
+ */
353
+ dropoffIata?: string
354
+ /**
355
+ * Advertiser ID for destination location.
356
+ */
357
+ dropoffId?: string
358
+ /**
359
+ * Type of flight fare (e.g. gotta get away).
360
+ */
361
+ flightFareType?: string
362
+ /**
363
+ * Other items added to the reservation (e.g. Wi-Fi).
364
+ */
365
+ flightOptions?: string
366
+ /**
367
+ * Type of flight (e.g. direct, layover, overnight).
368
+ */
369
+ flightType?: string
370
+ /**
371
+ * Flyer miles earned from this flight.
372
+ */
373
+ flyerMiles?: number
374
+ /**
375
+ * Number of guests.
376
+ */
377
+ guests?: number
378
+ /**
379
+ * IATA code (3-letter); If using for a multi-stop flight each city in a flight can be provided in a comma-separated list.
380
+ */
381
+ iata?: string
382
+ /**
383
+ * Booking itinerary ID.
384
+ */
385
+ itineraryId?: string
386
+ /**
387
+ * Minimum stay duration required in days.
388
+ */
389
+ minimumStayDuration?: number
390
+ /**
391
+ * Customer service origin city name (New York City, Ottawa, Los Angeles, etc...). If originCity is provided, originState is also provided
392
+ */
393
+ originCity?: string
394
+ /**
395
+ * Customer service origin country code per ISO 3166-1 alpha 3 country code (USA, GBR, SWE, etc...).
396
+ */
397
+ originCountry?: string
398
+ /**
399
+ * Customer service origin state/province code per ISO 3166-2 country subdivision standards (Alaska would be "or_state=US-AK", Bangkok would be "or_state=TH-10").
400
+ */
401
+ originState?: string
402
+ /**
403
+ * Amount paid at booking after taxes.
404
+ */
405
+ paidAtBookingPostTax?: number
406
+ /**
407
+ * Amount paid at booking before taxes.
408
+ */
409
+ paidAtBookingPreTax?: number
410
+ /**
411
+ * Origin location IATA code.
412
+ */
413
+ pickupIata?: string
414
+ /**
415
+ * Advertiser ID for origin location.
416
+ */
417
+ pickupId?: string
418
+ /**
419
+ * Departure port city (for cruises).
420
+ */
421
+ port?: string
422
+ /**
423
+ * Room type booked. If using the same values listed for "class" parameter, use that parameter instead.
424
+ */
425
+ roomType?: string
426
+ /**
427
+ * Number of rooms booked.
428
+ */
429
+ rooms?: number
430
+ /**
431
+ * Name of the cruise ship.
432
+ */
433
+ shipName?: string
434
+ /**
435
+ * Type of travel being booked. If you want access to standardized benchmark reporting, you must pass a value from the following list.
436
+ */
437
+ travelType?: string
438
+ }
439
+ /**
440
+ * This field is used to pass additional parameters specific to the finance vertical.
441
+ */
442
+ financeVerticals?: {
443
+ /**
444
+ * Amount of the annual fee.
445
+ */
446
+ annualFee?: number
447
+ /**
448
+ * Identifies the status of the application at the time the transaction is sent to CJ.
449
+ */
450
+ applicationStatus?: string
451
+ /**
452
+ * APR at time of application approval.
453
+ */
454
+ apr?: number
455
+ /**
456
+ * APR for transfers.
457
+ */
458
+ aprTransfer?: number
459
+ /**
460
+ * If transfer APR is only for a certain period of time, pass the number of months here.
461
+ */
462
+ aprTransferTime?: number
463
+ /**
464
+ * Category of the card.
465
+ */
466
+ cardCategory?: string
467
+ /**
468
+ * Amount of the fee associated with the cash advance.
469
+ */
470
+ cashAdvanceFee?: number
471
+ /**
472
+ * Contract length, in months.
473
+ */
474
+ contractLength?: number
475
+ /**
476
+ * Advertiser-specific contract description.
477
+ */
478
+ contractType?: string
479
+ /**
480
+ * Indicates if the customer received a credit report and if it was purchased.
481
+ */
482
+ creditReport?: string
483
+ /**
484
+ * Amount of credit extended through product.
485
+ */
486
+ creditLine?: number
487
+ /**
488
+ * Minimum credit tier required for product approval. (300-579=Very Poor, 580-669=Fair, 670-739=Good,740-799=Very Good, 800-850=Exceptional).
489
+ */
490
+ creditQuality?: string
491
+ /**
492
+ * Indicates the amount of funding added to the account at the time of transaction.
493
+ */
494
+ fundedAmount?: number
495
+ /**
496
+ * Currency of the funding provided for the new account.
497
+ */
498
+ fundedCurrency?: number
499
+ /**
500
+ * The introductory APR amount. (If the intro APR is not different than overall APR, use the "APR" parameter).
501
+ */
502
+ introductoryApr?: number
503
+ /**
504
+ * The number of months the intro APR applies for.
505
+ */
506
+ introductoryAprTime?: number
507
+ /**
508
+ * Value of the minimum cash balance requirement for the account.
509
+ */
510
+ minimumBalance?: number
511
+ /**
512
+ * Indicates the value if a minimum deposit is required.
513
+ */
514
+ minimumDeposit?: number
515
+ /**
516
+ * Indicates if the applicant was pre-qualified for the card.
517
+ */
518
+ prequalify?: string
519
+ /**
520
+ * The transfer fee amount (i.e. for a credit card).
521
+ */
522
+ transferFee?: number
523
+ }
524
+ /**
525
+ * This field is used to pass additional parameters specific to the network services vertical.
526
+ */
527
+ networkServicesVerticals?: {
528
+ /**
529
+ * Amount of the annual fee.
530
+ */
531
+ annualFee?: number
532
+ /**
533
+ * Identifies the status of the application at the time the transaction is sent to CJ.
534
+ */
535
+ applicationStatus?: string
536
+ /**
537
+ * Contract length, in months.
538
+ */
539
+ contractLength?: number
540
+ /**
541
+ * Advertiser-specific contract description.
542
+ */
543
+ contractType?: string
544
+ }
545
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Utility module for hashing values using various encryption methods and digest types.
3
+ * It includes functionality to check if a value is already hashed and to process hashing with optional cleaning.
4
+ */
5
+ import btoa from 'btoa-lite'
6
+
7
+ export type EncryptionMethod = 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'
8
+ export const hashConfigs: {
9
+ [key in EncryptionMethod]: { lengthHex: number; lengthBase64: number }
10
+ } = {
11
+ sha1: { lengthHex: 40, lengthBase64: 28 },
12
+ sha224: { lengthHex: 56, lengthBase64: 40 },
13
+ sha256: { lengthHex: 64, lengthBase64: 44 },
14
+ sha384: { lengthHex: 96, lengthBase64: 64 },
15
+ sha512: { lengthHex: 128, lengthBase64: 88 }
16
+ }
17
+
18
+ export const DigestTypes = ['hex', 'base64'] as const
19
+ export type DigestType = typeof DigestTypes[number]
20
+
21
+ type CleaningFunction = (value: string) => string
22
+
23
+ class SmartHashing {
24
+ private preHashed: boolean
25
+
26
+ /**
27
+ * Creates an instance of SmartHashing.
28
+ * @param encryptionMethod - The method of encryption to be used.
29
+ * @param digest - The type of digest to be used.
30
+ */
31
+ constructor(public encryptionMethod: EncryptionMethod = 'sha256', public digest: DigestType = 'hex') {
32
+ this.preHashed = false
33
+ }
34
+
35
+ isAlreadyHashed(value: string): boolean {
36
+ const config = hashConfigs[this.encryptionMethod]
37
+ if (!config) throw new Error(`Unsupported encryption method: ${this.encryptionMethod}`)
38
+
39
+ let regex: RegExp
40
+ switch (this.digest) {
41
+ case 'hex':
42
+ regex = new RegExp(`^[a-f0-9]{${config.lengthHex}}$`, 'i')
43
+ this.preHashed = value.length === config.lengthHex && regex.test(value)
44
+ break
45
+ case 'base64':
46
+ regex = new RegExp(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`)
47
+ this.preHashed = value.length === config.lengthBase64 && regex.test(value)
48
+ break
49
+ default:
50
+ throw new Error(`Unsupported digest type: ${this.digest}`)
51
+ }
52
+
53
+ return this.preHashed
54
+ }
55
+
56
+ async hash(value: string): Promise<string> {
57
+ if (value.trim() === '') {
58
+ throw new Error('Cannot hash an empty string')
59
+ }
60
+
61
+ if (this.preHashed) {
62
+ return value
63
+ }
64
+
65
+ const hash = await createHash(value, this.encryptionMethod, this.digest)
66
+
67
+ return hash
68
+ }
69
+ }
70
+
71
+ export async function createHash(
72
+ value: string,
73
+ encryptionMethod: EncryptionMethod = 'sha256',
74
+ digest: DigestType = 'hex'
75
+ ): Promise<string> {
76
+ const algo = encryptionMethod.toUpperCase().replace(/^SHA(\d+)$/, 'SHA-$1')
77
+ const encoded = new TextEncoder().encode(value);
78
+ const hashBuffer = await window.crypto.subtle.digest(algo, encoded)
79
+ const hashArray = new Uint8Array(hashBuffer)
80
+
81
+ return digest === 'hex' ? toHex(hashArray) : toBase64(hashArray)
82
+ }
83
+
84
+ function toHex(bytes: Uint8Array): string {
85
+ return Array.from(bytes)
86
+ .map(b => b.toString(16).padStart(2, '0'))
87
+ .join('')
88
+ }
89
+
90
+ function toBase64(bytes: Uint8Array): string {
91
+ const binary = String.fromCharCode(...bytes)
92
+ return btoa(binary)
93
+ }
94
+
95
+ /**
96
+ * Processes the hashing of a given value based on the provided encryption method, digest type, features, and optional cleaning function.
97
+ *
98
+ * @param value - The string value to be hashed.
99
+ * @param encryptionMethod - The method of encryption to be used.
100
+ * @param digest - The type of digest to be used.
101
+ * @param cleaningFunction - An optional function to clean the value before hashing.
102
+ * @returns The hashed value or the original value if it is already hashed.
103
+ */
104
+
105
+ export async function processHashing(
106
+ value: string,
107
+ encryptionMethod: EncryptionMethod,
108
+ digest: DigestType,
109
+ cleaningFunction?: CleaningFunction
110
+ ): Promise<string> {
111
+ if (value.trim() === '') {
112
+ return ''
113
+ }
114
+
115
+ const smartHashing = new SmartHashing(encryptionMethod, digest)
116
+
117
+ if (smartHashing.isAlreadyHashed(value)) {
118
+ return value
119
+ }
120
+
121
+ if (cleaningFunction) {
122
+ value = cleaningFunction(value)
123
+ }
124
+ return smartHashing.hash(value)
125
+ }
126
+
127
+ export async function smartHash(value: string, normalizeFunction?: (value: string) => string): Promise<string> {
128
+ return await processHashing(value, 'sha256', 'hex', normalizeFunction)
129
+ }
130
+
131
+ function normalize(value: string, allowedChars: RegExp, trim = true): string {
132
+ let normalized = value.toLowerCase().replace(allowedChars, '')
133
+ if (trim) normalized = normalized.trim()
134
+ return normalized
135
+ }
136
+
137
+ const emailAllowed = /[^a-z0-9.@+-]/g
138
+
139
+ export function normalizeEmail(email: string): string {
140
+ return normalize(email, emailAllowed)
141
+ }