All files / lib/schemas metadata.js

75.53% Statements 71/94
55.55% Branches 10/18
60% Functions 21/35
80.72% Lines 67/83

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                                                                  84x             12x 12x 12x 12x 12x           25x                                         25x                                     25x                       25x                     25x           33x                   25x   25x   74x 74x 74x               25x                               59x           25x   25x                           25x                                         244x         25x                                                     25x                 25x                   50x                                                     51x     2x           51x     25x   25x   25x         25x               25x 225x                             25x                   225x                                   25x                   25x                                             25x           25x                                                                 92x                                 25x                                                                               25x                         25x                     25x                               25x                   25x                           25x                                   25x                                 250x                                   25x                             75x       75x     25x                       25x                                                 182x 182x                 19x                                                 47x   24x                 4x                                                     41x 41x 41x 41x                                                  
import { ArkErrors, scope, type } from 'arktype';
 
import { parseISOSafe } from '../date.js';
import { EXIF_FIELDS } from '../exiffields.js';
import { boundingBoxResolver } from '../inference_utils.js';
import { ensureArray, entries, keys, mapValues, transformObject, unique } from '../utils.js';
import {
	ColorHex,
	FilepathTemplate,
	FileSize,
	ID,
	MIMEType,
	NamespacedMetadataID,
	NamespacedMetadataOptionID,
	Probability,
	ProtocolID,
	UniqueFileTypeSpecifier,
	URLString,
} from './common.js';
import { NaturalRegexExpression, NumberRangeLiteral, RegexExpression } from './constraints.js';
import { JsonataExpression, TemplatedString } from './expressions.js';
import {
	MODEL_DETECTION_OUTPUT_SHAPES,
	NeuralBoundingBoxInference,
	NeuralEnumInference,
} from './neural.js';
import { NumericUnit } from './units.js';
 
/**
 * @param {string} metadataId
 * @param {RuntimeValue<"enum">} key
 */
export function metadataOptionId(metadataId, key) {
	return `${metadataId}:${key}`;
}
 
/**
 * @param {string} optionId
 */
export function parseMetadataOptionId(optionId) {
	const parts = optionId.split(':');
	Iif (parts.length < 2) throw new Error(`Invalid metadata option ID: ${optionId}`);
	const metadataId = parts.slice(0, -1).join(':');
	const key = parts[parts.length - 1];
	return { metadataId, key };
}
 
/**
 * @satisfies { Record<string, {label: string, help: string}> }
 */
export const METADATA_TYPES = /** @type {const} */ ({
	string: { label: 'texte', help: 'du texte' },
	boolean: { label: 'booléen', help: 'vrai ou faux' },
	integer: { label: 'entier', help: 'un entier' },
	float: { label: 'nombre', help: 'un nombre, potentiellement à virgule' },
	enum: { label: 'énumération', help: 'un ensemble de valeur fixes' },
	date: { label: 'date', help: 'une date' },
	location: {
		label: 'localisation',
		help: 'un objet avec deux nombres, `latitude` et `longitude`',
	},
	boundingbox: {
		label: "région d'image",
		help: 'un objet représentant une région rectangulaire au format YOLO',
	},
	file: {
		label: 'fichier',
		help: 'un fichier, représenté par une référence à un MetadataFile, qui est exporté séparément',
	},
});
 
export const MetadataType = type.or(
	type("'string'", '@', METADATA_TYPES.string.help),
	type("'boolean'", '@', METADATA_TYPES.boolean.help),
	type("'integer'", '@', METADATA_TYPES.integer.help),
	type("'float'", '@', METADATA_TYPES.float.help),
	type("'enum'", '@', METADATA_TYPES.enum.help),
	type("'date'", '@', METADATA_TYPES.date.help),
	type("'location'", '@', METADATA_TYPES.location.help),
	type("'boundingbox'", '@', METADATA_TYPES.boundingbox.help),
	type("'file'", '@', METADATA_TYPES.file.help)
);
 
/**
 * @typedef {typeof MetadataType.infer} MetadataType
 */
 
/**
 * @satisfies {{[ key in MetadataType ]: import('arktype').Type }}
 */
export const MetadataRuntimeValue = /** @type {const} */ ({
	string: type('string'),
	boolean: type('boolean'),
	integer: type('number'),
	float: type('number'),
	enum: type('string | number'),
	date: type('Date'),
	location: type({ latitude: 'number', longitude: 'number' }),
	boundingbox: type({ x: 'number', y: 'number', w: 'number', h: 'number' }),
	file: type(ID),
});
 
