summaryrefslogtreecommitdiffstats
path: root/toolkit/components/formautofill/shared/AddressComponent.sys.mjs
blob: 40e00b66a0996b2fd231cfb9939443d97e1e60b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { FormAutofill } from "resource://autofill/FormAutofill.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  AddressParser: "resource://gre/modules/shared/AddressParser.sys.mjs",
  FormAutofillNameUtils:
    "resource://gre/modules/shared/FormAutofillNameUtils.sys.mjs",
  FormAutofillUtils: "resource://gre/modules/shared/FormAutofillUtils.sys.mjs",
  PhoneNumber: "resource://gre/modules/shared/PhoneNumber.sys.mjs",
  PhoneNumberNormalizer:
    "resource://gre/modules/shared/PhoneNumberNormalizer.sys.mjs",
});

/**
 * Class representing a collection of tokens extracted from a string.
 */
class Tokens {
  #tokens = null;

  // By default we split passed string with whitespace.
  constructor(value, sep = /\s+/) {
    this.#tokens = value.split(sep);
  }

  get tokens() {
    return this.#tokens;
  }

  /**
   * Checks if all the tokens in the current object can be found in another
   * token object.
   *
   * @param   {Tokens}   other   The other Tokens instance to compare with.
   * @param   {Function} compare An optional custom comparison function.
   * @returns {boolean}          True if the current Token object is a subset of the
   *                             other Token object, false otherwise.
   */
  isSubset(other, compare = (a, b) => a == b) {
    return this.tokens.every(tokenSelf => {
      for (const tokenOther of other.tokens) {
        if (compare(tokenSelf, tokenOther)) {
          return true;
        }
      }
      return false;
    });
  }

  /**
   * Checks if all the tokens in the current object can be found in another
   * Token object's tokens (in order).
   * For example, ["John", "Doe"] is a subset of ["John", "Michael", "Doe"]
   * in order but not a subset of ["Doe", "Michael", "John"] in order.
   *
   * @param   {Tokens}   other   The other Tokens instance to compare with.
   * @param   {Function} compare An optional custom comparison function.
   * @returns {boolean}          True if the current Token object is a subset of the
   *                             other Token object, false otherwise.
   */
  isSubsetInOrder(other, compare = (a, b) => a == b) {
    if (this.tokens.length > other.tokens.length) {
      return false;
    }

    let idx = 0;
    return this.tokens.every(tokenSelf => {
      for (; idx < other.tokens.length; idx++) {
        if (compare(tokenSelf, other.tokens[idx])) {
          return true;
        }
      }
      return false;
    });
  }
}

/**
 * The AddressField class is a base class representing a single address field.
 */
class AddressField {
  #userValue = null;

  #region = null;

  /**
   * Create a representation of a single address field.
   *
   * @param {string} value
   *        The unnormalized value of an address field.
   *
   * @param {string} region
   *        The region of a single address field. Used to determine what collator should be
   *        for string comparisons of the address's field value.
   */
  constructor(value, region) {
    this.#userValue = value?.trim();
    this.#region = region;
  }

  /**
   * Get the unnormalized value of the address field.
   *
   * @returns {string} The unnormalized field value.
   */
  get userValue() {
    return this.#userValue;
  }

  /**
   * Get the collator used for string comparisons.
   *
   * @returns {Intl.Collator} The collator.
   */
  get collator() {
    return lazy.FormAutofillUtils.getSearchCollators(this.#region, {
      ignorePunctuation: false,
    });
  }

  get region() {
    return this.#region;
  }

  /**
   * Compares two strings using the collator.
   *
   * @param   {string} a The first string to compare.
   * @param   {string} b The second string to compare.
   * @returns {number} A negative, zero, or positive value, depending on the comparison result.
   */
  localeCompare(a, b) {
    return lazy.FormAutofillUtils.strCompare(a, b, this.collator);
  }

  /**
   * Checks if the field value is empty.
   *
   * @returns {boolean} True if the field value is empty, false otherwise.
   */
  isEmpty() {
    return !this.#userValue;
  }

  /**
   * Normalizes the unnormalized field value using the provided options.
   *
   * @param {object} options - Options for normalization.
   * @returns {string} The normalized field value.
   */
  normalizeUserValue(options) {
    return lazy.AddressParser.normalizeString(this.#userValue, options);
  }

  /**
   * Returns a string representation of the address field.
   * Ex. "Country: US", "PostalCode: 55123", etc.
   */
  toString() {
    return `${this.constructor.name}: ${this.#userValue}\n`;
  }

  /**
   * Checks if the field value is valid.
   *
   * @returns {boolean} True if the field value is valid, false otherwise.
   */
  isValid() {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  }

  /**
   * Compares the current field value with another field value for equality.
   */
  equals() {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  }

  /**
   * Checks if the current field value contains another field value.
   */
  contains() {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  }
}

