All files / lib metadata.js

17.88% Statements 54/302
22.52% Branches 41/182
8.88% Functions 8/90
20.15% Lines 52/258

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                                                                            3x 3x 3x                                                           11x                                                                                                                                       3x       3x         3x 3x                                     3x       3x   3x 3x 3x     3x 3x 3x 3x 3x   3x   3x 3x             3x 3x 3x                                         3x   3x               3x                                                                 3x 3x                                                                                                                                                                                                                                                 7x                                                                                                                                                                                                                                                                                                                                                                                       7x         7x                                                                                                                                                                         7x                                                                                                                                                                                                           18x   18x   4x   2x   2x       2x     4x     2x         2x                 2x   2x   1x   1x           4x                                                                                                                                                                                                                                                                                                                                                                                                                                                           7x                                                         19x 15x 15x   4x            
import { type } from 'arktype';
import * as dates from 'date-fns';
 
import { computeCascades } from './cascades.js';
import { idComparator, Schemas } from './database.js';
import {
	ensureNamespacedMetadataId,
	isNamespacedToProtocol,
	namespacedMetadataId,
	namespaceOfMetadataId,
	removeNamespaceFromMetadataId
} from './schemas/metadata.js';
import { avg, compareBy, fromEntries, mapValues } from './utils.js';
 
/**
 * @import { DatabaseHandle, ReactiveTableNames } from './idb.svelte.js'
 * @import * as DB from './database.js'
 */
 
/**
 * @template {DB.MetadataType} [Type=DB.MetadataType]
 * @typedef  RuntimeValue
 * @type {import('$lib/schemas/metadata.js').RuntimeValue<Type>}
 */
 
/**
 * @template {DB.MetadataType} [Type=DB.MetadataType]
 * @typedef TypedMetadataValue
 * @type {Omit<DB.MetadataValue, 'value'> & { value: RuntimeValue<Type> }}
 */
 
/**
 * Refresh the specified table. Does nothing if we can't import idb.svelte.js.
 * We do it this way so that this file can be imported in the web worker.
 * @param {string} sessionId
 * @param {...ReactiveTableNames} tableNames
 */
async function refreshTables(sessionId, ...tableNames) {
	try {
		const idb = await import('$lib/idb.svelte.js');
		await Promise.all(tableNames.map((name) => idb.tables[name].refresh(sessionId)));
	} catch (error) {
		console.warn(`Cannot refresh tables ${tableNames}:`, error);
	}
}
 
/**
 * Get a strongly-typed metadata value from an image (Image ONLY, not Observation).
 * @template {DB.MetadataType} Type
 * @param {DB.Image} image
 * @param {Type} type
 * @param {string} metadataId
 * @returns {TypedMetadataValue<Type> | undefined}
 */
export function getMetadataValue(image, type, metadataId) {
	const value = image.metadata[metadataId];
	if (value === undefined) return undefined;
 
	return {
		...value,
		value: assertIs(type, value.value)
	};
}
 
/**
 * Serialize a metadata value for storing in the database.
 * @param {*} value
 * @returns {string}
 */
export function serializeMetadataValue(value) {
	return JSON.stringify(
		value instanceof Date && dates.isValid(value)
			? dates.format(value, "yyyy-MM-dd'T'HH:mm:ss")
			: value
	);
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('serializeMetadataValue', () => {
		expect(serializeMetadataValue('hello')).toBe('"hello"');
		expect(serializeMetadataValue(42)).toBe('42');
		expect(serializeMetadataValue(true)).toBe('true');
		expect(serializeMetadataValue(null)).toBe('null');
 
		const date = new Date('2023-01-01T12:30:45');
		expect(serializeMetadataValue(date)).toBe('"2023-01-01T12:30:45"');
 
		// Invalid date should be serialized as is
		const invalidDate = new Date('invalid');
		expect(serializeMetadataValue(invalidDate)).toBe('null'); // Invalid date becomes null when JSON stringified
 
		expect(serializeMetadataValue(['a', 'b'])).toBe('["a","b"]');
		expect(serializeMetadataValue({ key: 'value' })).toBe('{"key":"value"}');
	});
}
 
/**
 * Serialize a record of metadata values for storing in the database.
 * @param {DB.MetadataValues} values
 * @returns {typeof import('$lib/database').Schemas.MetadataValues.inferIn}
 */
export function serializeMetadataValues(values) {
	return mapValues(values, ({ value, ...rest }) => ({
		...rest,
		value: serializeMetadataValue(value)
	}));
}
 