export const MetadataRuntimeValueAny = type.or(
	MetadataRuntimeValue.string,
	MetadataRuntimeValue.boolean,
	MetadataRuntimeValue.integer,
	MetadataRuntimeValue.float,
	MetadataRuntimeValue.enum,
	MetadataRuntimeValue.date,
	MetadataRuntimeValue.location,
	MetadataRuntimeValue.boundingbox
);
 
export const MetadataError = type({
	message: 'string',
	details: 'unknown',
	stack: 'string = ""',
	/** Ignored by the user */
	ignored: 'boolean = false',
	happenedAt: ['string.date.iso', '=', () => new Date().toISOString()],
	kind: type.or(
		type(
			'"inference"',
			'@',
			"Erreur survenue lors de l'inférence de la valeur de cette métadonnée"
		)
	),
});
 
export const MetadataErrors = type.Record(NamespacedMetadataID, MetadataError.array());
 
const MetadataValueMain = type('string.json').pipe((jsonstring) => {
	/** @type {RuntimeValue<typeof MetadataType.infer>}  */
	let out = JSON.parse(jsonstring);
	if (typeof out === 'string') out = parseISOSafe(out) ?? out;
	return out;
}, MetadataRuntimeValueAny);
/**
 * @template {MetadataType} [Type=MetadataType]
 * @typedef  RuntimeValue
 * @type { typeof MetadataRuntimeValue[Type]['infer'] }
 */
 
export const MetadataValue = type({
	value: MetadataValueMain,
	confidence: Probability.default(1),
	'unit?': type(
		/** @type {type.cast<typeof NumericUnit.infer>} */
		('string')
	).describe('Unité dans laquelle la valeur est exprimée'),
	confirmed: type('boolean')
		.describe('Si la valeur a été manuellement confirmée comme correcte')
		.default(false),
	manuallyModified: type('boolean')
		.describe('Si la valeur a été modifiée manuellement')
		.default(false),
	isDefault: type('boolean')
		.describe('Si la valeur est la valeur par défaut définie dans le protocole')
		.default(false),
	alternatives: MetadataValueMain.array().default(() => []),
	confidences: {
		'[string.json]': Probability,
	},
});
 
export const MetadataValues = type.Record(NamespacedMetadataID, MetadataValue);
 
const JSONSchemaCompatibleRuntimeValue = type.or(
	'null',
	MetadataRuntimeValue.boolean,
	MetadataRuntimeValue.integer,
	MetadataRuntimeValue.float,
	MetadataRuntimeValue.string,
	// MetadataRuntimeValue.date
	// Date is not compatible with JSON Schemas, use a datestring instead
	'string.date.iso',
	MetadataRuntimeValue.location,
	MetadataRuntimeValue.boundingbox,
	MetadataRuntimeValue.file
);
 
export const MetadataRecordValue = MetadataValue.omit('value', 'alternatives').and({
	value: [JSONSchemaCompatibleRuntimeValue, '@', 'Valeur de la métadonnée'],
	alternatives: [
		JSONSchemaCompatibleRuntimeValue.array(),
		'@',
		'Valeurs alternatives pour la métadonnée',
	],
	'valueLabel?': [
		'string',
		'@',
		"Label de la valeur de la métadonnée. Existe pour les métadonnées de type enum, contient dans ce cas le label associé à la clé de l'option de l'enum choisie",
	],
	'baseUnitValue?': type('number').describe(
		"Si la métadonnée a une unité, c'est la valeur convertie dans l'unité de base définie pour cette métadonnée."
	),
});
 
/**
 * @template {string} K
 * @param {type.Any<K>} keySchema
 */
export const MetadataRecord = (keySchema) => type.Record(keySchema, MetadataRecordValue);
 
/**
 * @satisfies { Record<string, { label: string; help: string }> }
 */