/**
 * A street address.
 * See autocomplete="street-address".
 */
class StreetAddress extends AddressField {
  static ac = "street-address";

  #structuredStreetAddress = null;

  constructor(value, region) {
    super(value, region);

    this.#structuredStreetAddress = lazy.AddressParser.parseStreetAddress(
      lazy.AddressParser.replaceControlCharacters(this.userValue)
    );
  }

  get structuredStreetAddress() {
    return this.#structuredStreetAddress;
  }
  get street_number() {
    return this.#structuredStreetAddress?.street_number;
  }
  get street_name() {
    return this.#structuredStreetAddress?.street_name;
  }
  get floor_number() {
    return this.#structuredStreetAddress?.floor_number;
  }
  get apartment_number() {
    return this.#structuredStreetAddress?.apartment_number;
  }

  isValid() {
    return this.userValue ? !!/[\p{Letter}]/u.exec(this.userValue) : true;
  }

  equals(other) {
    if (this.structuredStreetAddress && other.structuredStreetAddress) {
      return (
        this.street_number?.toLowerCase() ==
          other.street_number?.toLowerCase() &&
        this.street_name?.toLowerCase() == other.street_name?.toLowerCase() &&
        this.apartment_number?.toLowerCase() ==
          other.apartment_number?.toLowerCase() &&
        this.floor_number?.toLowerCase() == other.floor_number?.toLowerCase()
      );
    }

    const options = {
      ignore_case: true,
    };

    return (
      this.normalizeUserValue(options) == other.normalizeUserValue(options)
    );
  }

  contains(other) {
    let selfStreetName = this.userValue;
    let otherStreetName = other.userValue;

    // Compare street number, apartment number and floor number if
    // both addresses are parsed successfully.
    if (this.structuredStreetAddress && other.structuredStreetAddress) {
      if (
        (other.street_number && this.street_number != other.street_number) ||
        (other.apartment_number &&
          this.apartment_number != other.apartment_number) ||
        (other.floor_number && this.floor_number != other.floor_number)
      ) {
        return false;
      }

      // Use parsed street name to compare
      selfStreetName = this.street_name;
      otherStreetName = other.street_name;
    }

    // Check if one street name contains the other
    const options = {
      ignore_case: true,
      replace_punctuation: " ",
    };
    const selfTokens = new Tokens(
      lazy.AddressParser.normalizeString(selfStreetName, options),
      /[\s\n\r]+/
    );
    const otherTokens = new Tokens(
      lazy.AddressParser.normalizeString(otherStreetName, options),
      /[\s\n\r]+/
    );

    return otherTokens.isSubsetInOrder(selfTokens, (a, b) =>
      this.localeCompare(a, b)
    );
  }

  static fromRecord(record, region) {
    return new StreetAddress(record[StreetAddress.ac], region);
  }
}

/**
 * A postal code / zip code
 * See autocomplete="postal-code"
 */
class PostalCode extends AddressField {
  static ac = "postal-code";

  constructor(value, region) {
    super(value, region);
  }

  isValid() {
    const { postalCodePattern } = lazy.FormAutofillUtils.getFormFormat(
      this.region
    );
    const regexp = new RegExp(`^${postalCodePattern}$`);
    return regexp.test(this.userValue);
  }

  equals(other) {
    const options = {
      ignore_case: true,
      remove_whitespace: true,
      remove_punctuation: true,
    };

    return (
      this.normalizeUserValue(options) == other.normalizeUserValue(options)
    );
  }

