Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 1121 1122 1123 1124 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 23x 1x 1x 1x 62x 62x 62x 1x 1x 1x 8x 4x 4x 4x 4x 4x 8x 1x 1x 1x 1x 1x 1x 7x 3x 3x 3x 3x 2x 3x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 1x 1x 1x 56x 3x 3x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 424x 9x 9x 9x 9x 9x 9x 416x 1x 1x 1x 1x 1x 1x 1x 1x 414x 414x 53x 56x 3x 3x 3x 3x 3x 53x 53x 1x 1x 1x 56x 56x 56x 3x 3x 3x 3x 3x 3x 50x 55x 3x 3x 3x 3x 3x 3x 56x 1x 1x 1x 45x 3x 3x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 336x 1x 1x 1x 336x 1x 1x 1x 1x 1x 1x 1x 1x 334x 334x 42x 45x 2x 2x 2x 2x 2x 42x 42x 1x 1x 1x 45x 45x 45x 2x 2x 2x 45x 1x 1x 1x 45x 45x 45x 45x 5x 5x 5x 45x 1x 1x 1x 39x 39x 39x 1x 1x 1x 52x 52x 52x 1x 1x 1x 42x 42x 1x 1x 1x 1x 1x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 38x 38x 1x 1x 1x 323x 323x 309x 309x 308x 323x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 145x 145x 1x 1x 1x 1x 1x 1x 1x 179x 179x 1x 1x 1x 512x 512x 512x 512x 512x 193x 193x 193x 512x 192x 192x 192x 192x 192x 192x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 49x 49x 7x 7x 49x 49x 1x 1x 1x 49x 49x 32x 32x 32x 32x 32x 49x 49x 1x 1x 1x 186x 186x 63x 186x 186x 1x 1x 1x 21x 21x 1x 1x 1x 2x 2x 1x 1x 1x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { CAS_REGEX, SPIN_SPEED, UOM, type Uom } from '@/constants/common';
import { CURRENCY_SYMBOL_MAP } from '@/constants/currency';
import { SUPPLIER_CLASS_NAMES } from '@/constants/suppliers';
import { findCountryByIso2 } from '@/helpers/country';
import { looksLikeSmiles } from '@/helpers/smiles';
import { addActualValueToIssues } from '@/helpers/utils';
import { Logger, REMOTE_LOG_LEVELS } from '@/utils/Logger';
//import { currencies } from "price-parser";
import * as v from 'valibot';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('typeGuards.common');
/**
* @categoryDescription Typeguards
* These functions are available for common typeguards that are used throughout the application.
* @showCategories
* @module
*/
const httpResponseSchema = v.object({
ok: v.boolean(),
status: v.number(),
statusText: v.string(),
json: v.custom<(...args: unknown[]) => unknown>((val) => typeof val === 'function'),
text: v.custom<(...args: unknown[]) => unknown>((val) => typeof val === 'function'),
});
/**
* Type guard to validate if a value is a valid HTTP Response object.
* Checks for the presence of essential Response properties and methods.
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value is a Response object
* @example
* ```typescript
* // Valid Response object
* const response = new Response('{"data": "test"}', {
* headers: { 'Content-Type': 'application/json' }
* });
* if (isHttpResponse(response)) {
* console.log('Valid HTTP response:', response.status);
* }
*
* // Invalid Response object
* const invalidResponse = { status: 200 }; // Missing required properties
* if (!isHttpResponse(invalidResponse)) {
* console.log('Not a valid HTTP response');
* }
* ```
* @source
*/
export function isHttpResponse(value: unknown): value is Response {
return v.safeParse(httpResponseSchema, value).success;
}
/**
* Type guard to validate if a value is a valid UOM.
* Checks if the value is a string and if it is in the UOM array.
*
* @category Typeguards
* @param uom - The value to validate
* @returns Type predicate indicating if the value is a valid UOM
*
* @example
* ```typescript
* // Valid UOM
* const validUOM = "g";
* if (isUOM(validUOM)) {
* console.log('Valid UOM:', validUOM);
* }
*
* // Invalid UOM
* const invalidUOM = 123; // Number instead of string
* if (!isUOM(invalidUOM)) {
* console.log('Invalid UOM:', invalidUOM);
* }
* ```
* @source
*/
export function isUOM(uom: unknown): uom is Uom {
// Widen the enum-value array to string[] so includes() accepts an arbitrary string.
return typeof uom === 'string' && (Object.values(UOM) as string[]).includes(uom);
}
/**
* Type guard to validate if a Response object contains JSON content.
* Checks both the Content-Type header and ensures it's a valid Response object.
*
* @category Typeguards
* @param response - The Response object to validate
* @returns Type predicate indicating if the response contains JSON content
*
* @example
* ```typescript
* // Valid JSON response
* const jsonResponse = new Response('{"data": "test"}', {
* headers: { 'Content-Type': 'application/json' }
* });
* if (isJsonResponse(jsonResponse)) {
* const data = await jsonResponse.json();
* console.log('JSON data:', data);
* }
*
* // Non-JSON response
* const htmlResponse = new Response('<html>...</html>', {
* headers: { 'Content-Type': 'text/html' }
* });
* if (!isJsonResponse(htmlResponse)) {
* console.log('Not a JSON response');
* }
* ```
* @source
*/
export function isJsonResponse(response: unknown): response is Response {
if (!isHttpResponse(response)) {
return false;
}
const contentType = response.headers.get('Content-Type');
return (
contentType !== null && (contentType.includes('/json') || contentType.includes('/javascript'))
);
}
/**
* Type guard to validate if a Response object contains JSON content.
* Checks both the Content-Type header and ensures it's a valid Response object.
*
* @category Typeguards
* @param response - The Response object to validate
* @returns Type predicate indicating if the response contains JSON content
*
* @example
* ```typescript
* // Valid JSON response
* const jsonResponse = new Response('{"data": "test"}', {
* headers: { 'Content-Type': 'application/json' }
* });
* assertJsonResponse(jsonResponse);
* ```
* @source
*/
export function assertJsonResponse(response: unknown): asserts response is Response {
if (!isJsonResponse(response)) {
throw new TypeError('assertJsonResponse| Invalid JSON response', { cause: response });
}
}
/**
* Type guard to validate if a Response object contains HTML content.
* Checks both the Content-Type header and ensures it's a valid Response object.
*
* @category Typeguards
* @param response - The Response object to validate
* @returns Type predicate indicating if the response contains HTML content
*
* @example
* ```typescript
* // Valid HTML response
* const htmlResponse = new Response('<html><body>Hello</body></html>', {
* headers: { 'Content-Type': 'text/html' }
* });
* if (isHtmlResponse(htmlResponse)) {
* const text = await htmlResponse.text();
* console.log('HTML content:', text);
* }
*
* // Non-HTML response
* const jsonResponse = new Response('{"data": "test"}', {
* headers: { 'Content-Type': 'application/json' }
* });
* if (!isHtmlResponse(jsonResponse)) {
* console.log('Not an HTML response');
* }
* ```
* @source
*/
export function isHtmlResponse(response: unknown): response is Response {
if (!isHttpResponse(response)) return false;
const contentType = response.headers.get('Content-Type');
return (
contentType !== null &&
(contentType.includes('text/') ||
contentType.includes('application/xhtml+xml') ||
contentType.includes('json-amazonui-streaming'))
);
}
/**
* Asserts that a Response object contains HTML content.
* Throws a TypeError if the response is not a valid HTML response.
*
* @category Typeguards
* @param response - The Response object to validate
* @throws TypeError if the response is not a valid HTML response
* @example
* ```typescript
* const htmlResponse = new Response('<html><body>Hello</body></html>', {
* headers: { 'Content-Type': 'text/html' }
* });
* assertHtmlResponse(htmlResponse);
* ```
* @source
*/
export function assertHtmlResponse(response: unknown): asserts response is Response {
if (!isHtmlResponse(response)) {
throw new TypeError('assertHtmlResponse| Invalid HTML response', { cause: response });
}
}
const validResultSchema = v.object({
title: v.string(),
price: v.number(),
quantity: v.number(),
uom: v.string(),
supplier: v.string(),
url: v.string(),
currencyCode: v.string(),
currencySymbol: v.string(),
});
/**
* Type guard to validate if a value has the minimal required properties of a search result.
* Checks for the presence and correct types of all required fields for a search result.
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value has required search result properties
* @example
* ```typescript
* // Valid search result
* const validResult = {
* title: "Sodium Chloride",
* price: 29.99,
* quantity: 500,
* uom: "g",
* supplier: "ChemSupplier",
* url: "/products/nacl",
* currencyCode: "USD",
* currencySymbol: "$"
* };
*
* if (isValidResult(validResult)) {
* console.log('Valid search result:', validResult.title);
* }
*
* // Invalid search result
* const invalidResult = {
* title: "Sodium Chloride",
* price: "29.99", // Wrong type (string instead of number)
* quantity: 500
* // Missing required fields
* };
* if (!isValidResult(invalidResult)) {
* console.log('Invalid search result');
* }
* ```
* @source
*/
export function isValidResult(value: unknown): value is RequiredProductFields {
return v.safeParse(validResultSchema, value).success;
}
/**
* Checks a product object for missing or incorrectly typed minimal required fields.
* Returns an array of field names that are missing or have the wrong type.
*
* @category Typeguards
* @param product - The product object to validate
* @returns Array of missing or invalid field names (empty if all fields are valid)
* @throws TypeError if product is null or not an object
* @example
* ```typescript
* const product = { title: "NaCl", price: 29.99 };
* const missing = checkMissingMinimalProductFields(product);
* // ["quantity", "uom", "supplier", "url", "currencyCode", "currencySymbol"]
* ```
* @source
*/
export function checkMissingMinimalProductFields(product: unknown): string[] {
if (!product || typeof product !== 'object') {
throw new TypeError('checkMissingMinimalProductFields| Invalid product', { cause: product });
}
const requiredProps: Record<keyof RequiredProductFields, string> = {
title: 'string',
price: 'number',
quantity: 'number',
uom: 'string',
supplier: 'string',
url: 'string',
currencyCode: 'string',
currencySymbol: 'string',
};
// Safe: the guard above already verified product is a non-null object.
const record = product as Record<string, unknown>;
const result = Object.entries(requiredProps).reduce(
(acc: string[], [key, expectedType]: [string, string]) => {
if (key in record === false) {
logger.debug('checkMissingMinimalProductFields| No value found in product', {
product,
key,
});
return [...acc, key];
}
if (typeof record[key] !== expectedType) {
logger.debug('checkMissingMinimalProductFields| Property not the correct type', {
product,
key,
expectedType,
actualType: typeof record[key],
});
return [...acc, key];
}
return acc;
},
[],
);
if (result.length > 0) {
logger.warn('checkMissingMinimalProductFields| Product is missing required fields', {
product,
result,
});
}
return result;
}
/**
* Type guard to validate if a value has the minimal required properties of a Product.
* This is a less strict validation than isProduct as it only checks for the minimum required fields.
* Useful for validating partial product data during construction.
*
* @category Typeguards
* @param product - The value to validate
* @returns Type predicate indicating if the value has minimal required product properties
*
* @example
* ```typescript
* const minimalProduct = {
* title: "Sodium Chloride",
* price: 29.99,
* quantity: 500,
* uom: "g",
* supplier: "ChemSupplier",
* url: "/products/nacl",
* currencyCode: "USD",
* currencySymbol: "$"
* };
*
* if (isMinimalProduct(minimalProduct)) {
* console.log('Valid minimal product:', minimalProduct.title);
* } else {
* console.log('Invalid minimal product');
* }
*
* // Example with missing required fields
* const invalidProduct = {
* title: "Sodium Chloride",
* price: 29.99,
* quantity: 500
* // Missing other required fields
* };
* if (!isMinimalProduct(invalidProduct)) {
* console.log('Invalid minimal product - missing required fields');
* }
* ```
* @source
*/
export function isMinimalProduct(product: unknown): product is RequiredProductFields {
try {
const missingFields = checkMissingMinimalProductFields(product);
if (missingFields.length > 0) {
logger.debug('isMinimalProduct| Product is missing minimal fields', {
product,
missingFields,
});
return false;
}
return true;
} catch (error) {
logger.warn(`isMinimalProduct| The product is invalid: ${getErrorMessage(error)}`, {
product,
error,
});
return false;
}
}
/**
* Checks a product object for missing or incorrectly typed complete required fields.
* Returns an array of field names that are missing or have the wrong type.
*
* @category Typeguards
* @param product - The product object to validate
* @returns Array of missing or invalid field names (empty if all fields are valid)
* @throws TypeError if product is null or not an object
* @example
* ```typescript
* const product = { title: "NaCl", price: 29.99, quantity: 500, uom: "g" };
* const missing = checkCompleteProductFields(product);
* // ["supplier", "url", "currencyCode", "currencySymbol"]
* ```
* @source
*/
export function checkCompleteProductFields(product: unknown): string[] {
if (!product || typeof product !== 'object') {
throw new TypeError('checkCompleteProductFields| Invalid product', { cause: product });
}
const requiredProps: Record<keyof RequiredProductFields, string> = {
title: 'string',
price: 'number',
quantity: 'number',
uom: 'string',
supplier: 'string',
url: 'string',
currencyCode: 'string',
currencySymbol: 'string',
};
// Safe: the guard above already verified product is a non-null object.
const record = product as Record<string, unknown>;
const result = Object.entries(requiredProps).reduce(
(acc: string[], [key, expectedType]: [string, string]) => {
if (key in record === false) {
logger.debug('checkCompleteProductFields| No value found in product', { product, key });
return [...acc, key];
}
if (typeof record[key] !== expectedType) {
logger.debug('checkCompleteProductFields| Property not the correct type', {
product,
key,
expectedType,
actualType: typeof record[key],
});
return [...acc, key];
}
return acc;
},
[],
);
if (result.length > 0) {
logger.warn('checkCompleteProductFields| Product has missing or invalid fields', {
product,
result,
});
}
return result;
}
/**
* Asserts that a product object contains all required fields with correct types.
* Throws a TypeError listing any missing or invalid fields.
*
* @category Typeguards
* @param product - The product object to assert
* @throws TypeError if any required fields are missing or have incorrect types
* @example
* ```typescript
* try {
* assertCompleteProductFields(product);
* // product is now typed as RequiredProductFields
* } catch (error) {
* console.error("Invalid product:", error.message);
* }
* ```
* @source
*/
export function assertCompleteProductFields(
product: unknown,
): asserts product is RequiredProductFields {
const missingFields = checkCompleteProductFields(product);
if (missingFields.length > 0) {
throw new TypeError(
`Product does not contain or has invalid data for the following required fields: ${missingFields.join(', ')} `,
);
}
}
/**
* Type guard to validate if a value is a complete Product object.
* Checks for the presence and correct types of all required product fields.
* This is a stricter validation than isMinimalProduct as it ensures all required fields are present.
*
* @category Typeguards
* @param product - The value to validate
* @returns Type predicate indicating if the value is a complete Product object
*
* @example
* ```typescript
* const completeProduct = {
* title: "Sodium Chloride",
* price: 29.99,
* quantity: 500,
* uom: "g",
* supplier: "ChemSupplier",
* url: "/products/nacl",
* currencyCode: "USD",
* currencySymbol: "$",
* description: "High purity sodium chloride",
* cas: "7647-14-5"
* };
*
* if (isProduct(completeProduct)) {
* console.log('Valid complete product:', completeProduct.title);
* } else {
* console.log('Invalid product object');
* }
*
* // Example with missing required fields
* const partialProduct = {
* title: "Sodium Chloride",
* price: 29.99
* // Missing required fields
* };
* if (!isProduct(partialProduct)) {
* console.log('Invalid product - missing required fields');
* }
* ```
* @source
*/
export function isProduct(product: unknown): product is Product {
try {
assertCompleteProductFields(product);
return true;
} catch (error) {
logger.warn(`isProduct| The product is invalid: ${getErrorMessage(error)}`, { product, error });
return false;
}
}
/**
* Type guard to validate if a value is a valid currency symbol.
* Checks if the value is a string and if it is in the CURRENCY_SYMBOL_MAP.
*
* @category Typeguards
* @param symbol - The value to validate
* @returns Type predicate indicating if the value is a valid currency symbol
*
* @example
* ```typescript
* const validSymbol = "$";
* if (isCurrencySymbol(validSymbol)) {
* console.log("Valid currency symbol:", validSymbol);
* } else {
* console.log("Invalid currency symbol:", validSymbol);
* }
* ```
* @source
*/
export function isCurrencySymbol(symbol: unknown): symbol is CurrencySymbol {
// CURRENCY_SYMBOL_MAP maps code -> symbol, so its values are the valid symbols (e.g. "$").
return typeof symbol === 'string' && Object.values(CURRENCY_SYMBOL_MAP).includes(symbol);
}
/**
* Type guard to validate if a value is a valid currency code.
* Checks if the value is a string and if it is a known currency code in the CURRENCY_CODE_MAP.
*
* @category Typeguards
* @param code - The value to validate
* @returns Type predicate indicating if the value is a valid currency code
*
* @example
* ```typescript
* const validCode = "USD";
* if (isCurrencyCode(validCode)) {
* console.log("Valid currency code:", validCode);
* } else {
* console.log("Invalid currency code:", validCode);
* }
* ```
* @source
*/
export function isCurrencyCode(code: unknown): code is CurrencyCode {
// CURRENCY_SYMBOL_MAP maps code -> symbol, so its keys are the valid codes (e.g. "USD").
return typeof code === 'string' && code in CURRENCY_SYMBOL_MAP;
}
/**
* Type guard to validate if a value is a known ISO 3166-1 alpha-2 country code.
* Checks the value against `country-list-js` so any real country code is accepted.
*
* @category Typeguards
* @param country - The value to validate
* @returns Type predicate indicating if the value is a valid country code
* @example
* ```typescript
* isCountryCode("US") // true
* isCountryCode("ZZ") // false
* isCountryCode(undefined) // false
* ```
* @source
*/
export function isCountryCode(country: unknown): country is CountryCode {
return typeof country === 'string' && findCountryByIso2(country) !== undefined;
}
/** The valid {@link ShippingRange} values, mirrored at runtime for {@link isShippingRange}. */
const SHIPPING_RANGES: readonly string[] = ['worldwide', 'domestic', 'international', 'local'];
/**
* Type guard to validate if a value is a valid shipping range.
*
* @category Typeguards
* @param shipping - The value to validate
* @returns Type predicate indicating if the value is a valid ShippingRange
* @example
* ```typescript
* isShippingRange("worldwide") // true
* isShippingRange("galactic") // false
* ```
* @source
*/
export function isShippingRange(shipping: unknown): shipping is ShippingRange {
return typeof shipping === 'string' && SHIPPING_RANGES.includes(shipping);
}
// The valid PaymentMethod values, mirrored at runtime for isPaymentMethod. The `satisfies`
// makes a value removed from the union a compile error here; an *addition* to the union can
// only be caught by the exhaustiveness test in typeGuards/__tests__/common.test.ts.
const PAYMENT_METHODS: readonly string[] = [
'mastercard',
'visa',
'paypal',
'ach',
'cash',
'check',
'crypto',
'moneyorder',
'ebay',
'amazon',
'ebayonly',
'amazononly',
'other',
] satisfies readonly PaymentMethod[];
/**
* Type guard to validate if a value is a valid payment method.
*
* @category Typeguards
* @param method - The value to validate
* @returns Type predicate indicating if the value is a valid PaymentMethod
* @example
* ```typescript
* isPaymentMethod("visa") // true
* isPaymentMethod("barter") // false
* ```
* @source
*/
export function isPaymentMethod(method: unknown): method is PaymentMethod {
return typeof method === 'string' && PAYMENT_METHODS.includes(method);
}
/**
* Checks if an object is empty.
*
* @category Typeguards
* @param obj - The object to check
* @returns True if the object is empty, false otherwise
* @example Empty object
* ```typescript
* isPopulatedObject({}) // Returns false
* ```
* @example Populated object
* ```typescript
* isPopulatedObject({ a: 1 }) // Returns true
* ```
* @example Null (which is considered an 'object' in JavaScript)
* ```typescript
* isPopulatedObject(null) // Returns false
* ```
* @source
*/
export function isPopulatedObject(obj: unknown): obj is Record<string, unknown> {
return (
typeof obj === 'object' &&
obj !== null &&
Array.isArray(obj) === false &&
Object.entries(obj).length > 0
);
}
/**
* Checks if an array is populated.
*
* @category Typeguards
* @param arr - The array to check
* @returns True if the array is populated, false otherwise
* @example Populated array
* ```typescript
* isPopulatedArray([1, 2, 3]) // Returns true
* ```
* @example Empty array
* ```typescript
* isPopulatedArray([]) // Returns false
* ```
* @source
*/
export function isPopulatedArray(arr: unknown): arr is unknown[] {
return Array.isArray(arr) === true && arr.length > 0;
}
const parsedPriceSchema = v.object({
currencyCode: v.string(),
currencySymbol: v.string(),
price: v.number(),
});
/**
* Type guard to validate if a value is a valid ParsedPrice object.
* Checks for the presence and correct types of currencyCode, currencySymbol, and price.
*
* @category Typeguards
* @param data - The value to validate
* @returns Type predicate indicating if the value is a valid ParsedPrice
* @example
* ```typescript
* const parsed = parsePrice('$1,234.56');
* if (isParsedPrice(parsed)) {
* console.log(parsed.currencyCode); // 'USD'
* }
* ```
* @source
*/
export function isParsedPrice(data: unknown): data is ParsedPrice {
return v.safeParse(parsedPriceSchema, data).success;
}
const quantityObjectSchema = v.object({
quantity: v.number(),
uom: v.string(),
});
/**
* Type guard to validate if a value is a valid QuantityObject.
* Checks for the presence and correct types of quantity (number) and uom (string).
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value is a valid QuantityObject
* @example
* ```typescript
* const qty = parseQuantity('100g');
* if (isQuantityObject(qty)) {
* console.log(`${qty.quantity}${qty.uom}`);
* }
* ```
* @source
*/
export function isQuantityObject(value: unknown): value is QuantityObject {
return v.safeParse(quantityObjectSchema, value).success;
}
/**
* Type guard to validate a CAS (Chemical Abstracts Service) number.
* CAS numbers follow a specific format (XXXXXXX-XX-X) and include a checksum digit.
*
* @category Typeguards
* @param cas - The CAS number to validate
* @returns Type predicate indicating if the value is a valid CAS number
* @example
* ```typescript
* isCAS('1234-56-6') // Returns true
* isCAS('50-00-0') // Returns true
* isCAS('1234-56-999') // Returns false
* ```
* @see https://www.cas.org/training/documentation/chemical-substances/checkdig
* @source
*/
export function isCAS(cas: unknown): cas is CAS<string> {
if (typeof cas !== 'string') return false;
const regex = RegExp(`^${CAS_REGEX.source}$`);
const match = cas.match(regex);
if (!match || !match.groups?.seg_a || !match.groups?.seg_b || !match.groups?.seg_checksum)
return false;
const segA = match.groups.seg_a;
const segB = match.groups.seg_b;
const segChecksum = match.groups.seg_checksum;
if (Number(segA) === 0 && Number(segB) === 0) return false;
const segABCalc = Array.from(segA + segB)
.map(Number)
.reverse()
.reduce((acc, curr, idx) => acc + (idx + 1) * curr, 0);
return segABCalc % 10 === Number(segChecksum);
}
/**
* Type guard to validate if a value is a full URL.
* Attempts to construct a URL object from the value.
*
* @category Typeguards
* @param val - The value to validate
* @returns Type predicate indicating if the value is a valid URL
* @example
* ```typescript
* isFullURL("https://www.google.com") // Returns true
* isFullURL("not a url") // Returns false
* ```
* @source
*/
export function isFullURL(val: unknown): val is URL {
try {
new URL(String(val));
return true;
} catch {
return false;
}
}
/**
* Type guard to validate if a value is a Request instance.
*
* @category Typeguards
* @param req - The value to validate
* @returns Type predicate indicating if the value is a Request
* @source
*/
export function isRequest(req: unknown): req is Request {
return req instanceof Request;
}
/**
* Type guard to check if a string is a valid SPIN_SPEED key.
* @category Typeguards
* @param key - The string to check
* @returns Type predicate indicating if the key is a valid SPIN_SPEED enum key
* @source
*/
export function isSpinSpeed(key: string): key is keyof typeof SPIN_SPEED {
return key in SPIN_SPEED;
}
/**
* Type guard to check if an EventTarget is an HTMLButtonElement.
* @category Typeguards
* @param target - The EventTarget to check
* @returns Type predicate indicating if the target is an HTMLButtonElement
* @source
*/
export function isButtonElement(target: EventTarget | null): target is HTMLButtonElement {
return target instanceof HTMLButtonElement;
}
/**
* Type guard to check if an EventTarget is an HTMLAnchorElement.
* @category Typeguards
* @param target - The EventTarget to check
* @returns Type predicate indicating if the target is an HTMLAnchorElement
* @source
*/
export function isAnchorElement(target: EventTarget | null): target is HTMLAnchorElement {
return target instanceof HTMLAnchorElement;
}
/**
* Type guard to check if an EventTarget is an HTMLInputElement.
* @category Typeguards
* @param target - The EventTarget to check
* @returns Type predicate indicating if the target is an HTMLInputElement
* @source
*/
export function isInputElement(target: EventTarget | null): target is HTMLInputElement {
return target instanceof HTMLInputElement;
}
// Memoized so the schema is built once on first validation rather than per call.
// This used to be load-bearing: reading the supplier list from `SupplierFactory`
// at module load hit a TDZ, because that pulled the circular path
// `SupplierFactory` → supplier classes → `SupplierBase` → `typeGuards/common`.
// Sourcing the names from a dependency-free constant removes that cycle — and
// keeps every supplier implementation out of the bundles of entry points (like
// the options page) that only need to validate settings.
let cachedUserSettingsSchema: ReturnType<typeof buildUserSettingsSchema> | null = null;
function buildUserSettingsSchema() {
// `v.coerce.number()` has no valibot equivalent; the numeric settings coerce
// via `Number` in a pipe (mirroring zod's `z.coerce.number()`), then apply the
// same int/nonnegative/positive constraints as `v.integer()` / `v.minValue()`.
const coercedNonnegative = v.pipe(v.unknown(), v.transform(Number), v.number(), v.minValue(0));
const optionalBoolean = v.optional(v.boolean());
const coercedNonnegativeInt = v.pipe(
v.unknown(),
v.transform(Number),
v.number(),
v.integer(),
v.minValue(0),
);
return v.object({
showHelp: optionalBoolean,
caching: v.optional(
v.object({
enabled: optionalBoolean,
doNotCacheEmptyResults: optionalBoolean,
ttlMinutes: v.optional(coercedNonnegative),
}),
),
priceTracking: v.optional(
v.object({
enabled: optionalBoolean,
maxDataPoints: v.optional(coercedNonnegativeInt),
}),
),
noCacheStatusCodes: v.optional(v.array(v.pipe(v.number(), v.integer(), v.minValue(1)))),
supplierSearchTimeBudgetSec: v.optional(coercedNonnegative),
currencyRate: v.optional(v.number()),
currency: v.optional(
v.pipe(
v.string(),
v.check((value) => isCurrencyCode(value), 'Invalid currency code'),
),
),
// Allow an empty string for the "None" location option.
location: v.optional(
v.pipe(
v.string(),
v.check((value) => value === '' || isCountryCode(value), 'Invalid country code'),
),
),
display: v.optional(
v.object({
theme: v.optional(v.picklist(['light', 'dark'])),
fontSize: v.optional(v.picklist(['small', 'medium', 'large'])),
openInTab: optionalBoolean,
}),
),
suppliers: v.optional(
v.object({
disabled: v.optional(v.array(v.picklist(SUPPLIER_CLASS_NAMES))),
excludeNonShipping: optionalBoolean,
resultLimit: v.optional(coercedNonnegativeInt),
}),
),
search: v.optional(
v.object({
groupProductVariants: optionalBoolean,
hideRestrictedProducts: optionalBoolean,
suggestAdvancedQuery: optionalBoolean,
invertSuppliersSelection: optionalBoolean,
}),
),
results: v.optional(
v.object({
autoHideEmpty: optionalBoolean,
hidden: v.optional(v.array(v.string())),
}),
),
fuzzScorerOverride: v.optional(v.string()),
remoteLogLevels: v.optional(v.array(v.picklist(REMOTE_LOG_LEVELS))),
});
}
function getUserSettingsSchema() {
if (!cachedUserSettingsSchema) {
cachedUserSettingsSchema = buildUserSettingsSchema();
}
return cachedUserSettingsSchema;
}
/**
* Type guard to validate if a value is a valid UserSettings object.
* Checks for the presence and correct types of all UserSettings properties.
*
* @category Typeguards
* @param settings - The value to validate
* @returns Type predicate indicating if the value is a valid UserSettings object
* @example
* ```typescript
* isValidUserSettings({ showHelp: true, caching: { enabled: true }, currencyRate: 1.0, currency: "USD", location: "US" }) // Returns true
* isValidUserSettings({ showHelp: "test", caching: { enabled: true }, currencyRate: 1.0, currency: "USD", location: "US" }) // Returns false
* ```
* @source
*/
export function isValidUserSettings(settings: unknown): settings is UserSettings {
const check = v.safeParse(getUserSettingsSchema(), settings);
if (!check.success) {
logger.warn('isValidUserSettings| The user settings are invalid', {
settings,
issues: addActualValueToIssues(check.issues, settings),
});
}
return check.success;
}
/**
* Check if a value is a plain object or array.
* @category Typeguards
* @param v - The value to check.
* @returns True if the value is a plain object or array, false otherwise.
* @example
* ```typescript
* const obj = { a: 1, b: 2, c: 3 };
* isPlainContainer(obj) // true
* isPlainContainer([1, 2, 3]) // true
* isPlainContainer(1) // false
* isPlainContainer("hello") // false
* isPlainContainer(null) // false
* isPlainContainer(undefined) // false
* ```
* @source
*/
export function isPlainContainer(v: unknown): v is object {
if (v == null || typeof v !== 'object') return false;
if (Array.isArray(v)) return true;
const proto = Object.getPrototypeOf(v);
return proto === Object.prototype || proto === null;
}
/**
* Type guard to validate if a value is a valid SMILES string.
* Checks if the value is a string and if it is a valid SMILES string.
*
* @category Typeguards
* @param smiles - The value to validate
* @returns Type predicate indicating if the value is a valid SMILES string
* @source
*/
export function isSmiles(smiles: unknown): smiles is Smiles<string> {
return looksLikeSmiles(String(smiles));
}
/**
* Type guard to validate if a value is a usable IUPAC name (a non-empty string).
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value is a valid IUPAC name
* @example
* ```typescript
* isIupacName("dipotassium;oxalate") // Returns true
* isIupacName("") // Returns false
* ```
* @source
*/
export function isIupacName(value: unknown): value is IupacName<string> {
return typeof value === 'string' && value.trim().length > 0;
}
/**
* Type guard to validate if a value is a PubChem Compound ID (a positive integer).
* Numeric strings are accepted and coerced before validation.
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value is a valid PubChem CID
* @example
* ```typescript
* isPubChemCID(11413) // Returns true
* isPubChemCID("11413") // Returns true
* isPubChemCID(0) // Returns false
* isPubChemCID("abc") // Returns false
* ```
* @source
*/
export function isPubChemCID(value: unknown): value is PubChemCID {
if (typeof value !== 'number' && typeof value !== 'string') return false;
const num = typeof value === 'string' ? Number(value) : value;
return Number.isInteger(num) && num > 0;
}
/**
* Normalizes a value already validated by {@link isPubChemCID} into the branded
* {@link PubChemCID} number, coercing a numeric string to its number form. The
* assertion is unavoidable and lives here as the single sanctioned construction
* point: a nominal brand can't be minted from `Number()` without one.
* @category Typeguards
* @param value - A number or numeric string already confirmed by {@link isPubChemCID}.
* @returns The CID as a branded number.
* @example
* ```typescript
* if (isPubChemCID(raw)) product.pubchemId = toPubChemCID(raw);
* toPubChemCID("11413"); // 11413
* ```
* @source
*/
export function toPubChemCID(value: number | string): PubChemCID {
return Number(value) as PubChemCID;
}
/**
* Type guard to validate if a value is an InChIKey.
* An InChIKey is three hyphen-separated uppercase-letter blocks of 14, 10, and 1 characters.
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value is a valid InChIKey
* @example
* ```typescript
* isInChIKey("IRXRGVFLQOSHOH-UHFFFAOYSA-L") // Returns true
* isInChIKey("not-an-inchikey") // Returns false
* ```
* @source
*/
export function isInChIKey(value: unknown): value is InChIKey<string> {
return typeof value === 'string' && /^[A-Z]{14}-[A-Z]{10}-[A-Z]$/.test(value);
}
/**
* Type guard to validate if a value is an InChI string. Accepts values with or without the
* leading `InChI=` prefix (the version layer `1S/...` or `1/...` must follow).
*
* @category Typeguards
* @param value - The value to validate
* @returns Type predicate indicating if the value is a valid InChI string
* @example
* ```typescript
* isInChI("InChI=1S/H2O/h1H2") // Returns true
* isInChI("1S/C2H2O4.2K/c3-1(4)2(5)6;;/h(H,3,4)(H,5,6);;/q;2*+1/p-2") // Returns true
* isInChI("not an inchi") // Returns false
* ```
* @source
*/
export function isInChI(value: unknown): value is InChI<string> {
return typeof value === 'string' && /^(InChI=)?1S?\/.+/.test(value);
}
|