/**
 *
 * @template {DB.MetadataType} Type
 * @param {object} options
 * @param {string} options.subjectId id de l'image, l'observation ou la session
 * @param {string} options.metadataId id de la métadonnée
 * @param {Type} [options.type] le type de données pour la métadonnée, sert à éviter des problèmes de typages
 * @param {RuntimeValue<Type>} options.value la valeur de la métadonnée
 * @param {boolean} [options.manuallyModified=false] si la valeur a été modifiée manuellement
 * @param {number} [options.confidence=1] la confiance dans la valeur (proba que ce soit la bonne valeur)
 * @param {DatabaseHandle} options.db BDD à modifier
 * @param {Array<{ value: RuntimeValue<Type>; confidence: number }>} [options.alternatives=[]] les autres valeurs possibles
 * @param {string[]} [options.cascadedFrom] ID des métadonnées dont celle-ci est dérivée, pour éviter les boucles infinies (cf "cascade" dans MetadataEnumVariant)
 * @param {AbortSignal} [options.abortSignal] signal d'abandon pour annuler la requête
 * @param {string} [options.sessionId] id de la session en cours, important pour refresh le state réactif des tables
 */
export async function storeMetadataValue({
	db,
	subjectId,
	metadataId,
	type,
	value,
	confidence = 1,
	alternatives = [],
	manuallyModified = false,
	cascadedFrom = [],
	sessionId,
	abortSignal
}) {
	Iif (!namespaceOfMetadataId(metadataId)) {
		throw new Error(`Le metadataId ${metadataId} n'est pas namespacé`);
	}
 
	Iif (confidence > 1) {
		console.warn(`Confidence ${confidence} is greater than 1, capping to 1`);
		confidence = 1;
	}
 
	abortSignal?.throwIfAborted();
	const newValue = {
		value: serializeMetadataValue(value),
		confidence,
		manuallyModified,
		alternatives: Object.fromEntries(
			alternatives.map(({ value, confidence }) => {
				if (confidence > 1) {
					console.warn(
						`Confidence ${confidence} of alternative ${value} is greater than 1, capping to 1`
					);
					confidence = 1;
				}
 
				return [serializeMetadataValue(value), confidence];
			})
		)
	};
 
	// Make sure the alternatives does not contain the value itself
	newValue.alternatives = Object.fromEntries(
		Object.entries(newValue.alternatives).filter(([key]) => key !== newValue.value)
	);
 
	console.debug(`Store metadata ${metadataId} = `, value, ` in ${subjectId}`, newValue);
 
	const metadata = await db.get('Metadata', metadataId);
	Iif (!metadata) throw new Error(`Métadonnée inconnue avec l'ID ${metadataId}`);
	Iif (type && metadata.type !== type)
		throw new Error(`Type de métadonnée incorrect: ${metadata.type} !== ${type}`);
 
	abortSignal?.throwIfAborted();
	const image = await db.get('Image', subjectId);
	const observation = await db.get('Observation', subjectId);
	const session = await db.get('Session', subjectId);
	const imagesFromImageFile = await db
		.getAll('Image')
		.then((imgs) => imgs.filter(({ fileId }) => fileId === subjectId));
 
	abortSignal?.throwIfAborted();
	Iif (session) {
		if (session.metadata) {
			session.metadata[metadataId] = newValue;
		} else {
			session.metadata = { [metadataId]: newValue };
		}
		db.put('Session', session);
	} else if (image) {
		image.metadata[metadataId] = newValue;
		db.put('Image', image);
	} else Eif (observation) {
		observation.metadataOverrides[metadataId] = newValue;
		db.put('Observation', observation);
	} else if (imagesFromImageFile) {
		for (const { id } of imagesFromImageFile) {
			await storeMetadataValue({
				db,
				sessionId,
				subjectId: id,
				metadataId,
				value,
				confidence,
				manuallyModified,
				abortSignal
			});
		}
	} else {
		throw new Error(`Aucune image ou observation avec l'ID ${subjectId}`);
	}
 
	abortSignal?.throwIfAborted();
 
	const cascades = await computeCascades({
		db,
		metadataId,
		value,
		confidence,
		alternatives
	});
 
	for (const cascade of cascades) {
		abortSignal?.throwIfAborted();
 
		if (cascadedFrom.includes(cascade.metadataId)) {
			throw new Error(
				`Boucle infinie de cascade détectée pour ${cascade.metadataId} avec ${cascade.value}: ${cascadedFrom.join(' -> ')} -> ${metadataId} -> ${cascade.metadataId}`
			);
		}
 
		console.info(
			`Cascading metadata ${metadataId} @ ${value} -> ${cascade.metadataId}  = ${cascade.value}`
		);
 
		const metadataNamespace = namespaceOfMetadataId(metadataId);
		if (!metadataNamespace)
			throw new Error(
				`Metadata ${metadataId} is not namespaced, cannot cascade onto ${cascade.metadataId}`
			);
 
		cascade.metadataId = ensureNamespacedMetadataId(cascade.metadataId, metadataNamespace);
 
		await storeMetadataValue({
			db,
			sessionId,
			subjectId,
			manuallyModified,
			cascadedFrom: [...cascadedFrom, metadataId],
			abortSignal,
			...cascade
		});
	}
 
	// Only refresh table state once everything has been cascaded, meaning not inside recursive calls
	Eif (cascadedFrom.length === 0 && sessionId) {
		await refreshTables(sessionId, image ? 'Image' : 'Observation');
	}
}
 