export const METADATA_MERGE_METHODS = /** @type {const} */ ({
	min: {
		label: 'Minimum',
		help: "Choisir la valeur avec la meilleure confiance, et prendre la plus petite valeur en cas d'ambuiguité",
	},
	max: {
		label: 'Maximum',
		help: "Choisir la valeur avec la meilleure confiance, et prendre la plus grande valeur en cas d'ambuiguité",
	},
	average: {
		label: 'Moyenne',
		help: 'Prend la moyenne des valeurs',
	},
	median: {
		label: 'Médiane',
		help: 'Prend la médiane des valeurs',
	},
	union: {
		label: 'Union',
		help: 'Spécifique aux boîtes de recadrage: fusionne les boîtes de recadrage en la plus petite boîte englobant toutes les boîtes',
	},
	none: {
		label: 'Aucune',
		help: 'Ne pas fusionner',
	},
});
 
export const MetadataMergeMethod = type.or(
	type('"min"', '@', METADATA_MERGE_METHODS.min.help),
	type('"max"', '@', METADATA_MERGE_METHODS.max.help),
	type('"average"', '@', METADATA_MERGE_METHODS.average.help),
	type('"median"', '@', METADATA_MERGE_METHODS.median.help),
	type('"none"', '@', METADATA_MERGE_METHODS.none.help),
	type('"union"', '@', METADATA_MERGE_METHODS.union.help)
);
 
export const MetadataEnumVariant = type({
	key: [ID, '@', 'Identifiant unique pour cette option'],
	label: ['string', '@', "Nom de l'option, affichable dans une interface utilisateur"],
	'kobocollect?': [
		'string | string[]',
		'@',
		'Valeur(s) (nom technique, sans espaces) de la métadonnée',
	],
	synonyms: type('string[]')
		.describe('Synonymes (labels alternatifs) pour cette option')
		.default(() => []),
	'description?': type('string').describe('Description (optionnelle) de cette option'),
	'index?': type('number').describe(
		"Nombre permettant de trier les options dans l'interface. Par défaut, correspond à l'indice de l'option dans l'ordre de définition de sa métadonnée"
	),
	'image?': URLString.configure({
		deprecated: true,
		description:
			"Image illustrant cette option de l'énumération. Utiliser plutôt `images` avec un seul élément.",
	}),
	'images?': URLString.array().describe(
		"Liste d'images illustrant cette option de l'énumération. Permet d'en spécifier plusieurs"
	),
	'learnMore?': URLString.describe(
		"Lien pour en savoir plus sur cette option de l'énumération en particulier"
	),
	'color?': ColorHex.describe(
		"Code hexadécimal (avec ou sans le # préfixe) d'une couleur associée à cette option, pour l'affichage dans l'interface"
	),
	'icon?': type(/^ri:[\w-]+$/).describe(
		"Code Iconify d'une icône associée à cette option, provenant du pack d'icônes “Remix Icon”. Voir https://icon-sets.iconify.design/ri/ pour la liste."
	),
	narrowerWeights: type
		.Record(ID, '0 <= number <= 1')
		.describe(
			"Uniquement utile sur les métadonnées de classification (dont les options sont les candidats en mode Élimination). Poids à donner pour influencer l'ordre d'affichage des métadonnées en mode Élimination. un nombre élevé la mettra plus proche. Le poids utilisé pour trier est la moyenne des poids pour chacun des candidats non éliminés. Les clés sont les identifiants des métadonnées (descripteurs), et les valeurs sont les poids à appliquer pour cette option. Correspond à la notion de poids dans Xper3 (https://xper3.fr/wp-content/uploads/2024/10/ikey_UserGuide_2011.pdf, section 1.2.9 Weight parameters)"
		)
		.default(() => ({})),
	'cascade?': type
		.Record(ID, ID.array().or(ID))
		.pipe((record) => mapValues(record, ensureArray))
		.describe(
			"Objet contenant pour clés des identifiants d'autres métadonnées, et pour valeurs la ou les valeur(s) à assigner à cette métadonnée si cette option est choisie. Si il y en a plusieurs, une des options est choisie comme valeur de la métadonnée en question, et les autres sont mises en tant qu'alternatives, avec une confiance de 1."
		),
	// --- Technical fields ---
	/** Metadata group names that are narrowable and that have at least one metadata that exists in the enum variant's cascades. Used for indexing purposes: can be used to get all species that are narrowable by metadata of a certain metadata group. This is not set automatically (as the computation requires access to metadata definitions and metadata groups of the enum variant's protocol) */
	_narrowableIn: type('string[]').default(() => []),
});
 
export const EXIFField = type.enumerated(...keys(EXIF_FIELDS));
 
export const EXIFInference = EXIFField.describe('Inférer depuis un champ EXIF', 'self');
 
