'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const { normalizeWorkIdentity, resolveWorkIdentity, sameWorkIdentity } = require('../lib/work-identity'); const { findManga } = require('../lib/library-inventory'); test('work identity follows canonical source priority and preserves an imported lineage', () => { const anilist = { scheme: 'mangacircus-work-v1', kind: 'anilist', value: '123' }; const meta = { 'x-anilist': { id: 123 }, 'x-scraper': { ids: { mangadex: 'md-1', weebcentral: 'wc-1' } } }; assert.deepEqual(resolveWorkIdentity(meta, 'folder', 'server'), anilist); const imported = { scheme: 'mangacircus-work-v1', kind: 'origin', value: 'a'.repeat(64) }; assert.deepEqual(resolveWorkIdentity({ ...meta, 'x-work-identity': imported }, 'other', 'other-server'), imported); assert.equal(normalizeWorkIdentity({ ...imported, value: '' }), null); assert.equal(sameWorkIdentity(imported, { ...imported }), true); assert.equal(sameWorkIdentity(imported, { ...imported, value: 'b'.repeat(64) }), false); assert.equal(resolveWorkIdentity({ 'x-scraper': { ids: { 'peer-p123': 'edition-only' } } }, 'folder', 'server').kind, 'origin', 'A peer edition ID is not a canonical work identity'); }); test('library matching uses a peer-carried stable identity before title or peer-edition IDs', () => { const localServerId = 'p-local-server'; const inventory = { mangas: [ { id: 'Peer A Test Manga', meta: { title: 'Peer A Test Manga' }, ids: {}, sources: [], chapters: [] }, { id: 'Unrelated edition', meta: { title: 'Peer A Test Manga' }, ids: { 'peer-p-other': 'p-other-manga' }, sources: [], chapters: [] }, ] }; const identity = resolveWorkIdentity(inventory.mangas[0].meta, inventory.mangas[0].id, localServerId); assert.equal(findManga(inventory, { source: 'peer-p-returning', seriesId: 'p-returning-manga', workIdentity: identity, localServerId }).id, 'Peer A Test Manga'); assert.equal(findManga(inventory, { source: 'peer-p-returning', seriesId: 'p-returning-manga', workIdentity: { ...identity, value: 'f'.repeat(64) }, localServerId }), null, 'A matching title alone must not merge unrelated work'); });