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 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | 10x 2x 4x 3x 6x 6x 41x 25x 37x 3x 111x 10x 17x 10x 10x 7x 16x 16x 23x 16x 109x 4x 4x 3x 4x 4x 89x 83x 7x 3x 21x 18x 3x 14x 13x 14x 14x 30x 30x 23x 23x 1x 9x 9x 7x 14x 6x 11x 15x 15x 15x 15x 15x 15x 12x 6x 6x 6x 7x 7x 7x 6x 1x 98x 5x 376x 4x 4x 4x 2x 4x 4x 68x 3x 21x 42x 42x 42x 11x 1x 1x 3x 3x 3x 3x 9x 18x 9x 27x 27x 9x 7x 7x 5x 1x 12x 12x 12x 20x 20x 20x 12x 39x 36x 33x 33x 33x 7x 7x 7x 7x 16x | // @wc-ignore-file
import fetchProgress from 'fetch-progress';
/**
* @template {string} K
* @template {any} VIn
* @template {any} VOut
* @param {Record<K, VIn>} subject
* @param {(value: VIn) => VOut} mapper
* @returns {Record<K, NoInfer<VOut>>}
*/
export function mapValues(subject, mapper) {
// @ts-expect-error
return Object.fromEntries(Object.entries(subject).map(([key, value]) => [key, mapper(value)]));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('mapValues', () => {
expect(mapValues({ a: 1, b: 2 }, (v) => v + 1)).toEqual({ a: 2, b: 3 });
expect(mapValues({ a: 1, b: 2 }, (v) => v.toString())).toEqual({ a: '1', b: '2' });
});
}
/**
* @template {string} KIn
* @template {string} KOut
* @template {any} V
* @param {Record<KIn, V>} subject
* @param {(key: KIn, value: V) => KOut} mapper
* @returns {Record<KOut, V>}
*/
export function mapKeys(subject, mapper) {
// @ts-expect-error
return Object.fromEntries(
Object.entries(subject).map(([key, value]) => [
mapper(/** @type {KIn} */ (key), value),
value
])
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('mapKeys', () => {
expect(mapKeys({ a: 1, b: 2 }, (k) => k.toUpperCase())).toEqual({ A: 1, B: 2 });
expect(mapKeys({ a: 1, b: 2 }, (k) => k + k)).toEqual({ aa: 1, bb: 2 });
});
}
/**
* Maps values of an object, and filters out entries with nullable values from the result
* @template {string} K
* @template {any} VIn
* @template {any} VOut
* @param {Record<K, VIn>} subject
* @param {(value: VIn) => VOut} mapper
* @returns {Record<K, NoInfer<NonNullable<VOut>>>}
*/
export function mapValuesNoNullables(subject, mapper) {
return Object.fromEntries(
Object.entries(subject)
.map(([key, value]) => [key, mapper(value)])
.filter(([, value]) => value !== null && value !== undefined)
);
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('mapValuesNoNullables', () => {
test('without any nullables', () => {
expect(mapValuesNoNullables({ a: 1, b: 2 }, (v) => v + 1)).toEqual({ a: 2, b: 3 });
});
test('with nullables', () => {
expect(mapValuesNoNullables({ a: 1, b: null }, (v) => (v ? v + 1 : v))).toEqual({
a: 2
});
});
test('with only nullables', () => {
expect(mapValuesNoNullables({ a: 1, b: 2 }, (v) => (v % 2 ? null : undefined))).toEqual(
{}
);
});
});
}
/**
* @template {string} K
* @param {Record<K, unknown>} subject
* @returns {K[]}
*/
export function keys(subject) {
// @ts-expect-error
return Object.keys(subject);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('keys', () => {
expect(keys({ a: 1, b: 2 })).toEqual(['a', 'b']);
expect(keys({})).toEqual([]);
});
}
/**
* @template {string} K
* @template {any} V
* @param {Array<[K, V]>} subject
* @returns {Record<K, V>}
*/
export function fromEntries(subject) {
// @ts-expect-error
return Object.fromEntries(subject);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('fromEntries', () => {
expect(
fromEntries([
['a', 1],
['b', 2]
])
).toEqual({ a: 1, b: 2 });
expect(fromEntries([])).toEqual({});
});
}
/**
* @template {string} K
* @template {any} V
* @param {Record<K, V>} subject
* @returns {Array<[K, V]>}
*/
export function entries(subject) {
// @ts-expect-error
return Object.entries(subject);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('entries', () => {
expect(entries({ a: 1, b: 2 })).toEqual([
['a', 1],
['b', 2]
]);
expect(entries({})).toEqual([]);
});
}
/**
* @template {string} K
* @template {string} V
* @param {Record<K, V>} subject
* @returns {Record<V, K>}
*/
export function invertRecord(subject) {
return fromEntries(entries(subject).map(([key, value]) => [value, key]));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('invertRecord', () => {
expect(invertRecord({ a: '1', b: '2', c: 'd' })).toEqual({ 1: 'a', 2: 'b', d: 'c' });
expect(invertRecord({})).toEqual({});
});
}
/**
* Checks that a value is included in a list of values
* @template {string} T
* @param {string} value
* @param {T[]} values
* @returns {value is T}
*/
export function oneOf(value, values) {
// @ts-expect-error
return values.includes(value);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('oneOf', () => {
expect(oneOf('a', ['a', 'b', 'c'])).toBe(true);
expect(oneOf('d', ['a', 'b', 'c'])).toBe(false);
});
}
/**
*
* @template {string} T
* @template {T} U
* @param {U} value
* @param {T[]} values
* @returns {values is [...Omit<T, U>[], U, ...Omit<T, U>[]]}
*/
export function hasOnce(value, values) {
return values.filter((v) => v === value).length === 1;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('hasOnce', () => {
expect(hasOnce('a', ['a', 'b', 'c'])).toBe(true);
// @ts-expect-error
expect(hasOnce('d', ['a', 'b', 'c'])).toBe(false);
expect(hasOnce('a', ['a', 'b', 'c', 'a'])).toBe(false);
});
}
/**
*
* @param {...any} args
* @returns {boolean}
*/
export function xor(...args) {
if (args.length === 0) return false;
const [first, ...rest] = args;
return xor(...rest) !== Boolean(first);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('xor', () => {
expect(xor()).toBe(false);
expect(xor(true)).toBe(true);
expect(xor(false)).toBe(false);
expect(xor(true, false)).toBe(true);
expect(xor(false, true)).toBe(true);
expect(xor(true, true)).toBe(false);
expect(xor(false, false)).toBe(false);
});
}
/**
* @param {...any} args
* @returns {boolean}
*/
export function or(...args) {
return args.some(Boolean);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('or', () => {
expect(or()).toBe(false);
expect(or(true)).toBe(true);
expect(or(false)).toBe(false);
expect(or(true, false)).toBe(true);
expect(or(false, true)).toBe(true);
expect(or(true, true)).toBe(true);
expect(or(false, false)).toBe(false);
});
}
/**
* Pick only some keys from an object
* @template {string & keyof Obj} KeysOut
* @template {*} Obj
* @param {Obj} subject
* @param {...KeysOut} keys
* @returns {Pick<Obj, KeysOut>}
*/
export function pick(subject, ...keys) {
// We're not using fromEntries and entries with a filter, because Object.fromEntries does not return $derived or $state fields from classes
// see https://svelte.dev/playground/32a7d1c8995f45b49f01b7ae86fef7bd?version=5.38.7
const result = /** @type {Pick<Obj, KeysOut>} */ ({});
for (const key of keys) {
result[key] = subject[key];
}
return result;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('pick', () => {
expect(pick({ a: 1, b: 2 }, 'a')).toEqual({ a: 1 });
expect(pick({ a: 1, b: 2 }, 'b')).toEqual({ b: 2 });
expect(pick({ a: 1, b: 2 }, 'a', 'b')).toEqual({ a: 1, b: 2 });
// @ts-expect-error
expect(pick({ a: 1, b: 2 }, 'c')).toEqual({});
class Test {
/** @type {number} */
id = 0;
/** @type {string} */
name = '';
}
const testZero = new Test();
const testOne = new Test();
testOne.id = 1;
expect(pick(testZero, 'id')).toEqual({ id: 0 });
expect(pick(testOne, 'id')).toEqual({ id: 1 });
expect(pick(testOne, 'name')).toEqual({ name: '' });
});
}
/**
* Omit some keys from an object
* @template {string} KeysIn
* @template {KeysIn} KeysOut
* @template {any} V
* @param {Record<KeysIn, V>} subject
* @param {...KeysOut} keys
* @returns {Record<Exclude<KeysIn, KeysOut>, V>}
*/
export function omit(subject, ...keys) {
return fromEntries(entries(subject).filter(([key]) => !oneOf(key, keys)));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('omit', () => {
expect(omit({ a: 1, b: 2 }, 'a')).toEqual({ b: 2 });
expect(omit({ a: 1, b: 2 }, 'b')).toEqual({ a: 1 });
expect(omit({ a: 1, b: 2 }, 'a', 'b')).toEqual({});
expect(omit({ a: 1, b: 2 }, 'c')).toEqual({ a: 1, b: 2 });
});
}
/**
*
* @param {*} str
* @returns
*/
export function safeJSONParse(str) {
try {
return JSON.parse(str?.toString() ?? '');
} catch {
return undefined;
}
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('safeJSONParse', () => {
expect(safeJSONParse('{"a":1}')).toEqual({ a: 1 });
expect(safeJSONParse('{"a":1')).toBeUndefined();
expect(safeJSONParse(null)).toBeUndefined();
expect(safeJSONParse(undefined)).toBeUndefined();
});
}
/**
* @param {*} value
*/
export function safeJSONStringify(value) {
try {
return JSON.stringify(value);
} catch {
return undefined;
}
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('safeJSONStringify', () => {
expect(safeJSONStringify({ a: 1 })).toEqual('{"a":1}');
expect(safeJSONStringify(undefined)).toBeUndefined();
expect(safeJSONStringify(null)).toBe('null');
expect(safeJSONStringify(Symbol('feur'))).toBeUndefined();
});
}
/**
* See https://github.com/microsoft/TypeScript/issues/19954
* @param {number} value
* @returns {-1|0|1}
*/
export function sign(value) {
// @ts-expect-error
return Math.sign(value);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('sign', () => {
expect(sign(1)).toBe(1);
expect(sign(-1)).toBe(-1);
expect(sign(0)).toBe(0);
expect(sign(-0)).toBe(-0); // 💀💀💀
expect(sign(NaN)).toBeNaN();
expect(sign(6732)).toBe(1);
expect(sign(-667)).toBe(-1);
expect(sign(Infinity)).toBe(1);
expect(sign(-Infinity)).toBe(-1);
});
}
/**
* @param {number} value
* @param {number} min
* @param {number} max
* @returns {number}
*/
export function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('clamp', () => {
expect(clamp(1, 0, 2)).toBe(1);
expect(clamp(-1, 0, 2)).toBe(0);
expect(clamp(3, 0, 2)).toBe(2);
expect(clamp(0, 0, 2)).toBe(0);
expect(clamp(-67, -5, 2)).toBe(-5);
});
}
/**
* @template {*} T
* @typedef {{[K in keyof T]: Iterable<T[K]>}} ToIterables
*/
/**
* @template {any[]} T
* @param {...ToIterables<T>} arrays
* @yields {T}
*/
export function* zip(...arrays) {
// Get iterators for all of the iterables.
const iterators = arrays.map((i) => i[Symbol.iterator]());
while (true) {
// Advance all of the iterators.
const results = iterators.map((i) => i.next());
// If any of the iterators are done, we should stop.
if (results.some(({ done }) => done)) {
break;
}
// We can assert the yield type, since we know none
// of the iterators are done.
yield /** @type {T} */ (results.map(({ value }) => value));
}
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('zip', () => {
test('works with 2 iterators', () => {
expect([...zip([1, 2], ['a', 'b'])]).toEqual([
[1, 'a'],
[2, 'b']
]);
});
test('works with 3 iterators', () => {
expect([...zip([1, 2], ['a', 'b'], [true, false])]).toEqual([
[1, 'a', true],
[2, 'b', false]
]);
});
test('works with asymmetrically-sized iterators', () => {
expect([...zip([1, 2, 3], [[], []])]).toEqual([
[1, []],
[2, []]
]);
});
});
}
/**
* @template {*} T
* @param {T[]} array
* @param {(item: T) => string|number} [key]
* @returns {T[]}
*/
// @ts-expect-error key should be non-optional if T is not string|number
export function unique(array, key = (x) => x) {
const seen = new Set();
return array.filter((item) => {
const k = key(item);
if (seen.has(k)) return false;
seen.add(k);
return true;
});
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('unique', () => {
expect(unique([1, 2, 3, 1, 2])).toEqual([1, 2, 3]);
expect(unique(['a', 'b', 'c', 'a', 'b'])).toEqual(['a', 'b', 'c']);
expect(unique([])).toEqual([]);
expect(unique([{ id: 1 }, { id: 2 }, { id: 1 }], (o) => o.id)).toEqual([
{ id: 1 },
{ id: 2 }
]);
expect(unique([{ id: 1 }, { id: 2 }, { id: 1 }], (o) => o.id.toString())).toEqual([
{ id: 1 },
{ id: 2 }
]);
});
}
/**
* @param {Uint8Array} uint8Array
* @returns {ArrayBuffer}
*/
export function uint8ArrayToArrayBuffer(uint8Array) {
return uint8Array.buffer.slice(
uint8Array.byteOffset,
uint8Array.byteOffset + uint8Array.byteLength
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('uint8ArrayToArrayBuffer', () => {
const uint8Array = new Uint8Array([1, 2, 3]);
const arrayBuffer = uint8ArrayToArrayBuffer(uint8Array);
expect(arrayBuffer).toBeInstanceOf(ArrayBuffer);
expect(new Uint8Array(arrayBuffer)).toEqual(uint8Array);
});
}
/**
* extension is all the last dotted parts: thing.tar.gz is [thing, tar.gz]
* @param {string} filename
* @returns [string, string] [filename without extension, extension]
*/
export function splitFilenameOnExtension(filename) {
const match = filename.match(/^([^.]+)\.(.+)$/);
if (!match) return [filename, ''];
return [match[1], match[2]];
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('splitFilenameOnExtension', () => {
expect(splitFilenameOnExtension('file.txt')).toEqual(['file', 'txt']);
expect(splitFilenameOnExtension('file')).toEqual(['file', '']);
expect(splitFilenameOnExtension('file.tar.gz')).toEqual(['file', 'tar.gz']);
});
}
/**
* @template Item
* @param {((item: Item) => string|number|undefined) | (keyof Item & string) } key function to create the comparator function with. Should return a string (will be used with localeCompare) or a number (will be subtracted)
*/
export function compareBy(key) {
if (typeof key === 'string') {
return compareBy((item) => item[key]);
}
/**
* @param {Item} a
* @param {Item} b
* @returns {number}
*/
return (a, b) => {
const aKey = key(a);
const bKey = key(b);
Iif (aKey === undefined && bKey === undefined) return 0;
Iif (aKey === undefined) return -1;
Iif (bKey === undefined) return 1;
if (aKey === bKey) return 0;
if (typeof aKey === 'string' && typeof bKey === 'string') {
return aKey.localeCompare(bKey);
}
Eif (typeof aKey === 'number' && typeof bKey === 'number') {
return aKey - bKey;
}
return aKey.toString().localeCompare(bKey.toString());
};
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('compareBy', () => {
test('.sort works', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' }
];
expect([...items].sort(compareBy((i) => i.id))).toEqual([
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' }
]);
expect([...items].sort(compareBy((i) => i.name))).toEqual([
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' }
]);
});
test('it works', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' }
];
expect(compareBy((i) => i.id)(items[0], items[1])).toBe(1);
expect(compareBy((i) => i.id)(items[1], items[0])).toBe(-1);
expect(compareBy((i) => i.id)(items[0], items[0])).toBe(0);
expect(compareBy((i) => i.name)(items[0], items[1])).toBe(1);
expect(compareBy((i) => i.name)(items[1], items[0])).toBe(-1);
expect(compareBy((i) => i.name)(items[0], items[0])).toBe(0);
});
test('it works with key strings', () => {
const items = [
{ id: 2, name: 'b' },
{ id: 1, name: 'a' },
{ id: 3, name: 'c' }
];
expect(compareBy('id')(items[0], items[1])).toBe(1);
expect(compareBy('name')(items[1], items[0])).toBe(-1);
expect(compareBy('id')(items[0], items[0])).toBe(0);
});
});
}
/**
* Add a v= query parameter to the URL to force the browser to reload the resource, using Date.now() as the value
* @template {string|URL} T
* @param {T} url
* @returns {T}
*/
export function cachebust(url) {
const parsedUrl = new URL(url);
// TODO use x-cigale-cache-bust instead of v
parsedUrl.searchParams.set('v', Date.now().toString());
if (typeof url === 'string') {
// @ts-expect-error
return parsedUrl.toString();
}
// @ts-expect-error
return parsedUrl;
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('cachebust', () => {
test('without any query params', () => {
const url = 'https://example.com/resource';
const cachebustedUrl = cachebust(url);
expect(URL.canParse(cachebustedUrl)).toBeTruthy();
expect([...new URL(cachebustedUrl).searchParams.entries()]).toEqual([
['v', expect.stringMatching(/^\d+$/)]
]);
});
test('with existing query params', () => {
const url = 'https://example.com/resource?param=value';
const cachebustedUrl = cachebust(url);
expect(URL.canParse(cachebustedUrl)).toBeTruthy();
expect(new URL(cachebustedUrl).searchParams.get('param')).toBe('value');
expect(new URL(cachebustedUrl).searchParams.get('v')).toMatch(/^\d+$/);
});
test('with a parsed URL', () => {
const url = new URL('https://example.com/resource?param=value');
const cachebustedUrl = cachebust(url);
expect(cachebustedUrl).toBeInstanceOf(URL);
expect(cachebustedUrl.searchParams.get('param')).toBe('value');
expect(cachebustedUrl.searchParams.get('v')).toMatch(/^\d+$/);
});
});
}
/**
* Semi-open range [start=0, end)
* @param {number} startOrEnd
* @param {number|undefined} [end]
* @returns {number[]}
*/
export function range(startOrEnd, end = undefined) {
if (end === undefined) {
return Array.from({ length: startOrEnd }, (_, i) => i);
}
return Array.from({ length: end - startOrEnd }, (_, i) => i + startOrEnd);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('range', () => {
expect(range(5)).toEqual([0, 1, 2, 3, 4]);
expect(range(2, 5)).toEqual([2, 3, 4]);
expect(range(5, 2)).toEqual([]);
expect(range(3, 3)).toEqual([]);
expect(range(3, 4)).toEqual([3]);
});
}
/**
* @param {typeof import('$lib/schemas/common.js').HTTPRequest.infer} request
* @param {object} [options]
* @param {''|'model'} [options.cacheAs=""]
* @param {import('fetch-progress').FetchProgressInitOptions['onProgress']} [options.onProgress]
*/
export async function fetchHttpRequest(request, { cacheAs = '', onProgress } = {}) {
let url = new URL(typeof request === 'string' ? request : request.url);
const options = typeof request === 'string' ? { headers: {} } : request;
if (cacheAs) {
url.searchParams.set('x-cigale-cache-as', cacheAs);
}
Iif (onProgress) return fetch(url, options).then(fetchProgress({ onProgress }));
return fetch(url, options);
}
if (import.meta.vitest) {
const { it, describe, expect, vi } = import.meta.vitest;
describe('fetchHttpRequest', async () => {
it('works with a simple URL string', async () => {
const fetchMock = vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
)
);
vi.stubGlobal('fetch', fetchMock);
const response = await fetchHttpRequest(
'https://example.com/api?q=test&another=param',
{
cacheAs: 'model'
}
);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
new URL('https://example.com/api?q=test&another=param&x-cigale-cache-as=model'),
{ headers: {} }
);
const data = await response.json();
expect(data).toEqual({ success: true });
// Clean up
vi.unstubAllGlobals();
});
it('works with a full request object', async () => {
const fetchMock = vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
)
);
vi.stubGlobal('fetch', fetchMock);
const request = /** @type {const} */ ({
url: 'https://example.com/api',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
});
const response = await fetchHttpRequest(request, { cacheAs: 'model' });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
new URL('https://example.com/api?x-cigale-cache-as=model'),
request
);
const data = await response.json();
expect(data).toEqual({ success: true });
// Clean up
vi.unstubAllGlobals();
});
});
}
/** @param {Iterable<number>} values */
export function sum(values) {
return [...values].reduce((acc, cur) => acc + cur, 0);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('sum', () => {
expect(sum([1, 2, 3])).toBe(6);
expect(sum([])).toBe(0);
expect(sum([-1, 1])).toBe(0);
});
}
/** @param {number[]} values */
export function avg(values) {
return sum(values) / values.length;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('avg', () => {
expect(avg([1, 2, 3])).toBe(2);
expect(avg([1, 1, 1])).toBe(1);
expect(avg([1, 3])).toBe(2);
});
}
/**
* @template {any} T
* @param {T} value
* @returns {value is NonNullable<T>}
*/
export function nonnull(value) {
return value !== null && value !== undefined;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('nonnull', () => {
expect(nonnull(1)).toBe(true);
expect(nonnull(0)).toBe(true);
expect(nonnull('a')).toBe(true);
expect(nonnull('')).toBe(true);
expect(nonnull(true)).toBe(true);
expect(nonnull(false)).toBe(true);
expect(nonnull({})).toBe(true);
expect(nonnull([])).toBe(true);
expect(nonnull(null)).toBe(false);
expect(nonnull(undefined)).toBe(false);
});
}
/**
* @param {number} value
* @param {number} decimals
* @returns {number}
*/
export function round(value, decimals = 0) {
Iif (decimals < 0) throw new Error('decimals must be non-negative');
const factor = Math.pow(10, decimals);
return Math.round(value * factor) / factor;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('round', () => {
expect(round(1.2345)).toBe(1);
expect(round(1.5)).toBe(2);
expect(round(1.2345, 2)).toBe(1.23);
expect(round(1.2355, 2)).toBe(1.24);
expect(round(-1.2355, 2)).toBe(-1.24);
expect(round(-1.2345, 2)).toBe(-1.23);
expect(round(1.23456789, 5)).toBe(1.23457);
expect(round(1.23456789, 8)).toBe(1.23456789);
expect(round(1.23456789, 10)).toBe(1.23456789);
});
}
/**
*
* @param {object} param0 offset coords from the given rect
* @param {number} param0.offsetX
* @param {number} param0.offsetY
* @param {DOMRect} rect
* @param {number} leeway how many pixels to consider still "inside" the rect even if it's outside
* @returns
*/
export function insideBoundingClientRect({ offsetX, offsetY }, rect, leeway = 0) {
return (
offsetX >= -leeway &&
offsetX <= rect.width + leeway &&
offsetY >= -leeway &&
offsetY <= rect.height + leeway
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('insideBoundingClientRect', () => {
const rect = new DOMRect(0, 0, 100, 100);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: 50 }, rect)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 0, offsetY: 0 }, rect)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 100, offsetY: 100 }, rect)).toBe(true);
expect(insideBoundingClientRect({ offsetX: -1, offsetY: 50 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: -1 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: 101, offsetY: 50 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: 101 }, rect)).toBe(false);
expect(insideBoundingClientRect({ offsetX: -1, offsetY: 50 }, rect, 2)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: -1 }, rect, 2)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 101, offsetY: 50 }, rect, 2)).toBe(true);
expect(insideBoundingClientRect({ offsetX: 50, offsetY: 101 }, rect, 2)).toBe(true);
});
}
/**
*
* @param {string} contentType
* @returns {contentType is 'application/zip' | 'application/x-zip-compressed' | 'application/x-zip' }
*/
export function isZip(contentType) {
return (
contentType === 'application/zip' ||
contentType === 'application/x-zip-compressed' ||
contentType === 'application/x-zip'
);
}
/**
* @template T
* @param {string} tag
* @param {T} expr
* @returns {T}
*/
export function logexpr(tag, expr) {
// oxlint-disable-next-line no-console
console.log(`{${tag}}`, expr);
return expr;
}
/**
* Outputs a [0, 1] progress value based on the progress of several weighted ordered parts. A value for a part assumes that all other parts defined beforehand have completed. Weights are in [0, 1], and the last part can let the weight be what sums with the rest to 1
*
* @example
* ```
* // download part represents 70% of the total time, decompression 20%, and parsing the rest
* const splitProgress = progressSplitter('download', 0.7, 'decompression', 0.2, 'parsing');
*
* // Download halfway there
* splitProgress('download', 0.5) // 0.35
* // Download finished, decompression 10% there
* splitProgress('decompression', 0.1) // 0.72 = 0.7 + 0.2 * 0.1
* // Decompression finished, parsing 50% there
* splitProgress('parsing', 0.5) // 0.85 = 0.7 + 0.2 + 0.1 * 0.5 = 0.7 + 0.2 + (0.7 + 0.2 - 1) * 0.5
* // Parsing finished
* splitProgress('parsing', 1) // 1 = 0.7 + 0.2 + 0.1 * 1 = 0.7 + 0.2 + (0.7 + 0.2 - 1) * 1
* ```
* @template {string} PartName
* @param {...(PartName | number)} layout
* @returns {(part: PartName, progress: number) => number}
*/
export function progressSplitter(...layout) {
/** @type {Array<[PartName, number]>} */
let parts = [];
for (let i = 0; i < layout.length; i += 2) {
const name = /** @type {PartName} */ (layout[i]);
const weight = /** @type {number} */ (layout[i + 1] ?? 1 - sum(parts.map(([, w]) => w)));
parts.push([name, weight]);
}
return (part, progress) => {
let total = 0;
const partIndex = parts.findIndex(([name]) => name === part);
for (const [i, [_, weight]] of parts.entries()) {
if (i < partIndex) total += weight;
if (i === partIndex) total += weight * progress;
}
return total;
};
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('progressSplitter', () => {
const splitProgress = progressSplitter('download', 0.7, 'decompression', 0.2, 'parsing');
const expectations = /** @type {const} */ ([
['download', 0, 0],
['download', 0.5, 0.35],
['download', 1, 0.7],
['decompression', 0, 0.7],
['decompression', 0.5, 0.8],
['decompression', 1, 0.9],
['parsing', 0, 0.9],
['parsing', 0.5, 0.95],
['parsing', 1, 1]
]);
for (const [phase, input, expected] of expectations) {
expect
.soft(splitProgress(phase, input), `with (${phase}, ${input})`)
.toBeCloseTo(expected, 15);
}
});
}
/**
* Replaces accents and punctuations with dashes, lowercases, and replaces accents with ASCII equivalents.
* Throws if the result is still not ASCII (e.g. CJK characters, we don't have transliteration tables for everything)
* @param {string} text
*/
export function slugify(text) {
const result = text
.normalize(/* @wc-ignore */ 'NFD') // separate accent from letter
.replace(/[\u0300-\u036f]/g, '') // remove all accents
.replace(/[^\w\s-]/g, '') // remove all non-word characters (except spaces and dashes)
.trim()
.replace(/[\s_-]+/g, '-') // replace spaces and underscores with a single dash
.replace(/^-+|-+$/g, '') // remove leading and trailing dashes
.toLowerCase();
if (!result) throw new Error(`Cannot slugify "${text}" (result is empty)`);
return result;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('slugify', () => {
expect(slugify('Hello World!')).toBe('hello-world');
expect(slugify(' Leading and trailing spaces ')).toBe('leading-and-trailing-spaces');
expect(slugify('Multiple spaces')).toBe('multiple-spaces');
expect(slugify('Special #$&* Characters')).toBe('special-characters');
expect(slugify('Accented éà üö Characters')).toBe('accented-eauo-characters');
expect(() => slugify('')).toThrow();
expect(() => slugify('ä½ å¥½')).toThrow();
});
}
/**
* Throws an error with the given message
* Useful to throw inside expressions
* Example: `const value = possiblyNull ?? throws('value is null')`
* @param {string} message
* @returns {never}
*/
export function throws(message) {
throw new Error(message);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('throws', () => {
expect(() => throws('test error')).toThrow('test error');
});
}
/**
* @template T
* @template [K=string]
* @template [V=T]
* @param {Iterable<T>} array
* @param {(item: T) => K} key
* @param {(item: T) => V} [valueMapper]
* @returns {Map<K, V[]>}
*/
export function groupBy(array, key, valueMapper) {
Iif ('groupBy' in Map && !valueMapper) {
// @ts-expect-error
return Map.groupBy(array, key);
}
const map = new Map();
for (const item of array) {
const k = key(item);
if (!map.has(k)) map.set(k, []);
map.get(k).push(valueMapper ? valueMapper(item) : item);
}
return map;
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('groupBy', () => {
expect(groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? 'even' : 'odd'))).toEqual(
new Map([
['odd', [1, 3, 5]],
['even', [2, 4]]
])
);
expect(
groupBy(
[
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' }
],
(user) => (user.id % 2 === 0 ? 'even' : 'odd'),
(user) => user.name
)
).toEqual(
new Map([
['odd', ['Alice', 'Charlie']],
['even', ['Bob', 'David']]
])
);
});
}
/**
* Returns a LAB color-mix placing the value on the color scale made from the given color stops
* Basically, it's like making a linear gradient and picking a color on it, where the 1 is the end of the gradient and 0 is the beginning
* @param {number} value between 0 and 1
* @param {...string} stops CSS color variable names (without the -- in front) representing the color gradient scale
*/
export function gradientedColor(value, ...stops) {
if (value >= 1) return `var(--${stops.at(-1)})`;
if (value <= 0) return `var(--${stops[0]})`;
const scale = stops.length - 1;
const stop = Math.floor(value * scale);
return `color-mix(
in lab,
var(--${stops[stop + 1]})
${round((value * scale - stop) * 100, 2)}%,
var(--${stops[stop]})
)`
.replaceAll('\n', '')
.replaceAll(/\s+/g, ' ')
.replaceAll('( ', '(')
.replaceAll(' )', ')');
}
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('gradientedColor', () => {
test('two colors', () => {
expect.soft(gradientedColor(0, 'red', 'blue')).toBe('var(--red)');
expect.soft(gradientedColor(1, 'red', 'blue')).toBe('var(--blue)');
const expectations = /** @type {const} */ ([
[0.1, 'blue', '10%', 'red'],
[0.2, 'blue', '20%', 'red'],
[0.25, 'blue', '25%', 'red'],
[0.3, 'blue', '30%', 'red'],
[0.4, 'blue', '40%', 'red'],
[0.5, 'blue', '50%', 'red'],
[0.6, 'blue', '60%', 'red'],
[0.7, 'blue', '70%', 'red'],
[0.75, 'blue', '75%', 'red'],
[0.8, 'blue', '80%', 'red'],
[0.9, 'blue', '90%', 'red']
]);
for (const [input, color, percent, otherColor] of expectations) {
expect
.soft(gradientedColor(input, 'red', 'blue'), `with ${input}`)
.toBe(`color-mix(in lab, var(--${color}) ${percent}, var(--${otherColor}))`);
}
});
test('three colors', () => {
expect.soft(gradientedColor(0, 'red', 'yellow', 'blue')).toBe('var(--red)');
expect.soft(gradientedColor(1, 'red', 'yellow', 'blue')).toBe('var(--blue)');
const expectations = /** @type {const} */ ([
[0.1, 'yellow', '20%', 'red'],
[0.2, 'yellow', '40%', 'red'],
[0.25, 'yellow', '50%', 'red'],
[0.3, 'yellow', '60%', 'red'],
[0.4, 'yellow', '80%', 'red'],
[0.5, 'blue', '0%', 'yellow'],
[0.6, 'blue', '20%', 'yellow'],
[0.7, 'blue', '40%', 'yellow'],
[0.75, 'blue', '50%', 'yellow'],
[0.8, 'blue', '60%', 'yellow'],
[0.9, 'blue', '80%', 'yellow']
]);
for (const [input, color, percent, otherColor] of expectations) {
expect
.soft(gradientedColor(input, 'red', 'yellow', 'blue'), `with ${input}`)
.toBe(`color-mix(in lab, var(--${color}) ${percent}, var(--${otherColor}))`);
}
});
test('four colors', () => {
expect.soft(gradientedColor(0, 'red', 'yellow', 'green', 'blue')).toBe('var(--red)');
expect.soft(gradientedColor(1, 'red', 'yellow', 'green', 'blue')).toBe('var(--blue)');
const expectations = /** @type {const} */ ([
[0.1, 'yellow', '30%', 'red'],
[0.2, 'yellow', '60%', 'red'],
[0.25, 'yellow', '75%', 'red'],
[0.3, 'yellow', '90%', 'red'],
[0.4, 'green', '20%', 'yellow'],
[0.5, 'green', '50%', 'yellow'],
[0.6, 'green', '80%', 'yellow'],
[0.7, 'blue', '10%', 'green'],
[0.75, 'blue', '25%', 'green'],
[0.8, 'blue', '40%', 'green'],
[0.9, 'blue', '70%', 'green']
]);
for (const [input, color, percent, otherColor] of expectations) {
expect
.soft(gradientedColor(input, 'red', 'yellow', 'green', 'blue'), `with ${input}`)
.toBe(`color-mix(in lab, var(--${color}) ${percent}, var(--${otherColor}))`);
}
});
});
}
/**
* Fades out an element matching the given selector over the given duration, then removes it from the DOM.
* If it's the first time the app is started (determined by checking localStorage), uses firstTimeDuration instead of duration if provided.
* @param {string} selector
* @param {number} duration in milliseconds
* @param {object} [options]
* @param {number} [options.firstTimeDuration] in milliseconds, if provided and it's the first time the app is started, this duration will be used instead of duration
*/
export function fadeOutElement(selector, duration, { firstTimeDuration } = {}) {
const firstStart = !localStorage.getItem('app_started_before');
localStorage.setItem('app_started_before', 'true');
if (firstStart) duration = firstTimeDuration ?? duration;
const element = document.querySelector(selector);
if (!(element instanceof HTMLElement)) {
element?.remove();
return;
}
element.style.transition = `opacity ${duration}ms linear`;
element.style.opacity = '0';
setTimeout(() => {
element.remove();
}, duration);
}
/**
* @param {string} color Hex of background color string, e.g. #RRGGBB
*/
export function readableOn(color) {
const rgb = color.replace(/^#/, '').match(/.{2}/g);
Iif (rgb === null) throw new Error('Invalid color, use hex notation');
const o = Math.round(
(parseInt(rgb[0], 16) * 299 + parseInt(rgb[1], 16) * 587 + parseInt(rgb[2], 16) * 114) /
1000
);
return o > 125 ? '#000000' : '#ffffff';
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('readableOn', () => {
expect(readableOn('#ffffff')).toBe('#000000');
expect(readableOn('#000000')).toBe('#ffffff');
expect(readableOn('#ff0000')).toBe('#ffffff');
expect(readableOn('#00ff00')).toBe('#000000');
expect(readableOn('#0000ff')).toBe('#ffffff');
expect(readableOn('#808080')).toBe('#000000');
expect(readableOn('#c0ffee')).toBe('#000000');
});
}
/**
* @param {string} message
* @returns {never}
*/
export function throwError(message) {
throw new Error(message);
}
/**
* Await to await the given promise, but throw if the given AbortSignal is aborted before the promise resolves
* @template T
* @param {AbortSignal | undefined} signal
* @param {Promise<T>} promise
* @returns {Promise<T>}
*/
export async function unlessAborted(signal, promise) {
return Promise.race([
promise,
new Promise((_, reject) => {
signal?.addEventListener('abort', () => {
reject(signal.reason);
});
})
]);
}
export const LOREM_IPSUM = `Lorem ipsum dolor sit amet. A impedit beatae sed nostrum voluptatem
ut omnis aliquid et galisum quaerat. Est sunt voluptatem aut porro iste et tempora voluptatem
aut pariatur minima sed omnis cumque est iusto fugit vel rerum magni. 33 ducimus nesciunt ut
consequuntur esse nam necessitatibus tempore sit suscipit voluptatibus qui rerum earum non autem
doloribus. Rem itaque esse est nostrum optio id repellat recusandae et ipsa quis.
Aut odio ipsa sed autem esse ut autem error qui voluptates perspiciatis aut officiis consequuntur
sit amet nihil. Eos delectus consequatur sit natus iure qui omnis omnis ea illum distinctio et
quos quidem. Et nisi autem est rerum eius ut dolorum commodi et temporibus expedita ea dolorem
error ad asperiores facilis ad numquam libero. Aut suscipit maxime sit explicabo dolorem est
accusantium enim et repudiandae omnis cum dolorem nemo id quia facilis.
Et dolorem perferendis et rerum suscipit qui voluptatibus quia et nihil nostrum 33 omnis soluta.
Nam minus minima et perspiciatis velit et eveniet rerum et nihil voluptates aut eaque ipsa et
ratione facere!`;
|