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 | 26x 2x 6x 4x 4x 6x 2x 6x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 2x 2x 2x 26x 650x 624x 650x 26x 624x 26x 650x 572x 650x 26x 139x 66x 66x 1584x 66x 10x 41x 41x 26x 271x 21x 21x 21x 462x 21x 21x 21x 21x 21x 21x 21x | /**
* Computed expression templates: Handlebars and Jsonata
*/
import { ArkErrors, type } from 'arktype';
import { format as formatDate, formatISO, parse as parseDate } from 'date-fns';
import Handlebars from 'handlebars';
import jsonata from 'jsonata';
import {
mapValues,
safeJSONStringify,
splitFilenameOnExtension,
transformObject,
} from '../utils.js';
/**
* @typedef {object} Helper
* @property {string} documentation
* @property {[string[], unknown]} usage [args, result]
* @property {((...args: any[]) => any)} [implementation]
* @property {((...args: any[]) => any)} [implementationHandlebars]
* @property {((...args: any[]) => any)} [implementationJsonata]
*/
/**
* @satisfies {Record<string, Helper>}
*/
export const HELPERS = /** @type {const} */ ({
titlecase: {
documentation:
'Met la première lettre de chaque mot en majuscule et les autres en minuscules',
usage: [["'some Test HERE!!'"], 'Some Test Here!!'],
/**
* @param {string} subject
*/
implementation(subject) {
return subject
.split(/\s/)
.map((word) => word.at(0)?.toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
},
},
suffix: {
documentation: "Ajoute un suffixe à un nom de fichier, avant l'extension",
usage: [["'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: [["'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: [["'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: [['obj.does_not_exist', "'Unknown'"], 'Unknown'],
/**
* @param {string} subject
* @param {string} fallback
*/
implementation(subject, fallback) {
return subject ?? fallback;
},
},
clamp: {
documentation: 'Contraindre un nombre à une plage donnée',
usage: [['101', '0', '100'], 100],
/**
* @param {number} value
* @param {number} min
* @param {number} max
*/
implementation(value, min, max) {
return Math.min(Math.max(value, min), max);
},
},
trim: {
documentation: 'Supprime les espaces au début et à la fin d’un texte',
usage: [["' some text '"], 'some text'],
/**
* @param {string} subject
*/
implementation(subject) {
return subject.trim();
},
},
percentage: {
documentation:
'Display a percentage string, with a optional number of decimals (default: 0)',
usage: [['0.1236', '1'], '12.4%'],
implementationHandlebars(...args) {
args.pop(); // Remove Handlebars options argument
const [value, decimals = 0] = args;
return `${(value * 100).toFixed(decimals)}%`;
},
implementationJsonata(value, decimals = 0) {
return `${(value * 100).toFixed(decimals)}%`;
},
},
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: [['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) {
Eif ('metadata' in subject) {
const record = subject.protocolMetadata ?? subject.metadata;
Eif (metadataId in record) return record[metadataId]?.value;
return null;
}
if ('metadataOverrides' in subject) {
const record = subject.protocolMetadataOverrides ?? subject.metadataOverrides;
if (metadataId in record) return record[metadataId]?.value;
return null;
}
throw new Error('Subject must have either metadata or metadataOverrides property');
},
},
now: {
documentation: 'Renvoie la date actuelle au format ISO',
usage: [[], '2026-12-31T23:59:00Z'],
implementation() {
return formatISO(new Date());
},
},
year: {
documentation: "Renvoie l’année d'une date sur 4 chiffres",
usage: [["'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: [["'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: [["'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: [["'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: [["'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: [["'2024-12-31T23:59:01'"], '01'],
/**
* @param {string} date
*/
implementation(date) {
return formatDate(new Date(date), 'ss');
},
},
json: {
documentation: 'Sérialise une valeur en JSON',
usage: [
['{ "key": { "nested1": "value1", "nested2": "value2" } }', '2'],
JSON.stringify({ key: { nested1: 'value1', nested2: 'value2' } }, null, 2),
],
/**
* @param {unknown} value
* @param {number | string | undefined} indentation
* @returns {string}
*/
implementationJsonata(value, indentation) {
return JSON.stringify(value, null, indentation);
},
},
slice: {
documentation: "Prendre une partie d'une liste ou d'un texte",
usage: [['"abcDEFgh"', '3', '6'], 'DEF'],
/**
* @param {string | unknown[]} subject
* @param {number} start
* @param {number} stop
*/
implementation(subject, start, stop) {
return subject.slice(start, stop);
},
},
parseDate: {
documentation: "Construire une date à partir d'un texte et d'un format",
usage: [['"202508311121"', '"yyyyMMddHHmm"'], '2025-08-31T11:21:00.000Z'],
/**
* @param {string} datestring
* @param {string} format
*/
implementation(datestring, format) {
return parseDate(datestring, format, new Date()).toISOString();
},
},
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: [
['year=2024', 'month=12', 'day=31', 'hours=23', 'minutes=58', 'seconds=1.5'],
'2024-12-31T23:58:01.500Z',
],
implementationHandlebars(...args) {
/** @type {{hash: { year?: number, month?: number, day?: number, hours?: number, minutes?: number, seconds?: number}}} */
const { hash } = args.pop();
const year = hash.year ?? args.shift();
const month = hash.month ?? args.shift();
const day = hash.day ?? args.shift();
const hours = hash.hours ?? args.shift() ?? 0;
const minutes = hash.minutes ?? args.shift() ?? 0;
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)
).toISOString();
},
},
formatDate: {
documentation: "Formatte une date à partir d'une date au format ISO",
usage: [["'2024-01-10T02:03:04Z'", "'dd/MM/yyyy'"], '10/01/2024'],
/**
* @param {string} datestring
* @param {string} format
*/
implementation(datestring, format) {
return formatDate(new Date(datestring), format);
},
},
object: {
documentation:
"Crée une représentation JSON d'un objet en prenant les paramètres comme paires clé-valeur",
usage: [
["key1='value1'", "key2='value2'"],
JSON.stringify({ key2: 'value2', key1: 'value1' }),
],
/**
* @param {{hash: Record<string, unknown>}} options
*/
implementationHandlebars({ 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: [
['"value1"', '"value2"'],
['value1', 'value2'],
],
implementationHandlebars(...args) {
args.pop(); // Remove hash argument added by Handlebars
return safeJSONStringify(args.filter((e) => e !== undefined));
},
},
gps: {
documentation:
'Crée une représetation JSON des coordonnées GPS données (latitude puis longitude)',
usage: [
['42.957408', '1.0859884'],
JSON.stringify({ 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: [['0.5', '0.5', '1', '1'], JSON.stringify({ 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 });
},
},
});
export const HANDLEBARS_HELPERS = transformObject(
HELPERS,
(name, { usage: [usageArgs, usageResult], ...rest }) => {
if (!('implementationHandlebars' in rest || 'implementation' in rest)) return undefined;
const impl =
'implementationHandlebars' in rest
? rest.implementationHandlebars
: rest.implementation;
return [
name,
{
...rest,
usageArgs,
usageResult,
implementation: impl,
usage: `{{ ${name} ${usageArgs.join(' ')} }} -> ${safeJSONStringify(usageResult)}`,
},
];
}
);
for (const [name, { implementation }] of Object.entries(HANDLEBARS_HELPERS)) {
Handlebars.registerHelper(name, implementation);
}
const JSONATA_HELPERS = transformObject(
HELPERS,
(name, { usage: [usageArgs, usageResult], ...rest }) => {
if (!('implementationJsonata' in rest || 'implementation' in rest)) return undefined;
const impl =
'implementationJsonata' in rest ? rest.implementationJsonata : rest.implementation;
return [
name,
{
...rest,
usageArgs,
usageResult,
usage: `$${name}(${usageArgs.join(', ')}) -> ${safeJSONStringify(usageResult)}`,
/**
*
* @param {import('jsonata').Focus} _this
* @param {...any} args
*/
implementation: impl,
},
];
}
);
/**
* @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 });
}
});
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('Handlebars helpers', () => {
for (const [name, { usageArgs, usageResult }] of Object.entries(HANDLEBARS_HELPERS)) {
// We should try mocking new Date() maybe?
if (name === 'now') continue;
const call = `${name} ${usageArgs.join(' ')}`;
test(call, () => {
const result = TemplatedString(type({}))
.assert(`{{ ${call} }}`)
.render({
obj: {},
session: {
protocolMetadata: { transect_code: { value: 'TR123' } },
metadata: {},
},
});
expect(result).toEqual(
typeof usageResult === 'string' ? usageResult : safeJSONStringify(usageResult)
);
});
}
});
}
/**
* @template {import("arktype").Type} I
* @template {import("arktype").Type} O
* @param {I} Input
* @param {O} Output
*/
export const JsonataExpression = (Input, Output) =>
type.string.pipe((t) => {
try {
const expr = jsonata(t);
for (const [name, helper] of Object.entries(JSONATA_HELPERS)) {
expr.registerFunction(name, helper.implementation);
}
return {
toJSON: () => t,
/**
* @param {Input['inferIn']} data
* @param {Record<string, any>} [context] additional variables to set on the expression before evaluation
* @returns {Promise<Output['inferOut']>}
*/
async evaluate(data, context = {}) {
for (const [key, value] of Object.entries(context)) {
expr.assign(key, value);
}
let raw = await expr.evaluate(Input.assert(data));
// Jsonata can produce null-prototype objects, which causes issues with .toString() & others
Iif (raw && typeof raw === 'object' && Object.getPrototypeOf(raw) === null) {
raw = mapValues(raw, (v) => v);
}
const out = Output(raw);
Iif (out instanceof ArkErrors) {
console.error(
`Validation error on output of jsonata expression ${safeJSONStringify(t)}: ${out.summary}`,
{ raw, out }
);
throw out;
}
return out;
},
};
} catch (cause) {
throw new Error(
`Invalid Jsonata expression ${safeJSONStringify(t)}: ${cause.message}`,
{ cause }
);
}
});
if (import.meta.vitest) {
const { test, expect, describe } = import.meta.vitest;
describe('Jsonata helpers', () => {
for (const [name, { usageArgs, usageResult }] of Object.entries(JSONATA_HELPERS)) {
// We should try mocking new Date() maybe?
if (name === 'now') continue;
const call = `$${name}(${usageArgs.join(', ')})`;
test(call, async () => {
const expr = JsonataExpression(type({}), type('unknown')).assert(call);
const result = await expr.evaluate({
obj: {},
session: {
protocolMetadata: { transect_code: { value: 'TR123' } },
metadata: {},
},
});
expect(result).toEqual(usageResult);
});
}
});
}
|