  contains(other) {
    const options = {
      ignore_case: true,
      remove_whitespace: true,
      remove_punctuation: true,
    };

    const self_normalized_value = this.normalizeUserValue(options);
    const other_normalized_value = other.normalizeUserValue(options);

    return (
      self_normalized_value.endsWith(other_normalized_value) ||
      self_normalized_value.startsWith(other_normalized_value)
    );
  }

  static fromRecord(record, region) {
    return new PostalCode(record[PostalCode.ac], region);
  }
}

/**
 * City name.
 * See autocomplete="address-level2"
 */
class City extends AddressField {
  static ac = "address-level2";

  #city = null;

  constructor(value, region) {
    super(value, region);

    const options = {
      ignore_case: true,
    };
    this.#city = this.normalizeUserValue(options);
  }

  get city() {
    return this.#city;
  }

  isValid() {
    return this.userValue ? !!/[\p{Letter}]/u.exec(this.userValue) : true;
  }

  equals(other) {
    return this.city == other.city;
  }

  contains(other) {
    const options = {
      ignore_case: true,
      replace_punctuation: " ",
      merge_whitespace: true,
    };

    const selfTokens = new Tokens(this.normalizeUserValue(options));
    const otherTokens = new Tokens(other.normalizeUserValue(options));

    return otherTokens.isSubsetInOrder(selfTokens, (a, b) =>
      this.localeCompare(a, b)
    );
  }

  static fromRecord(record, region) {
    return new City(record[City.ac], region);
  }
}

/**
 * State.
 * See autocomplete="address-level1"
 */
class State extends AddressField {
  static ac = "address-level1";

  // The abbreviated region name. For example, California is abbreviated as CA
  #state = null;

  constructor(value, region) {
    super(value, region);

    if (!this.userValue) {
      return;
    }

    const options = {
      merge_whitespace: true,
      remove_punctuation: true,
    };
    this.#state = lazy.FormAutofillUtils.getAbbreviatedSubregionName(
      this.normalizeUserValue(options),
      region
    );
  }

  get state() {
    return this.#state;
  }

  isValid() {
    // If we can't get the abbreviated name, assume this is an invalid state name
    return !!this.#state;
  }

  equals(other) {
    // If we have an abbreviated name, compare with it.
    if (this.state) {
      return this.state == other.state;
    }

    // If we don't have an abbreviated name, just compare the userValue
    return this.userValue == other.userValue;
  }

  contains(other) {
    return this.equals(other);
  }

  static fromRecord(record, region) {
    return new State(record[State.ac], region);
  }
}

/**
 * A country or territory code.
 * See autocomplete="country"
 */
class Country extends AddressField {
  static ac = "country";

  // iso 3166 2-alpha code
  #country_code = null;

  constructor(value, region) {
    super(value, region);

    if (this.isEmpty()) {
      return;
    }

    const options = {
      merge_whitespace: true,
      remove_punctuation: true,
    };

    const country = this.normalizeUserValue(options);
    this.#country_code = lazy.FormAutofillUtils.identifyCountryCode(country);

    // When the country name is not a valid one, we use the current region instead
    if (!this.#country_code) {
      this.#country_code = lazy.FormAutofillUtils.identifyCountryCode(region);
    }
  }

  get country_code() {
    return this.#country_code;
  }

  isValid() {
    return !!this.#country_code;
  }

  equals(other) {
    return this.country_code == other.country_code;
  }

  contains(_other) {
    return false;
  }

  static fromRecord(record, region) {
    return new Country(record[Country.ac], region);
  }
}

/**
 * The field expects the value to be a person's full name.
 * See autocomplete="name"
 */
class Name extends AddressField {
  static ac = "name";

  constructor(value, region) {
    super(value, region);
  }