/**
 *
 * @param {object} options
 * @param {string} options.subjectId id de l'image ou l'observation
 * @param {string} options.metadataId id de la métadonnée
 * @param {boolean} [options.recursive=false] si true, supprime la métadonnée de toutes les images composant l'observation
 * @param {DatabaseHandle} options.db BDD à modifier
 * @param {boolean} [options.reactive=true] refresh reactive table state if possible
 * @param {string} [options.sessionId] current session, used to refresh reactive tables
 */
export async function deleteMetadataValue({
	db,
	subjectId,
	metadataId,
	recursive = false,
	reactive = true,
	sessionId
}) {
	const image = await db.get('Image', subjectId);
	const observation = await db.get('Observation', subjectId);
	const session = await db.get('Session', subjectId);
	const imagesFromImageFile = await db
		.getAllFromIndex('Image', 'sessionId', sessionId)
		.then((imgs) => imgs.filter(({ fileId }) => fileId === subjectId));
 
	if (!image && !observation && !session && imagesFromImageFile.length === 0)
		throw new Error(`Aucune image, observation ou session avec l'ID ${subjectId}`);
 
	console.debug(`Delete metadata ${metadataId} in ${subjectId}`);
	if (image) {
		delete image.metadata[metadataId];
		db.put('Image', image);
	} else if (session) {
		delete session.metadata[metadataId];
		db.put('Session', session);
	} else if (observation) {
		delete observation.metadataOverrides[metadataId];
		db.put('Observation', observation);
		if (recursive) {
			for (const imageId of observation.images) {
				await deleteMetadataValue({
					db,
					sessionId,
					subjectId: imageId,
					recursive: false,
					metadataId,
					// Don't refresh table state on recursive calls, we just have to do it once
					reactive: false
				});
			}
		}
	} else if (imagesFromImageFile) {
		for (const { id } of imagesFromImageFile) {
			await deleteMetadataValue({
				db,
				sessionId,
				subjectId: id,
				recursive: false,
				metadataId,
				reactive: false
			});
		}
	}
 
	if (reactive && sessionId) await refreshTables(sessionId, 'Image', 'Observation');
 
	return;
}
 
/**
 * Gets all metadata for an observation, including metadata derived from merging the metadata values of the images that make up the observation.
 * @param {Pick<DB.Observation, 'images' | 'metadataOverrides'>} observation
 * @param {DatabaseHandle} db
 * @param {DB.Protocol} protocol
 * @returns {Promise<DB.MetadataValues>}
 */
export async function observationMetadata(db, protocol, observation) {
	const images = await Promise.all(
		observation.images.map(async (id) => await db.get('Image', id))
	);
 
	images.sort(compareBy(({ id }) => observation.images.indexOf(id)));
 
	const metadataFromImages = await mergeMetadataValues(
		db,
		protocol,
		images.map((img) => Schemas.MetadataValues.assert(img.metadata))
	);
 
	return {
		...metadataFromImages,
		...observation.metadataOverrides
	};
}
 
/**
 * Adds valueLabel to each metadata value object when the metadata is an enum.
 * @param {DB.MetadataValues} values
 * @param {Record<string, Record<string, DB.MetadataEnumVariant>>} metadataOptions
 * @returns {Promise<Record<string, DB.MetadataValue & { valueLabel?: string }>>}
 */