export const SidecarFilepathTemplatePayload = type({
	filepath: ['string', '@', "Chemin vers le fichier de l'image traitée"],
	// TODO more stuff
});
 
export const SidecarFilepathTemplate = FilepathTemplate(SidecarFilepathTemplatePayload).describe(
	"Un template pour construire le filepath du fichier sidecar à partir duquel inférer la valeur de la métadonnée. Les variables disponibles pour construire ce filepath sont à définir, mais devraient au minimum inclure le filepath de l'image, et potentiellement d'autres métadonnées de l'image ou de l'observation"
);
 
/**
 * @template {import('arktype').Type} T
 * @param {T} QueryOutput
 */
export const SidecarInference = (QueryOutput) =>
	type.or(
		type('string').pipe((query) => ({
			query: JsonataExpression(type.unknown, QueryOutput).assert(query),
			filepath: undefined,
		})),
		{
			filepath: SidecarFilepathTemplate.describe(
				"Une template handlebars pour calculer le chemin vers le fichier Sidecar à partir du chemin de l'image (accessible avec la variable `filepath`). Il est possible égalemnt de préciser une simple expression JQ au lieu d'un objet filepath+query, si l'on utilise le fichier annexe par défault, définit par le protocole (voir sidecars.filepath)"
			),
			query: JsonataExpression(type.unknown, QueryOutput).describe(
				'Un expression Jsonata (https://docs.jsonata.org/) pour extraire la valeur depuis le fichier sidecar'
			),
		}
	);
 
export const InferenceConfigs = /** @type {const} */ ({
	exif: type({
		exif: EXIFInference.describe("Inférer depuis les données EXIF de l'image"),
	}),
 
	/**
	 * @template {import('arktype').Type} T
	 * @param {T} QueryOutput
	 */
	sidecar: (QueryOutput) =>
		type({
			sidecar: SidecarInference(QueryOutput).describe(
				"Inférer depuis un fichier annexe associé à l'image, dont le nom dépend du nom de l'image associée. Le fichier doit être au format JSON ou XML. L'inférence se fait à l'aide d'une expression Jsonata (https://docs.jsonata.org/), qui permet d'extraire la valeur de la métadonnée depuis ce fichier"
			),
		}),
 
	neuralEnum: type({
		neural: NeuralEnumInference.array().describe(
			'Inférer depuis un ou plusieurs réseaux neuronaux de classification'
		),
	}),
	neuralBoundingBox: type({
		neural: NeuralBoundingBoxInference.array().describe(
			"Inférer depuis un ou plusieurs réseaux neuronaux de détection d'objets"
		),
	}),
});
 
export const MetadataDefaultDynamicPayload = type({
	protocolMetadata: MetadataRecord(NamespacedMetadataID),
	metadata: MetadataRecord(ID),
	session: {
		protocolMetadata: MetadataRecord(NamespacedMetadataID),
		metadata: MetadataRecord(ID),
		createdAt: 'string.date.iso',
	},
});
 
export const MetadataDefault = scope({ MetadataRuntimeValueAny }).type(
	'<static extends MetadataRuntimeValueAny>',
	[
		[
			'Exclude<static, string>',
			'@',
			"Une valeur par défaut pour une métadonnée. Pour l'instant, uniquement supportée sur les métadonnées de session",
		],
		'|',
		TemplatedString(MetadataDefaultDynamicPayload, (serialized) => {
			const parsed = MetadataValue.get('value')(serialized);
 
			if (parsed instanceof ArkErrors) {
				return serialized.trim();
			}
 
			return parsed;
		}).describe(
			"Une valeur par défaut dynamique. Pour l'instant, uniquement supportée sur les métadonnées de session. C'est une templates Handlebars, avec pour variables `protocolMetadata` (contenant les métadonnées du protocole courant) et `metadata` (contenant les métadonnées de _toutes_ les métadonnées). La valeur par défaut sera évaluée en considérant que le texte final (après éxécution de la template Handlebars) est une représentation JSON (sauf pour les métadonnées de type texte ou enum, où le text final est pris tel-quel). Les helpers gps, boundingBox, date, object et array sont disponibles pour facilement construire des représentations JSON de valeurs complexes"
		),
	]
);
 
export const MetadataPatternConstraint = type.or();
 
/**
 * @typedef {typeof EXIFInference.infer} EXIFInference
 */
 