  // Reference:
  // https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/data_model/autofill_profile_comparator.cc;drc=566369da19275cc306eeb51a3d3451885299dabb;bpv=1;bpt=1;l=935
  static createNameVariants(name) {
    let tokens = name.trim().split(" ");

    let variants = [""];
    if (!tokens[0]) {
      return variants;
    }

    for (const token of tokens) {
      let tmp = [];
      for (const variant of variants) {
        tmp.push(variant + " " + token);
        tmp.push(variant + " " + token[0]);
      }
      variants = variants.concat(tmp);
    }

    const options = {
      merge_whitespace: true,
    };
    return variants.map(v => lazy.AddressParser.normalizeString(v, options));
  }

  isValid() {
    return this.userValue ? !!/[\p{Letter}]/u.exec(this.userValue) : true;
  }

  equals(other) {
    const options = {
      ignore_case: true,
    };
    return (
      this.normalizeUserValue(options) == other.normalizeUserValue(options)
    );
  }

  contains(other) {
    // Unify puncutation while comparing so users can choose the right one
    // if the only different part is puncutation
    // Ex. John O'Brian is similar to John O`Brian
    let options = {
      ignore_case: true,
      replace_punctuation: " ",
      merge_whitespace: true,
    };
    let selfName = this.normalizeUserValue(options);
    let otherName = other.normalizeUserValue(options);
    let selfTokens = new Tokens(selfName);
    let otherTokens = new Tokens(otherName);

    if (
      otherTokens.isSubsetInOrder(selfTokens, (a, b) =>
        this.localeCompare(a, b)
      )
    ) {
      return true;
    }

    // Remove puncutation from self and test whether current contains other
    // Ex. John O'Brian is similar to John OBrian
    selfName = this.normalizeUserValue({
      ignore_case: true,
      remove_punctuation: true,
      merge_whitespace: true,
    });
    otherName = other.normalizeUserValue({
      ignore_case: true,
      remove_punctuation: true,
      merge_whitespace: true,
    });

    selfTokens = new Tokens(selfName);
    otherTokens = new Tokens(otherName);
    if (
      otherTokens.isSubsetInOrder(selfTokens, (a, b) =>
        this.localeCompare(a, b)
      )
    ) {
      return true;
    }

    // Create variants of the names by generating initials for given and middle names.

    selfName = lazy.FormAutofillNameUtils.splitName(selfName);
    otherName = lazy.FormAutofillNameUtils.splitName(otherName);
    // In the following we compare cases when people abbreviate first name
    // and middle name with initials. So if family name is different,
    // we can just skip and assume the two names are different
    if (!this.localeCompare(selfName.family, otherName.family)) {
      return false;
    }

    const otherNameWithoutFamily = lazy.FormAutofillNameUtils.joinNameParts({
      given: otherName.given,
      middle: otherName.middle,
    });
    let givenVariants = Name.createNameVariants(selfName.given);
    let middleVariants = Name.createNameVariants(selfName.middle);

    for (const given of givenVariants) {
      for (const middle of middleVariants) {
        const nameVariant = lazy.FormAutofillNameUtils.joinNameParts({
          given,
          middle,
        });

        if (this.localeCompare(nameVariant, otherNameWithoutFamily)) {
          return true;
        }
      }
    }

    // Check cases when given name and middle name are abbreviated with initial
    // and the initials are put together. ex. John Michael Doe to JM. Doe
    if (selfName.given && selfName.middle) {
      const nameVariant = [
        ...selfName.given.split(" "),
        ...selfName.middle.split(" "),
      ].reduce((initials, name) => {
        initials += name[0];
        return initials;
      }, "");

      if (this.localeCompare(nameVariant, otherNameWithoutFamily)) {
        return true;
      }
    }

    return false;
  }

  static fromRecord(record, region) {
    return new Name(record[Name.ac], region);
  }
}

/**
 * A full telephone number, including the country code.
 * See autocomplete="tel"
 */
class Tel extends AddressField {
  static ac = "tel";

  #valid = false;

  // The country code part of a telphone number, such as "1" for the United States
  #country_code = null;

  // The national part of a telphone number. For example, the phone number "+1 520-248-6621"
  // national part is "520-248-6621".
  #national_number = null;

