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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 12x 12x 12x 12x 12x 12x 4x 4x 12x 12x 10x 10x 10x 9x 10x 1x 1x 8x 10x 7x 7x 12x 1x 12x 1x 1x 1x | import { ArkErrors } from 'arktype';
import { Tables } from '$lib/database.js';
import { tables, type DatabaseHandle } from '$lib/idb.svelte.js';
import {
isNamespacedToProtocol,
MetadataDefaultDynamicPayload,
removeNamespaceFromMetadataId
} from '$lib/schemas/metadata.js';
import { toMetadataRecord } from '$lib/schemas/results.js';
import { toasts } from '$lib/toasts.svelte.js';
import { transformObject } from '$lib/utils.js';
import { serializeMetadataValue } from './serializing.js';
import { storeMetadataValue } from './storage.js';
import { getMetadataValue } from './types.js';
export async function resolveDefaults({
db,
sessionId,
metadataToConsider,
iterations = metadataToConsider.length
}: {
db: DatabaseHandle;
sessionId: string;
metadataToConsider: string[];
iterations?: number;
}) {
// iterations ??= metadataToConsider.length;
if (iterations <= 0) return;
const session = await db
.get('Session', sessionId)
.then((session) => Tables.Session.assert(session));
const defs = await tables.Metadata.getMany(metadataToConsider).then((defs) =>
defs.filter((def) => def.default !== undefined)
);
// TODO for now it only works on session metadata
const sessionMetadata = toMetadataRecord(session.metadata);
const payload: typeof MetadataDefaultDynamicPayload.inferIn = {
protocolMetadata: {},
metadata: {},
session: {
createdAt: session.createdAt,
metadata: sessionMetadata,
protocolMetadata: transformObject(sessionMetadata, (key, value) => {
Iif (!isNamespacedToProtocol(session.protocol, key)) return;
return [removeNamespaceFromMetadataId(key), value];
})
}
};
const metadataToIterateFurtherOn = new Set<string>();
for (const { default: defaultSpec, id, type } of defs) {
Iif (defaultSpec === undefined) continue;
const currentValue = getMetadataValue(session, type, id);
if (currentValue && !currentValue.isDefault) continue;
const value =
typeof defaultSpec === 'object' && 'render' in defaultSpec
? defaultSpec.render(payload)
: defaultSpec;
if (value instanceof ArkErrors) {
toasts.warn(
`La valeur par défaut de la métadonnée ${id} est invalide : ${value.toString()}`
);
continue;
}
console.debug('resolved default for', id, {
defaultSpec,
value,
currentValue,
serializeds: {
new: serializeMetadataValue(value),
current: serializeMetadataValue(currentValue?.value)
}
});
if (serializeMetadataValue(value) === serializeMetadataValue(currentValue?.value)) continue;
await storeMetadataValue({
db,
sessionId,
metadataId: id,
subjectId: sessionId,
type,
isDefault: true,
value
});
metadataToIterateFurtherOn.add(id);
}
await resolveDefaults({
db,
sessionId,
metadataToConsider: [...metadataToIterateFurtherOn],
iterations: iterations - 1
});
}
if (import.meta.vitest) {
const { describe, it, expect, vi, beforeEach } = import.meta.vitest;
vi.mock('$lib/database.js', () => ({
Tables: { Session: { assert: vi.fn((v: unknown) => v) } }
}));
vi.mock('$lib/idb.svelte.js', () => ({
tables: { Metadata: { getMany: vi.fn(async () => []) } }
}));
vi.mock('$lib/toasts.svelte.js', () => ({
toasts: { warn: vi.fn() }
}));
vi.mock('./storage.js', () => ({
storeMetadataValue: vi.fn(async () => {})
}));
// Module-level imports are now the mocks — cast for mock method access
const _tables = tables as unknown as { Metadata: { getMany: ReturnType<typeof vi.fn> } };
const _store = storeMetadataValue as unknown as ReturnType<typeof vi.fn>;
const _toasts = toasts as unknown as { warn: ReturnType<typeof vi.fn> };
function mockDb(session: Record<string, unknown>) {
return { get: vi.fn(async () => session) } as unknown as DatabaseHandle;
}
function makeSession(
metadata: Record<string, Record<string, unknown>> = {},
protocol = 'proto'
) {
return { createdAt: '2024-01-01T00:00:00.000Z', protocol, metadata };
}
beforeEach(() => {
vi.clearAllMocks();
_tables.Metadata.getMany.mockResolvedValue([]);
});
describe('resolveDefaults', () => {
it('returns immediately when iterations is 0', async () => {
const db = mockDb({});
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: [],
iterations: 0
});
expect(db.get).not.toHaveBeenCalled();
});
it('returns immediately when metadataToConsider is empty (iterations defaults to 0)', async () => {
const db = mockDb(makeSession());
await resolveDefaults({ db, sessionId: 'sess1', metadataToConsider: [] });
expect(db.get).not.toHaveBeenCalled();
});
it('does nothing when no metadata definitions have defaults', async () => {
const db = mockDb(makeSession());
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string' }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(_store).not.toHaveBeenCalled();
});
it('stores a static default when no current value exists', async () => {
const db = mockDb(makeSession());
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string', default: 'hello' }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(_store).toHaveBeenCalledWith(
expect.objectContaining({
db,
sessionId: 'sess1',
metadataId: 'proto__field1',
subjectId: 'sess1',
type: 'string',
isDefault: true,
value: 'hello'
})
);
});
it('skips metadata whose current value is not a default', async () => {
const db = mockDb(
makeSession({
'proto__field1': {
value: 'existing',
confidence: 1,
confirmed: false,
manuallyModified: false,
isDefault: false,
alternatives: {}
}
})
);
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string', default: 'hello' }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(_store).not.toHaveBeenCalled();
});
it('overwrites a current default value with a different new default', async () => {
const db = mockDb(
makeSession({
'proto__field1': {
value: 'old',
confidence: 1,
confirmed: false,
manuallyModified: false,
isDefault: true,
alternatives: {}
}
})
);
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string', default: 'new' }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(_store).toHaveBeenCalledWith(
expect.objectContaining({ value: 'new', isDefault: true })
);
});
it('does not store when new default equals current value', async () => {
const db = mockDb(
makeSession({
'proto__field1': {
value: 'hello',
confidence: 1,
confirmed: false,
manuallyModified: false,
isDefault: true,
alternatives: {}
}
})
);
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string', default: 'hello' }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(_store).not.toHaveBeenCalled();
});
it('evaluates dynamic defaults via render()', async () => {
const db = mockDb(makeSession());
const renderFn = vi.fn(() => 'computed');
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string', default: { render: renderFn } }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(renderFn).toHaveBeenCalledWith(
expect.objectContaining({
session: expect.objectContaining({
createdAt: '2024-01-01T00:00:00.000Z'
})
})
);
expect(_store).toHaveBeenCalledWith(
expect.objectContaining({ value: 'computed', isDefault: true })
);
});
it('warns and skips when dynamic default returns ArkErrors', async () => {
const { type } = await import('arktype');
const errors = type('number')('not a number');
const db = mockDb(makeSession());
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__field1', type: 'string', default: { render: () => errors } }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1']
});
expect(_toasts.warn).toHaveBeenCalled();
expect(_store).not.toHaveBeenCalled();
});
it('recurses on metadata that was stored', async () => {
const db = mockDb(makeSession());
_tables.Metadata.getMany
.mockResolvedValueOnce([
{ id: 'proto__field1', type: 'string', default: 'hello' }
])
.mockResolvedValueOnce([]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__field1'],
iterations: 2 // allow one level of recursion
});
// db.get called twice: initial + one recursive call
expect(db.get).toHaveBeenCalledTimes(2);
expect(_tables.Metadata.getMany).toHaveBeenCalledTimes(2);
// Second call should be with the IDs that were stored
expect(_tables.Metadata.getMany).toHaveBeenLastCalledWith(['proto__field1']);
});
it('handles multiple metadata definitions', async () => {
const db = mockDb(makeSession());
_tables.Metadata.getMany
.mockResolvedValueOnce([
{ id: 'proto__a', type: 'string', default: 'val-a' },
{ id: 'proto__b', type: 'integer', default: 42 }
])
.mockResolvedValueOnce([]); // recursive call finds nothing new
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__a', 'proto__b']
});
expect(_store).toHaveBeenCalledWith(
expect.objectContaining({ metadataId: 'proto__a', value: 'val-a' })
);
expect(_store).toHaveBeenCalledWith(
expect.objectContaining({ metadataId: 'proto__b', value: 42 })
);
});
it('passes session protocolMetadata with unnamespaced keys to render()', async () => {
const db = mockDb(
makeSession(
{
'proto__species': {
value: 'Apis mellifera',
confidence: 1,
confirmed: false,
manuallyModified: false,
isDefault: false,
alternatives: {}
}
},
'proto'
)
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const renderFn = vi.fn((_payload: typeof MetadataDefaultDynamicPayload.inferIn) => 'derived');
_tables.Metadata.getMany.mockResolvedValue([
{ id: 'proto__label', type: 'string', default: { render: renderFn } }
]);
await resolveDefaults({
db,
sessionId: 'sess1',
metadataToConsider: ['proto__label']
});
const payload = renderFn.mock.calls[0][0];
// protocolMetadata should have the un-namespaced key
expect(payload.session.protocolMetadata).toHaveProperty('species');
// regular metadata keeps the full namespaced key
expect(payload.session.metadata).toHaveProperty('proto__species');
});
});
}
|