export async function addValueLabels(values, metadataOptions) {
	return Object.fromEntries(
		Object.entries(values).map(([key, value]) => {
			const opts = metadataOptions[key];
			if (!opts) return [key, value];
 
			const opt = opts[value.value.toString()];
 
			return [key, { ...value, valueLabel: opt?.label }];
		})
	);
}
 
/**
 * @type {Set<DB.MetadataType>}
 */
export const MERGEABLE_METADATA_TYPES = new Set([
	'boolean',
	'integer',
	'float',
	'date',
	'location',
	'boundingbox',
	'enum'
]);
 
/**
 * Merge metadata values from images and observations. For every metadata key, the value is taken from the merged values of observation overrides if there exists at least one, otherwise from the merged values of the images.
 * @param {DatabaseHandle} db
 * @param {DB.Protocol} protocol
 * @param {DB.Image[]} images
 * @param {DB.Observation[]} observations
 */
export async function mergeMetadataFromImagesAndObservations(db, protocol, images, observations) {
	const mergedValues = await mergeMetadataValues(
		db,
		protocol,
		images.map((img) => img.metadata)
	);
	const mergedOverrides = await mergeMetadataValues(
		db,
		protocol,
		observations.map((obs) => obs.metadataOverrides)
	);
 
	const keys = new Set([...Object.keys(mergedValues), ...Object.keys(mergedOverrides)]);
 
	/** @type {Record<string, DB.MetadataValue & { merged: boolean }>}  */
	const output = {};
 
	for (const key of keys) {
		const value = mergedOverrides[key] ?? mergedValues[key];
		if (value) output[key] = value;
	}
 
	return output;
}
 
/**
 * @param {DatabaseHandle} db
 * @param {DB.Protocol} protocol
 * @param {Array<DB.MetadataValues>} values
 * @returns {Promise<Record<string, DB.MetadataValue & { merged: boolean }>>}
 */
export async function mergeMetadataValues(db, protocol, values) {
	if (values.length === 1) {
		return mapValues(values[0], (v) => ({ ...v, merged: false }));
	}
 
	/** @type {Record<string, DB.MetadataValue & { merged: boolean }>}  */
	const output = {};
 
	const keys = new Set(values.flatMap((singleSubjectValues) => Object.keys(singleSubjectValues)));
 
	for (const key of keys) {
		const definition = Schemas.Metadata.assert(await db.get('Metadata', key));
		if (!definition) {
			console.warn(`Cannot merge metadata values for unknown key ${key}`);
			continue;
		}
 
		const valuesOfKey = values.flatMap((singleSubjectValues) =>
			Object.entries(singleSubjectValues)
				.filter(([k]) => k === key)
				.map(([, v]) => v)
		);
 
		/** @type {DB.MetadataEnumVariant[]} */
		let options = [];
 
		if (definition.type === 'enum' && definition.mergeMethod === 'average') {
			const optionsCount = await db.count(
				'MetadataOption',
				metadataOptionsKeyRange(protocol.id, definition.id)
			);
 
			if (optionsCount > 500) {
				throw new Error(
					`Impossible de fusionner les valeurs de la métadonnée ${key} en mode moyenne car elle possède plus de 500 options (${optionsCount} options). Le protocol doit choisir un autre mode de fusion.`
				);
			}
 
			options = await db
				.getAll('MetadataOption', metadataOptionsKeyRange(protocol.id, definition.id))
				.then((opts) => opts.map((opt) => Schemas.MetadataEnumVariant.assert(opt)));
		}
 
		const merged = mergeMetadata(definition, valuesOfKey, options);
 
		if (merged !== null && merged !== undefined)
			output[key] = {
				...merged,
				merged: new Set(valuesOfKey.map((v) => JSON.stringify(v.value))).size > 1
			};
	}
 
	return output;
}
 
/**
 *
 * @param {DB.Metadata} definition
 * @param {DB.MetadataValue[]} values
 * @param {DB.MetadataEnumVariant[]} [options]
 */