const MetadataBase = type({
	id: NamespacedMetadataID.describe(
		'Identifiant unique pour la métadonnée. On conseille de mettre une partie qui vous identifie dans cet identifiant, car il doit être globalement unique. Par exemple, mon-organisation.ma-métadonnée'
	),
	'inheritedFrom?': ProtocolID.describe(
		"Si cette métadonnée est héritée d'un autre protocole, indique de quel protocole elle est héritée"
	),
	label: ['string', '@', 'Nom de la métadonnée'],
	'kobocollect?': [
		'string | string[]',
		'@',
		'Label(s) ou nom(s) de colonne de la question Kobocollect associée à cette métadonnée. Non sensible à la casse',
	],
	'classification?': [
		'boolean',
		'@',
		'Marque la métadonnée comme utilisable comme métadonnée de classification',
	],
	'group?': ID.brand('MetadataGroup').describe(
		'Identifiant du groupe dans lequel mettre cette métadonnée. Voir le champ metadataGroups du protocole'
	),
	// TODO: move to type-specific branches (e.g. for boundingbox, it's union | none, for others there isnt union, ...)
	// Get the allowed per-type methods from mergeBy<method> functions' declarations (add a satisfies to the implementations' type switches and export a const for each method)
	mergeMethod: MetadataMergeMethod.configure(
		"Méthode utiliser pour fusionner plusieurs différentes valeurs d'une métadonnée. Notamment utilisé pour calculer la valeur d'une métadonnée sur une Observation à partir de ses images",
		'self'
	),
	required: ['boolean', '@', 'Si la métadonnée est obligatoire'],
	description: ['string', '@', 'Description, pour aider à comprendre la métadonnée'],
	images: URLString.array()
		.describe(
			"Liste d'images illustrant cette métadonnée. Utile pour aider les utilisateurs à comprendre ce que représente la métadonnée"
		)
		.default(() => []),
	sortable: type('boolean')
		.describe('Si la métadonnée peut être utilisée pour trier des images ou observations')
		.default(false),
	groupable: type('boolean')
		.describe('Si la métadonnée peut être utilisée pour grouper des images ou observations')
		.default(false),
	// TODO move to the type: '"enum"' only branch
	'options?': MetadataEnumVariant.array()
		.pipe((opts) => unique(opts, (o) => o.key))
		.pipe((opts) => opts.map((opt, index) => ({ index, ...opt })))
		.describe('Les options valides. Uniquement utile pour une métadonnée de type "enum"'),
	learnMore: URLString.describe(
		'Un lien pour en apprendre plus sur ce que cette métadonnée décrit'
	).optional(),
});
 
const MetadataBoolean = MetadataBase.omit('kobocollect').and({
	type: '"boolean"',
	'default?': MetadataDefault('boolean'),
	'infer?': type.and(
		InferenceConfigs.exif.partial(),
		InferenceConfigs.sidecar(type('boolean')).partial()
	),
	'kobocollect?': type.or(
		{
			'list?': [
				'string | string[]',
				'@',
				'Label(s) ou nom(s) de colonne de la question Kobocollect associée (question à choix)',
			],
			true: [
				'string | string[]',
				'@',
				'Label(s) ou nom(s) technique du choix associé à Vrai. Mettre OK pour une question de type "Acknowledge"',
			],
			false: [
				'string | string[]',
				'@',
				'Label(s) ou nom(s) technique du choix associé à Faux. Mettre "" pour une question de type "Acknowledge"',
			],
		},
		{
			'list?': [
				'string | string[]',
				'@',
				'Label(s) ou nom(s) de colonne de la question Kobocollect associée (question à choix multiples)',
			],
			choice: [
				'string | string[]',
				'@',
				'Label(s) ou nom(s) technique du choix à cocher si cette métadonnée est vraie',
			],
		}
	),
});
 
export const MetadataString = MetadataBase.and({
	type: '"string"',
	'default?': MetadataDefault('string'),
	'infer?': type.and(
		InferenceConfigs.exif.partial(),
		InferenceConfigs.sidecar(type('string')).partial()
	),
	'regex?': RegexExpression.describe(
		'Une expression régulière que la valeur de cette métadonnée doit respecter'
	),
	'pattern?': NaturalRegexExpression,
});
 
export const MetadataInteger = MetadataBase.and({
	type: '"integer"',
	'range?': NumberRangeLiteral,
	'default?': MetadataDefault('number.integer'),
	'infer?': type.and(
		InferenceConfigs.exif.partial(),
		InferenceConfigs.sidecar(type('number.integer')).partial()
	),
	'unit?': NumericUnit,
});
 