  constructor(value, region) {
    super(value, region);

    if (!this.userValue) {
      return;
    }

    // TODO: Support parse telephone extension
    // We compress all tel-related fields into a single tel field when an an form
    // is submitted, so we need to decompress it here.
    const parsed_tel = lazy.PhoneNumber.Parse(this.userValue, region);
    if (parsed_tel) {
      this.#national_number = parsed_tel?.nationalNumber;
      this.#country_code = parsed_tel?.countryCode;

      this.#valid = true;
    } else {
      this.#national_number = lazy.PhoneNumberNormalizer.Normalize(
        this.userValue
      );

      const md = lazy.PhoneNumber.FindMetaDataForRegion(region);
      this.#country_code = md ? "+" + md.nationalPrefix : null;

      this.#valid = lazy.PhoneNumber.IsValid(this.#national_number, md);
    }
  }

  get country_code() {
    return this.#country_code;
  }

  get national_number() {
    return this.#national_number;
  }

  isValid() {
    return this.#valid;
  }

  equals(other) {
    return (
      this.national_number == other.national_number &&
      this.country_code == other.country_code
    );
  }

  contains(other) {
    if (!this.country_code || this.country_code != other.country_code) {
      return false;
    }

    return this.national_number.endsWith(other.national_number);
  }

  toString() {
    return `${this.constructor.name}: ${this.country_code} ${this.national_number}\n`;
  }

  static fromRecord(record, region) {
    return new Tel(record[Tel.ac], region);
  }
}

/**
 * A company or organization name.
 * See autocomplete="organization".
 */
class Organization extends AddressField {
  static ac = "organization";

  constructor(value, region) {
    super(value, region);
  }

  isValid() {
    return this.userValue
      ? !!/[\p{Letter}\p{Number}]/u.exec(this.userValue)
      : true;
  }

  /**
   * Two company names are considered equal only when everything is the same.
   */
  equals(other) {
    return this.userValue == other.userValue;
  }

  // Mergeable use locale compare
  contains(other) {
    const options = {
      replace_punctuation: " ", // mozilla org vs mozilla-org
      merge_whitespace: true,
      ignore_case: true, // mozilla vs Mozilla
    };

    // If every token in B can be found in A without considering order
    // Example, 'Food & Pharmacy' contains 'Pharmacy & Food'
    const selfTokens = new Tokens(this.normalizeUserValue(options));
    const otherTokens = new Tokens(other.normalizeUserValue(options));

    return otherTokens.isSubset(selfTokens, (a, b) => this.localeCompare(a, b));
  }

  static fromRecord(record, region) {
    return new Organization(record[Organization.ac], region);
  }
}

/**
 * An email address
 * See autocomplete="email".
 */
class Email extends AddressField {
  static ac = "email";

  constructor(value, region) {
    super(value, region);
  }

  // Since we are using the valid check to determine whether we capture the email field when users submitting a forma,
  // use a less restrict email verification method so we capture an email for most of the cases.
  // The current algorithm is based on the regular expression defined in
  // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
  //
  // We might also change this to something similar to the algorithm used in
  // EmailInputType::IsValidEmailAddress if we want a more strict email validation algorithm.
  isValid() {
    const regex =
      /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    const match = this.userValue.match(regex);
    if (!match) {
      return false;
    }

    return true;
  }

  /*
  // JS version of EmailInputType::IsValidEmailAddress
  isValid() {
    const regex = /^([a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+)@([a-zA-Z0-9-]+\.[a-zA-Z]{2,})$/;
    const match = this.userValue.match(regex);
    if (!match) {
      return false;
    }
    const local = match[1];
    const domain = match[2];

    // The domain name can't begin with a dot or a dash.
    if (['-', '.'].includes(domain[0])) {
      return false;
    }

    // A dot can't follow a dot or a dash.
    // A dash can't follow a dot.
    const pattern = /(\.\.)|(\.-)|(-\.)/;
    if (pattern.test(domain)) {
      return false;
    }

    return true;
  }
*/

  equals(other) {
    const options = {
      ignore_case: true,
    };

    // email is case-insenstive
    return (
      this.normalizeUserValue(options) == other.normalizeUserValue(options)
    );
  }

  contains(_other) {
    return false;
  }