function mergeMetadata(definition, values, options = []) {
	/**
	 * @param {(probabilities: number[]) => number} merger
	 * @param {DB.MetadataValue[]} values
	 * Run merger on array of confidences for every probability of each alternative of each values:
	 * example: [ { alternatives: { a: 0.8, b: 0.2 } }, { alternatives: { a: 0.6, b: 0.4 } } ]
	 * turns into: { a: merger([0.8, 0.6]), b: merger([0.2, 0.4]) }
	 */
 
	/**
	 * @param {(probabilities: number[]) => number} merger
	 * @param {DB.MetadataValue[]} values
	 */
	const mergeAlternatives = (merger, values) =>
		Object.fromEntries(
			values
				.flatMap((v) => Object.keys(v.alternatives))
				.map((valueAsString) => [
					valueAsString,
					merger(
						values.flatMap((v) => v.alternatives[valueAsString] ?? null).filter(Boolean)
					)
				])
		);
 
	switch (definition.mergeMethod) {
		case 'average':
			return {
				value: mergeAverage(
					definition.type,
					values.map((v) => v.value),
					options
				),
				manuallyModified: values.some((v) => v.manuallyModified),
				confidence: avg(values.map((v) => v.confidence)),
				alternatives: mergeAlternatives(avg, values)
			};
		case 'max':
		case 'min':
			return {
				value: mergeByMajority(
					definition.type,
					// @ts-expect-error
					values,
					definition.mergeMethod === 'max' ? max : min
				),
				manuallyModified: values.some((v) => v.manuallyModified),
				confidence: max(values.map((v) => v.confidence)),
				alternatives: mergeAlternatives(max, values)
			};
		case 'median':
			return {
				value: mergeMedian(
					definition.type,
					values.map((v) => v.value)
				),
				manuallyModified: values.some((v) => v.manuallyModified),
				confidence: median(values.map((v) => v.confidence)),
				alternatives: mergeAlternatives(median, values)
			};
		case 'union':
			return {
				value: mergeByUnion(
					definition.type,
					values.map((v) => v.value)
				),
				manuallyModified: values.some((v) => v.manuallyModified),
				confidence: avg(values.map((v) => v.confidence)),
				alternatives: mergeAlternatives(avg, values)
			};
		case 'none':
			return null;
	}
}
 
/**
 *
 * @param {number[]} values
 */
const max = (values) => Math.max(...values);
 
/**
 * @param {number[]} values
 */
const min = (values) => Math.min(...values);
 
/**
 * Merge values by best confidence. If multiple values have the same confidence, use `strategy` to break the tie. If `strategy` throws, use first value as a fallback.
 * @param {Type} _type
 * @param {Array<{ value: Value, confidence: number }>} values
 * @param {(values: Value[]) => Value} strategy
 * @returns {Value}
 * @template {RuntimeValue<Type>} Value
 * @template {DB.MetadataType} Type
 */
function mergeByMajority(_type, values, strategy) {
	const bestConfidence = Math.max(...values.map((v) => v.confidence));
	const bestValues = values.filter((v) => v.confidence === bestConfidence);
	try {
		return strategy(bestValues.map((v) => v.value));
	} catch (error) {
		console.error(error);
		return bestValues[0].value;
	}
}
 
/**
 * Merge values by average.
 * @param {Type} type
 * @param {Value[]} values
 * @param {import('./database.js').MetadataEnumVariant[]} [options]
 * @returns {Value}
 * @template {RuntimeValue<Type>} Value
 * @template {DB.MetadataType} Type
 */
function mergeAverage(type, values, options = []) {
	/**
	 * @template {DB.MetadataType} T
	 * @param {Parameters<typeof toNumber>[1]} values
	 */
	const average = (values) => avg(toNumber(type, values));
 
	// @ts-expect-error
	if (type === 'boolean') return average(values) > 0.5;
	// @ts-expect-error
	if (type === 'integer') return Math.ceil(average(values));
	// @ts-expect-error
	if (type === 'float') return average(values);
	// @ts-expect-error
	if (type === 'date') return new Date(average(values));
	if (type === 'location') {
		// @ts-expect-error
		return {
			latitude: avg(
				values.map(
					(v) =>
						// @ts-expect-error
						v.latitude
				)
			),
			longitude: avg(
				values.map(
					(
						v //@ts-expect-error
					) => v.longitude
				)
			)
		};
	}
 
	if (type === 'enum') {
		// Get average index of values, and return closest option
 
		const averageIndex = Math.round(
			avg(
				/** @type {string[]} */ (values)
					.map((v) => options.find((opt) => opt.key === v)?.index)
					.filter((v) => v !== undefined)
			)
		);
 
		// @ts-expect-error
		return options.find((opt) => opt.index === averageIndex)?.key ?? values[0];
	}
 
	throw new Error(`Impossible de fusionner en mode moyenne des valeurs de type ${type}`);
}
 
