All files / lib/schemas common.js

48.05% Statements 37/77
8.33% Branches 3/36
43.75% Functions 14/32
47.88% Lines 34/71

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            21x   21x       21x                 77x             98x         21x   21x   21x                                   21x     71x           21x                 2x 2x                   4x                                         4x                                                                                                                                                                                                                                                                                                                                                                             21x 357x                 21x 75x 36x 36x       612x     36x 10x           12x   12x                       21x 36x   21x               21x                     21x         21x                                                                                       21x 18x                    
import { type } from 'arktype';
import { format as formatDate } from 'date-fns';
import Handlebars from 'handlebars';
 
import { clamp, mapValues, safeJSONStringify, splitFilenameOnExtension } from '../utils.js';
 
export const ID = type(/^[\w._-]+$/);
 
export const ProtocolID = type(/[\w.-]+/).describe(
	'Identifiant unique pour un protocole. On conseille de mettre une partie qui vous identifie dans cet identifiant, car il doit être globalement unique. Par exemple, fr.sete-moulis-cnrs.mon-protocole si vous contrôler le nom de domain sete-moulis.cnrs.fr'
);
 
export const NamespacedMetadataID = type('/^([\\w.-]+)__([\\w._-]+)$/').describe(
	'Identifiant de métadonnée avec namespace, sous la forme "protocolId__metadataId"'
);
 
/**
 * @template {string} [P=string]
 * @typedef {`${P}__${string}`} NamespacedMetadataID
 */
 
export const References = ID.array().pipe((ids) => [...new Set(ids)]);
 
/**
 * Between 0 and 1
 * Allow slightly above 1 to account for floating point imprecision,
 * but clamp it back to [0, 1]
 */
export const Probability = type('0 <= number <= 1.0001').pipe((n) => clamp(n, 0, 1));
 
/**
 * Can't use string.url.parse because it prevents us from generating JSON schemas
 */
export const URLString = type(/https?:\/\/.+/);
 