export const MetadataFloat = MetadataBase.and({
	type: '"float"',
	'range?': NumberRangeLiteral,
	'default?': MetadataDefault('number'),
	'infer?': type.and(
		InferenceConfigs.exif.partial(),
		InferenceConfigs.sidecar(type('number')).partial()
	),
	'unit?': NumericUnit,
	'cascade?': type
		.Record(NamespacedMetadataOptionID, NumberRangeLiteral)
		.describe(
			"Associe des options d'une métadonnée (de type Enum) dont la valeur changera si cette métadonnée a une valeur dans la plage spécifiée. Par exemple, en mettant `{'A:1': '0..5', 'A:2': '5..10', 'A:3': '10..15'}`, la métadonnée A sera mise à jour sur les options 1 et (en alternative) 2, si la valeur de cette métadonnée est mise à 5. (car on sera dans la plage 0..5 et 5..10)"
		),
});
 
export const MetadataDate = MetadataBase.and({
	type: '"date"',
	'range?': '"future" | "past"',
	'default?': MetadataDefault('string.date.iso'),
	'infer?': type.and(
		InferenceConfigs.exif.partial(),
		InferenceConfigs.sidecar(type('string.date.iso.parse')).partial()
	),
});
 
const MetadataLocation = MetadataBase.and({
	type: '"location"',
	'default?': MetadataDefault({ latitude: 'number', longitude: 'number' }),
	'infer?': type.and(
		InferenceConfigs.sidecar(
			type({ latitude: 'number', longitude: 'number', '+': 'reject' })
		).partial(),
		type({
			latitude: InferenceConfigs.exif,
			longitude: InferenceConfigs.exif,
		}).partial()
	),
});
 
const MetadataEnum = MetadataBase.and({
	type: '"enum"',
	'default?': MetadataDefault('string | number'),
	presentation: type
		.enumerated('dropdown', 'buttons', 'auto')
		.describe(
			"Comment présenter les options de cette métadonnée dans l'interface utilisateur. Dropdown pour une liste déroulante avec recherche, Buttons pour des boutons affichant directement toutes les optiosn, Auto pour laisser l'application décider (souvent en fonction du nombre d'options)"
		)
		.default('auto'),
	'infer?': type.and(
		InferenceConfigs.exif.partial(),
		InferenceConfigs.sidecar(type('string|number')).partial(),
		InferenceConfigs.neuralEnum.partial()
	),
	// --- Technical fields ---
	_optionsCount: 'number.integer = 0',
});
 
const MetadataBoundingbox = MetadataBase.and({
	type: '"boundingbox"',
	'default?': MetadataDefault({
		x: '0 <= number <= 1',
		y: '0 <= number <= 1',
		w: '0 <= number <= 1',
		h: '0 <= number <= 1',
	}),
	'infer?': type.and(
		InferenceConfigs.neuralBoundingBox.partial(),
		InferenceConfigs.sidecar(
			type({
				'+': 'reject',
				...transformObject(
					MODEL_DETECTION_OUTPUT_SHAPES,
					(shape) =>
						/** @type {const} */
						([shape, type('0 <= number <= 1').optional()])
				),
			})
				.array()
				.pipe((boxes) =>
					boxes.map((box) => {
						const atoms = entries(box).filter(([_, value]) => value !== undefined);
						const resolver = boundingBoxResolver(atoms.map(([shape]) => shape));
						return resolver(
							0,
							atoms.map(([_, value]) => value ?? 0)
						);
					})
				)
		).partial()
	),
});
 
export const MetadataFile = MetadataBase.and({
	type: '"file"',
	'default?': 'null',
	'infer?': type.and(
		InferenceConfigs.sidecar(
			type({
				name: 'string',
				'type?': MIMEType,
				'lastModified?': 'number',
				content: type.or('string', ['instanceof', Uint8Array]),
			}).pipe(({ name, content, ...attrs }) => new File([content], name, attrs))
		).partial()
	),
	size: type({ 'minimum?': FileSize, 'maximum?': FileSize })
		.describe('Limites sur la taille du fichier')
		.default(() => ({})),
	accept: UniqueFileTypeSpecifier.array()
		.pipe((specs) => specs.join(', '))
		.describe('Fichiers acceptés pour cette métadonnée')
		.default(() => []),
});
 