/** @param {number[]} values */
const median = (values) => {
	const sorted = values.sort((a, b) => a - b);
	const middle = Math.floor(sorted.length / 2);
	if (sorted.length % 2 === 0) {
		return (sorted[middle - 1] + sorted[middle]) / 2;
	}
	return sorted[middle];
};
 
/**
 * Merge values by median.
 * @param {Type} type
 * @param {Value[]} values
 * @returns {Value}
 * @template {RuntimeValue<Type>} Value
 * @template {DB.MetadataType} Type
 */
function mergeMedian(type, values) {
	/** @param {typeof values} values */
	const median_ = (values) => median(toNumber(type, values));
 
	// @ts-ignore
	if (type === 'boolean') return median_(values) > 0.5;
	// @ts-ignore
	if (type === 'integer') return Math.ceil(median_(values));
	// @ts-ignore
	if (type === 'float') return median_(values);
	// @ts-ignore
	if (type === 'date') return new Date(median_(values));
	if (type === 'location') {
		// @ts-ignore
		return {
			latitude: median(
				values.map(
					(v) =>
						// @ts-ignore
						v.latitude
				)
			),
			longitude: median(
				values.map(
					(v) =>
						// @ts-ignore
						v.longitude
				)
			)
		};
	}
 
	throw new Error(`Impossible de fusionner en mode médiane des valeurs de type ${type}`);
}
 
/**
 * Merge values by union.
 * @param {import('./database.js').MetadataType} type
 * @param {Array<RuntimeValue>} values
 * @returns {RuntimeValue<"boundingbox">}
 */
function mergeByUnion(type, values) {
	if (!areType('boundingbox', type, values)) {
		throw new Error(`Impossible de fusionner en mode union des valeurs de type ${type}`);
	}
 
	const xStart = Math.min(...values.map((v) => v.x));
	const yStart = Math.min(...values.map((v) => v.y));
	const xEnd = Math.max(...values.map((v) => v.x + v.w));
	const yEnd = Math.max(...values.map((v) => v.y + v.h));
 
	return {
		x: xStart,
		y: yStart,
		w: xEnd - xStart,
		h: yEnd - yStart
	};
}
 
/**
 * Convert series of values to an output number
 * @param {DB.MetadataType} type
 * @param {Array<RuntimeValue<"integer" | "float" | "boolean" | "date">>} values
 * @returns {number[]}
 */
function toNumber(type, values) {
	// @ts-ignore
	if (type === 'integer') return values;
	// @ts-ignore
	if (type === 'float') return values;
	if (type === 'boolean') return values.map((v) => (v ? 1 : 0));
	if (type === 'date')
		return values.map((v) => new Date(/** @type {Date|string} */ (v)).getTime());
	throw new Error(`Impossible de convertir des valeurs de type ${type} en nombre`);
}
 
/**
 * Returns a human-friendly string for a metadata value.
 * Used for e.g. CSV exports.
 * @param {import('$lib/i18n.js').Language} language
 * @param {Pick<DB.Metadata, 'type'>} metadata the metadata definition
 * @param {DB.MetadataValue['value'] | null} value the value of the metadata
 * @param {string} [valueLabel] the label of the value, if applicable (e.g. for enums)
 */
export function metadataPrettyValue(language, metadata, value, valueLabel = undefined) {
	Iif (value === null) return '';
 
	switch (metadata.type) {
		case 'boolean':
			switch (language) {
				case 'fr':
					return value ? 'Oui' : 'Non';
				default:
					return value ? 'Yes' : 'No';
			}
 
		case 'date':
			return value instanceof Date ? dates.format(value, 'Ppp') : value.toString();
 
		case 'enum':
			return valueLabel || value.toString();
 
		case 'location': {
			const { latitude, longitude } = type({
				latitude: 'number',
				longitude: 'number'
			}).assert(value);
 
			return `${latitude}, ${longitude}`;
		}
 
		case 'boundingbox': {
			const {
				x: x1,
				y: y1,
				w,
				h
			} = type({ x: 'number', y: 'number', h: 'number', w: 'number' }).assert(value);
 
			switch (language) {
				case 'fr':
					return `Boîte de (${x1}, ${y1}) à (${x1 + w}, ${y1 + h})`;
				default:
					return `Box from (${x1}, ${y1}) to (${x1 + w}, ${y1 + h})`;
			}
		}
 
		case 'float':
		case 'integer':
			return Intl.NumberFormat(language).format(type('number').assert(value));
 
		default:
			return value.toString();
	}
}
 
