const { test } = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const vm = require('node:vm'); function harness(bookmarks) { let listener; const context = vm.createContext({}); vm.runInContext(fs.readFileSync('src/background/messages.js', 'utf8'), context); context.registerBackgroundMessages({ messageTypes: { addShortcutBookmark: 'bookmark', getBookmarkFolders: 'folders' }, runtimeApi: { bookmarks: { getTree: async () => [{ id: "0", children: [{ id: "1", parentId: "0", title: "Favorites" }] }], ...bookmarks }, runtime: { onMessage: { addListener(fn) { listener = fn; } } } } }); return (message = { type: "bookmark", parentId: "1" }) => new Promise(resolve => { assert.equal(listener(message, {}, resolve), true); }); } test('creates only the fixed extension shortcut, deduplicating concurrent requests', async () => { const created = []; const request = harness({ search: async () => [], create: async value => { created.push(value); } }); const results = await Promise.all([request(), request()]); assert.equal(created.length, 1); assert.equal(created[0].parentId, '1'); assert.equal(created[0].title, 'Opportunities Extension'); assert.equal(created[0].url, 'https://eeho.fa.us2.oraclecloud.com/hcmUI/faces/FuseWelcome#opportunities-extension'); assert.ok(results.every(result => result.ok)); }); test('does not duplicate an existing bookmark', async () => { const request = harness({ search: async () => [{ id: '2', parentId: '1' }], create: async () => assert.fail('duplicate') }); assert.equal((await request()).existing, true); }); test('reports API errors and allows retry', async () => { let calls = 0; const request = harness({ search: async () => { if (++calls === 1) throw new Error('Permission denied'); return [{ id: '2', parentId: '1' }]; } }); assert.equal((await request()).error, 'Permission denied'); assert.equal((await request()).ok, true); }); test('lists nested writable folders without bookmarks or managed folders', async () => { const request = harness({ getTree: async () => [{ id: '0', children: [ { id: '1', parentId: '0', title: 'Favorites', children: [ { id: '2', parentId: '1', title: 'Work', children: [] }, { id: '3', parentId: '1', title: 'Link', url: 'https://example.com' } ] }, { id: '4', parentId: '0', title: 'Managed', unmodifiable: 'managed' } ] }] }); const result = await request({ type: 'folders' }); assert.deepEqual(JSON.parse(JSON.stringify(result.folders)), [ { id: '1', label: 'Favorites' }, { id: '2', label: 'Favorites / Work' } ]); }); test('rejects missing or unavailable destinations without creating a bookmark', async () => { const request = harness({ create: async () => assert.fail('invalid destination') }); assert.equal((await request({ type: 'bookmark' })).ok, false); assert.equal((await request({ type: 'bookmark', parentId: 'unknown' })).ok, false); });