  static fromRecord(record, region) {
    return new Email(record[Email.ac], region);
  }
}

/**
 * The AddressComparison class compares two AddressComponent instances and
 * provides information about the differences or similarities between them.
 *
 * The comparison result is stored and the object and can be retrieved by calling
 * 'result' getter.
 */
export class AddressComparison {
  // Const to define the comparison result for two address fields
  static BOTH_EMPTY = 0;
  static A_IS_EMPTY = 1;
  static B_IS_EMPTY = 2;
  static A_CONTAINS_B = 3;
  static B_CONTAINS_A = 4;
  // When A contains B and B contains A Ex. "Pizza & Food vs Food & Pizza"
  static SIMILAR = 5;
  static SAME = 6;
  static DIFFERENT = 7;

  // The comparion result, keyed by field name.
  #result = {};

  /**
   * Constructs AddressComparison by comparing two AddressComponent objects.
   *
   * @class
   * @param {AddressComponent} addressA - The first address to compare.
   * @param {AddressComponent} addressB - The second address to compare.
   */
  constructor(addressA, addressB) {
    for (const fieldA of addressA.getAllFields()) {
      const fieldName = fieldA.constructor.ac;
      const fieldB = addressB.getField(fieldName);
      if (fieldB) {
        this.#result[fieldName] = AddressComparison.compare(fieldA, fieldB);
      } else {
        this.#result[fieldName] = AddressComparison.B_IS_EMPTY;
      }
    }

    for (const fieldB of addressB.getAllFields()) {
      const fieldName = fieldB.constructor.ac;
      if (!addressB.getField(fieldName)) {
        this.#result[fieldName] = AddressComparison.A_IS_EMPTY;
      }
    }
  }

  /**
   * Retrieves the result object containing the comparison results.
   *
   * @returns {object} The result object with keys corresponding to field names
   *                  and values being comparison constants.
   */
  get result() {
    return this.#result;
  }

  /**
   * Compares two address fields and returns the comparison result.
   *
   * @param  {AddressField} fieldA The first field to compare.
   * @param  {AddressField} fieldB The second field to compare.
   * @returns {number}       A constant representing the comparison result.
   */
  static compare(fieldA, fieldB) {
    if (fieldA.isEmpty()) {
      return fieldB.isEmpty()
        ? AddressComparison.BOTH_EMPTY
        : AddressComparison.A_IS_EMPTY;
    } else if (fieldB.isEmpty()) {
      return AddressComparison.B_IS_EMPTY;
    }

    if (fieldA.equals(fieldB)) {
      return AddressComparison.SAME;
    }

    if (fieldB.contains(fieldA)) {
      if (fieldA.contains(fieldB)) {
        return AddressComparison.SIMILAR;
      }
      return AddressComparison.B_CONTAINS_A;
    } else if (fieldA.contains(fieldB)) {
      return AddressComparison.A_CONTAINS_B;
    }

    return AddressComparison.DIFFERENT;
  }

  /**
   * Converts a comparison result constant to a readable string.
   *
   * @param  {number} result The comparison result constant.
   * @returns {string}        A readable string representing the comparison result.
   */
  static resultToString(result) {
    switch (result) {
      case AddressComparison.BOTH_EMPTY:
        return "both fields are empty";
      case AddressComparison.A_IS_EMPTY:
        return "field A is empty";
      case AddressComparison.B_IS_EMPTY:
        return "field B is empty";
      case AddressComparison.A_CONTAINS_B:
        return "field A contains field B";
      case AddressComparison.B_CONTAINS_B:
        return "field B contains field A";
      case AddressComparison.SIMILAR:
        return "field A and field B are similar";
      case AddressComparison.SAME:
        return "two fields are the same";
      case AddressComparison.DIFFERENT:
        return "two fields are different";
    }
    return "";
  }