export const Metadata = type.or(
	MetadataBoolean,
	MetadataString,
	MetadataInteger,
	MetadataFloat,
	MetadataDate,
	MetadataLocation,
	MetadataEnum,
	MetadataBoundingbox,
	MetadataFile
);
 
export const MetadataGroup = type({
	id: ID.brand('MetadataGroup'),
	name: 'string',
	description: "string = ''",
	narrowable: type(
		'boolean',
		'@',
		"Si le groupe peut être utilisé pour classifier une observation en mode 'élimination'. Dans ce mode, on propose de choisir des valeurs dans l'ensemble des métadonnées du groupe narrowable choisi, afin de réduire une liste de candidats possibles (les candidats sont les options de la métadonnée de classification (par exemple, 'Espèce') tels que leurs cascades correspondent à l'ensemble des choix effectués sur les métadonnées du groupe narrowable)"
	).default(false),
	collapsed: type(
		'boolean',
		'@',
		"Si le groupe doit être replié par défaut dans l'interface utilisateur. Utile pour les groupes contenant beaucoup de métadonnées ou des métadonnées peu importantes"
	).default(false),
});
 
/**
 * Ensures a metadata ID is namespaced to the given protocol ID
 * If the ID is already namespaced, the existing namespace is re-namespaced to the given protocol ID.
 * @template {string} P
 * @param {P} protocolId
 * @param {string} metadataId
 * @returns {NamespacedMetadataID<P>}
 */
export function namespacedMetadataId(protocolId, metadataId) {
	metadataId = metadataId.replace(/^.+__/, '');
	return `${protocolId}__${metadataId}`;
}
 
/**
 * Ensures a metadata ID is namespaced to the given protocol ID. If the metadata ID is not namespaced, it will be prefixed with the protocol ID. If it already is namespaced, it will stay as is.
 * @param {string} metadataId the metadata ID to ensure is namespaced
 * @param {string} fallbackProtocolId the protocol ID to use if the metadata ID is not namespaced
 */
export function ensureNamespacedMetadataId(metadataId, fallbackProtocolId) {
	Eif (isNamespacedToProtocol(fallbackProtocolId, metadataId)) return metadataId;
	return namespacedMetadataId(fallbackProtocolId, metadataId);
}
 
/**
 * @template {string} ProtocolID
 * @overload
 * @param {ProtocolID} protocolId
 * @param {string} metadataId
 * @returns {metadataId is NamespacedMetadataID<ProtocolID>}
 */
 
/**
 * @overload
 * @param {null} protocolId
 * @param {string} metadataId
 * @returns {metadataId is NamespacedMetadataID<string>}
 */
 
/**
 * Checks if a given metadata ID is namespaced to a given protocol ID
 * @param {null | string} protocolId
 * @param {string} metadataId
 */
export function isNamespacedToProtocol(protocolId, metadataId) {
	if (protocolId) return metadataId.startsWith(`${protocolId}__`);
 
	return metadataId.includes('__');
}
 
/**
 *
 * @param {string} metadataId
 * @returns {string}
 */
export function removeNamespaceFromMetadataId(metadataId) {
	return metadataId.replace(/^.+__/, '');
}
 
/**
 * @overload
 * @param {NamespacedMetadataID} metadataId
 * @returns {string}
 */
 
/**
 * @overload
 * @param {string} metadataId
 * @returns {string	| undefined}
 */
 
/**
 * @overload
 * @param {undefined | NamespacedMetadataID} metadataId
 * @returns {undefined|string}
 */
 
/**
 *
 * @param {string|undefined} metadataId
 * @returns
 */
export function namespaceOfMetadataId(metadataId) {
	Iif (!metadataId) return undefined;
	const parts = metadataId.split('__');
	Iif (parts.length < 2) return undefined;
	return parts.slice(0, -1).join('__');
}
 
/**
 * @overload
 * @param {NamespacedMetadataID} metadataId
 * @returns {{ namespace: string, id: string }}
 */
 
/**
 * @overload
 * @param {string} metadataId
 * @returns {{ namespace: string | undefined, id: string }}
 */
 
/**
 *
 * @param {string} metadataId
 */
export function splitMetadataId(metadataId) {
	return {
		namespace: namespaceOfMetadataId(metadataId),
		id: removeNamespaceFromMetadataId(metadataId),
	};
}