export const ColorHex = type(/^#?[0-9A-Fa-f]{6}$/).pipe((s) => (s.startsWith('#') ? s : `#${s}`));
 
export const HTTPRequest = URLString.configure(
	"L'URL à laquelle se situe le fichier. Effectue une requête GET sans en-têtes particuliers.",
	'self'
)
	.or({
		url: URLString.describe("L'URL de la requête"),
		'headers?': type({ '[string]': 'string' }).describe(
			'Les en-têtes à ajouter dans la requête'
		),
		'method?': type
			.enumerated('GET', 'POST', 'PUT', 'DELETE')
			.describe('La méthode de la requête (GET par défaut)')
	})
	.configure(
		'Le requête HTTP pour obtenir le fichier, avec des en-têtes et une méthode personnalisable',
		'self'
	);
 
export const Dimensions = type({
	width: 'number > 0',
	height: 'number > 0'
}).pipe(({ width, height }) => ({
	width,
	height,
	aspectRatio: width / height
}));
 
export const HANDLEBARS_HELPERS = {
	suffix: {
		documentation: "Ajoute un suffixe à un nom de fichier, avant l'extension",
		usage: "{{ suffix 'filename.jpeg' '_example' }} -> 'filename_example.jpeg'",
		/**
		 * @param {string} subject
		 * @param {string} suffix
		 */
		implementation: (subject, suffix) => {
			const [stem, ext] = splitFilenameOnExtension(subject);
			return `${stem}${suffix}.${ext}`;
		}
	},
	extension: {
		documentation: 'Récupère l’extension d’un nom de fichier',
		usage: "{{ extension 'filename.jpeg' }} -> 'jpeg'",
		/**
		 * @param {string} subject
		 */
		implementation: (subject) => {
			return splitFilenameOnExtension(subject)[1];
		}
	},
	stem: {
		documentation: 'Récupère le nom d’un fichier sans son extension',
		usage: "{{ stem 'filename.jpeg' }} -> 'filename'",
		/**
		 * @param {string} subject
		 */
		implementation: (subject) => {
			return splitFilenameOnExtension(subject)[0];
		}
	},
	fallback: {
		documentation: 'Fournit une valeur de repli si la première est indéfinie',
		usage: "{{ fallback obj.does_not_exist 'Unknown' }} -> 'Unknown'",
		/**
		 * @param {string} subject
		 * @param {string} fallback
		 */
		implementation: (subject, fallback) => {
			return subject ?? fallback;
		}
	},
	metadata: {
		documentation:
			"Récupère la valeur d'une métadonnée sur un subjet (une session, une observation ou une image) donnée. L'ID de la métadonnée peut ne pas comporter de namespace. Dans ce cas, le namespace correspondant au protocole courant est utilisé. Renvoie null si la métadonnée n'existe pas.",
		usage: "{{ metadata session 'transect_code' }} -> 'TR123'",
		/**
		 * @param {{ [ K in "protocolMetadata" | "metadata"]: import('$lib/database.js').MetadataValues } | { [ K in "metadataOverrides" | "protocolMetadataOverrides"]: import('$lib/database.js').MetadataValues }} subject
		 * @param {import('$lib/schemas/common.js').NamespacedMetadataID} metadataId
		 */
		implementation: (subject, metadataId) => {
			if ('metadata' in subject) {
				return (
					subject.protocolMetadata[metadataId]?.value ??
					subject.metadata[metadataId]?.value ??
					null
				);
			}
 
			if ('metadataOverrides' in subject) {
				return (
					subject.protocolMetadataOverrides[metadataId]?.value ??
					subject.metadataOverrides[metadataId]?.value ??
					null
				);
			}
 
			throw new Error('Subject must have either metadata or metadataOverrides property');
		}
	},
	now: {
		documentation:
			'Renvoie la date actuelle dans le format précisé. Voir https://date-fns.org/v4.1.0/docs/format pour une description complète du format',
		usage: "{{ now \"dd/MM/yyyy 'à' HH:mm\" }} -> '31/12/2026 à 23:59'",
		/**
		 * @param {string} format
		 */
		implementation: (format) => {
			return formatDate(Date.now(), format);
		}
	},
	year: {
		documentation: "Renvoie l’année d'une date sur 4 chiffres",
		usage: "{{ year '2024-12-31' }} -> '2024'",
		/**
		 * @param {string} date
		 */
		implementation: (date) => {
			return formatDate(new Date(date), 'yyyy');
		}
	},
	month: {
		documentation: "Renvoie le mois d'une date sur 2 chiffres",
		usage: "{{ month '2024-12-31' }} -> '12'",
		/**
		 * @param {string} date
		 */
		implementation: (date) => {
			return formatDate(new Date(date), 'MM');
		}
	},
	day: {
		documentation: "Renvoie le jour d'une date sur 2 chiffres",
		usage: "{{ day '2024-12-31' }} -> '31'",
		/**
		 * @param {string} date
		 */
		implementation: (date) => {
			return formatDate(new Date(date), 'dd');
		}
	},
	hour: {
		documentation: "Renvoie l'heure d'une date sur 2 chiffres",
		usage: "{{ hour '2024-12-31T23:59' }} -> '23'",
		/**
		 * @param {string} date
		 */
		implementation: (date) => {
			return formatDate(new Date(date), 'HH');
		}
	},
	minute: {
		documentation: "Renvoie les minutes d'une date sur 2 chiffres",
		usage: "{{ minute '2024-12-31T23:59' }} -> '59'",
		/**
		 * @param {string} date
		 */
		implementation: (date) => {
			return formatDate(new Date(date), 'mm');
		}
	},
	second: {
		documentation: "Renvoie les secondes d'une date sur 2 chiffres",
		usage: "{{ second '2024-12-31T23:59:01' }} -> '01'",
		/**
		 * @param {string} date
		 */
		implementation: (date) => {
			return formatDate(new Date(date), 'ss');
		}
	},
	date: {
		documentation:
			"Construire une date à partir de ses composantes. il est possible d'omettre les noms des composantes si on les donne dans l'ordre descendant (year, ..., minutes). toutes les composantes sont optionelles à partir des heures (et valent 0 par défaut). Les dates sont interprétées localement (dans le fuseau horaire local) ",
		usage: "{{ date year=2024 month=12 day=31 hours=23 minutes=59 seconds=1.5 }} -> '2024-12-31T23:59:01.500+02:00'",
		/**
		 * @param {number} year
		 * @param {number} month
		 * @param {number} day
		 * @param {number | undefined} hours
		 * @param {number | undefined} minutes
		 * @param {{hash: { year?: number, month?: number, day?: number, hours?: number, minutes?: number, seconds?: number}}} options
		 */
		implementation: (year, month, day, hours, minutes, { hash }) => {
			const seconds = hash.seconds ?? 0;
 
			return new Date(
				year,
				month - 1, // JavaScript 🥰
				day,
				hours ?? hash.hours ?? 0,
				minutes ?? hash.minutes ?? 0,
				Math.floor(seconds),
				Math.round((seconds - Math.floor(seconds)) * 1000)
			);
		}
	},
	object: {
		documentation:
			"Crée une représentation JSON d'un objet en prenant les paramètres comme paires clé-valeur",
		usage: '{{ object key1=\'value1\' key2=\'value2\' }} -> \'{"key1":"value1","key2":"value2"}\'',
		/**
		 * @param {{hash: Record<string, unknown>}} options
		 */
		implementation: ({ hash }) => {
			return safeJSONStringify(hash);
		}
	},
	array: {
		documentation:
			"Crée une représentation JSON d'un tableau en prenant les paramètres comme éléments du tableau",
		usage: "{{ array 'value1' 'value2' }} -> '[\"value1\",\"value2\"]'",
		/**
		 * @param {unknown} e0
		 * @param {unknown} e1
		 * @param {unknown} e2
		 * @param {unknown} e3
		 * @param {unknown} e4
		 * @param {unknown} e5
		 */
		implementation: (e0, e1, e2, e3, e4, e5) => {
			return safeJSONStringify([e0, e1, e2, e3, e4, e5].filter((e) => e !== undefined));
		}
	},
	gps: {
		documentation:
			'Crée une représetation JSON des coordonnées GPS données (latitude puis longitude)',
		usage: '{{ gps 42.957408 1.0859884 }} -> \'{"latitude": 42.957408, "longitude": 1.0859884}\'',
		/**
		 * @param {number} latitude
		 * @param {number} longitude
		 */
		implementation: (latitude, longitude) => {
			return safeJSONStringify({ latitude, longitude });
		}
	},
	boundingBox: {
		documentation:
			'Crée une représentation JSON d’une bounding box à partir de ses coordonnées normalisées (x, y, w, h)',
		usage: '{{ boundingBox 0.5 0.5 1 1 }} -> \'{"x":0.5,"y":0.5,"w":1,"h":1}\'',
		/**
		 * @param {number} x
		 * @param {number} y
		 * @param {number} w
		 * @param {number} h
		 */
		implementation: (x, y, w, h) => {
			return safeJSONStringify({ x, y, w, h });
		}
	}
};
 
for (const [name, { implementation }] of Object.entries(HANDLEBARS_HELPERS)) {
	Handlebars.registerHelper(name, implementation);
}
 
/**
 * @template {import("arktype").Type} T
 * @template {any} [O=string]
 * @param {T} Input
 * @param {(output: string) => O} [postprocess]
 */
export const TemplatedString = (Input, postprocess) =>
	type.string.pipe((t) => {
		try {
			const compiled = Handlebars.compile(t, {
				noEscape: true,
				assumeObjects: true,
				knownHelpersOnly: true,
				knownHelpers: mapValues(HANDLEBARS_HELPERS, () => true)
			});
 
			return {
				toJSON: () => t,
				/**
				 * @param {T["inferIn"]} data
				 * @returns {O}
				 */
				render(data) {
					const rendered = compiled(Input.assert(data));
					// @ts-ignore
					return postprocess ? postprocess(rendered) : rendered;
				}
			};
		} catch (cause) {
			throw new Error(`Invalid template ${safeJSONStringify(t)}`, { cause });
		}
	});
 
/**
 * @template {import("arktype").Type} T
 * @param {T} Input
 */
export const FilepathTemplate = (Input) =>
	TemplatedString(Input, (path) => path.replaceAll('\\', '/'));
 
export const MIMEType = type(
	/^(application|audio|font|example|image|message|model|multipart|text|video|x-\w+)\/\w+$/
);
 
/**
 * Describes valid values of `<input type=file>`'s "accept" list
 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/file#unique_file_type_specifiers
 */
export const UniqueFileTypeSpecifier = type.or(
	[/^\..+$/, '@', 'Une extension de fichier'],
	[MIMEType, '@', 'Un type MIME'],
	['"audio/*"', '@', 'Un fichier audio'],
	['"video/*"', '@', 'Un fichier vidéo'],
	['"image/*"', '@', 'Un fichier image']
);
 
// XXX: Most JSON schema integrations don't support named capture groups...
const FILE_SIZE_PATTERN =
	// /^\s*(?<amount>\d+(\.\d+)?)\s+(?<prefix>[kMGTP])(?<binary>i?)(?<unit>[oBb])\s*$/i;
	/^\s*(\d+(?:[.,]\d+)?)\s+([kMGTP]?)(i?)([oBb])\s*$/i;
 
/**
 * Parse a human-readable file size (e.g. "2.5 MB") into a number of bytes
 */
export const FileSize = type('number')
	.describe('Une taille de fichier exprimée en octets')
	.or(
		type(FILE_SIZE_PATTERN)
			.pipe.try((literal) => {
				const match = literal.match(FILE_SIZE_PATTERN);
				if (!match) throw new Error(`Invalid file size: ${literal}`);
 
				const [_, amountString, prefix, binary, unit] = match;
 
				let amount = Number.parseFloat(amountString.replace(',', '.'));
				if (Number.isNaN(amount))
					throw new Error(`Invalid file size amount: ${amountString} is ${amount}`);
 
				const power = {
					'': 0,
					K: 3,
					M: 6,
					G: 9,
					T: 12,
					P: 15
				}[prefix.toUpperCase()];
 
				const base = binary ? 2 : 10;
 
				amount *= Math.pow(base, power ?? 0);
 
				if (unit === 'b') {
					amount /= 8;
				}
 
				return amount;
			})
			.describe(
				"Une taille de fichier sous une forme plus lisible comme '2.5 MB' (les suffixes k, M, G, T et P sont supportés, avec une base 10 ou 2 selon la présence du suffixe 'i', et les unités 'B'/'o' ou 'b' sont supportées pour indiquer si le nombre donné est en bits ou en octets)"
			)
	);
 
/**
 * @template {import("arktype").Type} K
 * @template {import("arktype").Type} V
 * @param {K} k
 * @param {V} v
 */
export const SingleEntryRecord = (k, v) =>
	type('Record<string, unknown>').pipe.try((obj) => {
		const entries = Object.entries(obj);
		if (entries.length !== 1) {
			throw new Error(
				`Expected an object with a single entry, but got ${entries.length} entries: ${safeJSONStringify(obj)}`
			);
		}
		const [key, value] = entries[0];
		return { key: k.assert(key), value: v.assert(value) };
	});