  /**
   * Returns a formatted string representing the comparison results for each field.
   *
   * @returns {string} A formatted string with field names and their respective
   *                  comparison results.
   */
  toString() {
    let string = "Comparison Result:\n";
    for (const [name, result] of Object.entries(this.#result)) {
      string += `${name}: ${AddressComparison.resultToString(result)}\n`;
    }
    return string;
  }
}

/**
 * The AddressComponent class represents a structured address that is transformed
 * from address record created in FormAutofillHandler 'createRecord' function.
 *
 * An AddressComponent object consisting of various fields such as state, city,
 * country, postal code, etc. The class provides a compare methods
 * to compare another AddressComponent against the current instance.
 *
 * Note. This class assumes records that pass to it have already been normalized.
 */
export class AddressComponent {
  /**
   * An object that stores individual address field instances
   * (e.g., class State, class City, class Country, etc.), keyed by the
   * field's clas name.
   */
  #fields = {};

  /**
   * Constructs an AddressComponent object by converting passed address record object.
   *
   * @class
   * @param {object}  record         The address record object containing address data.
   * @param {object}  [options = {}] a list of options for this method
   * @param {boolean} [options.ignoreInvalid = true]  Whether to ignore invalid address
   *                                 fields in the AddressComponent object. If set to true,
   *                                 invalid fields will be ignored.
   */
  constructor(record, { ignoreInvalid = true } = {}) {
    this.record = {};

    // Get country code first so we can use it to parse other fields
    const country = new Country(
      record[Country.ac],
      FormAutofill.DEFAULT_REGION
    );
    const region =
      country.country_code ||
      lazy.FormAutofillUtils.identifyCountryCode(FormAutofill.DEFAULT_REGION);

    // Build an mapping that the key is field name and the value is the AddressField object
    [
      country,
      new StreetAddress(record[StreetAddress.ac], region),
      new PostalCode(record[PostalCode.ac], region),
      new State(record[State.ac], region),
      new City(record[City.ac], region),
      new Name(record[Name.ac], region),
      new Tel(record[Tel.ac], region),
      new Organization(record[Organization.ac], region),
      new Email(record[Email.ac], region),
    ].forEach(addressField => {
      if (
        !addressField.isEmpty() &&
        (!ignoreInvalid || addressField.isValid())
      ) {
        const fieldName = addressField.constructor.ac;
        this.#fields[fieldName] = addressField;
        this.record[fieldName] = record[fieldName];
      }
    });
  }

  /**
   * Retrieves all the address fields.
   *
   * @returns {Array} An array of address field objects.
   */
  getAllFields() {
    return Object.values(this.#fields);
  }

  /**
   * Retrieves the field object with the specified name.
   *
   * @param  {string} name The name of the field to retrieve.
   * @returns {object}      The address field object with the specified name,
   *                       or undefined if the field is not found.
   */
  getField(name) {
    return this.#fields[name];
  }

  /**
   * Compares the current AddressComponent with another AddressComponent.
   *
   * @param  {AddressComponent} address The AddressComponent object to compare
   *                                    against the current one.
   * @returns {object} An object containing comparison results. The keys of the object represent
   *                  individual address field, and the values are strings indicating the comparison result:
   *                  - "same" if both components are either empty or the same,
   *                  - "superset" if the current contains the input or the input is empty,
   *                  - "subset" if the input contains the current or the current is empty,
   *                  - "similar" if the two address components are similar,
   *                  - "different" if the two address components are different.
   */
  compare(address) {
    let result = {};

    const comparison = new AddressComparison(this, address);
    for (const [k, v] of Object.entries(comparison.result)) {
      if ([AddressComparison.BOTH_EMPTY, AddressComparison.SAME].includes(v)) {
        result[k] = "same";
      } else if (
        [AddressComparison.B_IS_EMPTY, AddressComparison.A_CONTAINS_B].includes(
          v
        )
      ) {
        result[k] = "superset";
      } else if (
        [AddressComparison.A_IS_EMPTY, AddressComparison.B_CONTAINS_A].includes(
          v
        )
      ) {
        result[k] = "subset";
      } else if ([AddressComparison.SIMILAR].includes(v)) {
        result[k] = "similar";
      } else {
        result[k] = "different";
      }
    }
    return result;
  }

  /**
   * Print all the fields in this AddressComponent object.
   */
  toString() {
    let string = "";
    for (const field of Object.values(this.#fields)) {
      string += field.toString();
    }
    return string;
  }
}