if (import.meta.vitest) {
	const { expect, test, describe, beforeEach } = import.meta.vitest;
 
	describe('metadataPrettyValue', () => {
		describe('in french', () => {
			beforeEach(async () => {
				const { fr } = await import('date-fns/locale');
				dates.setDefaultOptions({ locale: fr });
			});
 
			test('booleans', () => {
				expect(metadataPrettyValue('fr', { type: 'boolean' }, true)).toBe('Oui');
				expect(metadataPrettyValue('fr', { type: 'boolean' }, false)).toBe('Non');
			});
 
			test('dates', () => {
				expect(
					metadataPrettyValue('fr', { type: 'date' }, new Date('2023-02-01T15:04:05Z'))
				).toBe('01/02/2023, 15:04:05');
			});
 
			test('floats', () => {
				expect(metadataPrettyValue('fr', { type: 'float' }, 12012.34)).toBe('12 012,34');
			});
 
			test('bounding boxes', () => {
				expect(
					metadataPrettyValue('fr', { type: 'boundingbox' }, { x: 1, y: 2, w: 3, h: 4 })
				).toBe('Boîte de (1, 2) à (4, 6)');
			});
 
			test('integers', () => {
				expect(metadataPrettyValue('fr', { type: 'integer' }, 12012)).toBe('12\u202F012');
			});
		});
 
		describe('in english', () => {
			beforeEach(async () => {
				const { enUS } = await import('date-fns/locale');
				dates.setDefaultOptions({ locale: enUS });
			});
 
			test('booleans', () => {
				expect(metadataPrettyValue('en', { type: 'boolean' }, true)).toBe('Yes');
				expect(metadataPrettyValue('en', { type: 'boolean' }, false)).toBe('No');
			});
 
			test('dates', () => {
				expect(
					metadataPrettyValue('en', { type: 'date' }, new Date('2023-02-01T15:04:05Z'))
				).toBe('02/01/2023, 3:04:05 PM');
			});
 
			test('bounding boxes', () => {
				expect(
					metadataPrettyValue('en', { type: 'boundingbox' }, { x: 1, y: 2, w: 3, h: 4 })
				).toBe('Box from (1, 2) to (4, 6)');
			});
 
			test('floats', () => {
				expect(metadataPrettyValue('en', { type: 'float' }, 12012.34)).toBe('12,012.34');
			});
 
			test('integers', () => {
				expect(metadataPrettyValue('en', { type: 'integer' }, 12012)).toBe('12,012');
			});
		});
 
		test('locations', () => {
			expect(
				metadataPrettyValue(
					'fr',
					{ type: 'location' },
					{ latitude: 12.34, longitude: 56.78 }
				)
			).toBe('12.34, 56.78');
			expect(
				metadataPrettyValue(
					'en',
					{ type: 'location' },
					{ latitude: 12.34, longitude: 56.78 }
				)
			).toBe('12.34, 56.78');
		});
 
		test('enums', () => {
			expect(metadataPrettyValue('en', { type: 'enum' }, 'value1', 'Label 1')).toBe(
				'Label 1'
			);
			expect(metadataPrettyValue('fr', { type: 'enum' }, 'value1', 'Label 1')).toBe(
				'Label 1'
			);
			expect(metadataPrettyValue('en', { type: 'enum' }, 'value2')).toBe('value2');
			expect(metadataPrettyValue('fr', { type: 'enum' }, 'value2')).toBe('value2');
		});
	});
}
 
/**
 * Returns a human-friendly string for a metadata key. Uses the label, and adds useful info about the data format if applicable.
 * To be used with `metadataPrettyValue`.
 * @param {DB.Metadata} metadata
 * @returns
 */
export function metadataPrettyKey(metadata) {
	let out = metadata.label;
	switch (metadata.type) {
		case 'location':
			out += ' (latitude, longitude)';
	}
	return out;
}
 
/**
 * Asserts that a metadata is of a certain type, inferring the correct runtime type for its value
 * @template {DB.MetadataType} Type
 * @template {undefined | RuntimeValue} Value
 * @param {Type} testedtyp
 * @param {DB.MetadataType} metadatatyp
 * @param {Value} value
 * @returns {value is (Value extends RuntimeValue ?  RuntimeValue<Type> : (undefined | RuntimeValue<Type>))}
 */
export function isType(testedtyp, metadatatyp, value) {
	/**
	 * @param {import('arktype').Type} v
	 * @returns boolean
	 */
	const ok = (v) =>
		metadatatyp === testedtyp && (value === undefined || !(v(value) instanceof type.errors));
 
	switch (testedtyp) {
		case 'boolean':
			return ok(type('boolean'));
		case 'integer':
		case 'float':
			return ok(type('number'));
		case 'enum':
			return ok(type('string | number'));
		case 'date':
			return ok(type('Date'));
		case 'location':
			return ok(type({ latitude: 'number', longitude: 'number' }));
		case 'boundingbox':
			return ok(type({ x: 'number', y: 'number', w: 'number', h: 'number' }));
		case 'string':
			return ok(type('string'));
		default:
			throw new Error(`Type inconnu: ${testedtyp}`);
	}
}
 
/**
 * Just like `isType`, but for an array of values
 * @template {DB.MetadataType} Type
 * @template {undefined | RuntimeValue} Value
 * @param {Type} testedtyp
 * @param {DB.MetadataType} metadatatyp
 * @param {Value[]} value
 * @returns {value is (Value extends RuntimeValue ?  RuntimeValue<Type>[] : (undefined | RuntimeValue<Type>[]))}
 */
function areType(testedtyp, metadatatyp, value) {
	return value.every((v) => isType(testedtyp, metadatatyp, v));
}
 
/**
 *
 * @template {DB.MetadataType} Type
 * @param {Type} type
 * @param {any} value
 * @returns {value is RuntimeValue<Type>}
 */
export function hasRuntimeType(type, value) {
	return isType(type, type, value);
}
 
/**
 * @template {DB.MetadataType} Type
 * @param {Type} type
 * @param {unknown} value
 * @returns {RuntimeValue<Type>}
 */
export function assertIs(type, value) {
	// @ts-ignore
	if (!isType(type, type, value))
		throw new Error(`La valeur n'est pas de type ${type}: ${JSON.stringify(value)}`);
	return value;
}
 
/**
 *
 * @param {{metadataOrder?: undefined | string[]}} protocol
 * @returns {(a: string | { id: string }, b: string | { id: string }) => number}
 */
export function metadataDefinitionComparator(protocol) {
	return (a, b) => {
		if (typeof a !== 'string') a = a.id;
		if (typeof b !== 'string') b = b.id;
 
		if (protocol.metadataOrder) {
			return protocol.metadataOrder.indexOf(a) - protocol.metadataOrder.indexOf(b);
		}
		return idComparator(a, b);
	};
}
 
/**
 * @template T
 * @template Undefinable
 * @typedef{ Undefinable extends true ? T | undefined : T } Maybe
 */
 
/**
 * A null-value MetadataValue object
 * @satisfies {ReturnType<typeof protocolMetadataValues>[string]}
 */
const METADATA_ZERO_VALUE = /** @type {const} */ ({
	value: null,
	manuallyModified: false,
	confidence: 0,
	alternatives: {}
});
 
/**
 * Returns a un-namespaced object of all metadata values of the given protocol, given the metadata values object of an image/observation. If a metadata value is absent from the given values, the value is still present, but set to `null`.
 *
 * @param {DB.Protocol} protocol
 * @param {DB.MetadataValues} values
 * @returns {Record<string, Omit<DB.MetadataValue, 'value'> & { value: RuntimeValue | null }>}
 */
export function protocolMetadataValues(protocol, values) {
	return fromEntries(
		protocol.metadata
			.filter((key) => isNamespacedToProtocol(protocol.id, key))
			.map((key) => [removeNamespaceFromMetadataId(key), values[key] ?? METADATA_ZERO_VALUE])
	);
}
 
/**
 *
 * @param {string} protocolId
 * @param {string|null} metadataId null to get options of all metadata of the protocol
 * @returns {IDBKeyRange}
 */
export function metadataOptionsKeyRange(protocolId, metadataId) {
	if (metadataId) {
		const fullMetadataId = ensureNamespacedMetadataId(metadataId, protocolId);
		return IDBKeyRange.bound(fullMetadataId + ':', fullMetadataId + ':\uffff');
	} else {
		return IDBKeyRange.bound(
			namespacedMetadataId('', protocolId),
			namespacedMetadataId('\uffff', protocolId)
		);
	}
}