// The global extension page has no session to borrow an inventory from: its // rows come from `GET /server?include=extensions`. A reply missing that // inventory is malformed, and a failed read surfaces, rather than showing an // empty list that a daemon E2E, which never sees the client's reading of the // reply, would not notice. import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { stripTypeScriptTypes } from 'node:module'; import test from 'node:test'; const typeless = async (path) => stripTypeScriptTypes( (await readFile(new URL(path, import.meta.url), 'utf8')).replace( /^import type .*;\n/gm, '', ), { mode: 'transform' }, ); const api = await import( `data:text/javascript;base64,${Buffer.from(await typeless('../src/lib/api.ts')).toString('base64')}` ); const inventoryItem = { id: 'work', description: 'track work', requires: [], enabled: true, quarantined: false, diagnostic: null, }; function response(body, { ok = true, status = 200 } = {}) { return { ok, status, statusText: ok ? 'OK' : 'Bad Request', headers: { get: (name) => (name === 'etag' ? '"settings-1"' : null) }, json: async () => body, }; } /** Routes the global choices reads; `server` answers the inventory read. */ function stub(t, server) { const asked = []; t.after(() => delete globalThis.fetch); globalThis.fetch = async (url) => { const address = String(url); asked.push(address); if (address.startsWith('/api/settings')) return response({}); if (address.startsWith('/api/server')) return typeof server === 'function' ? server() : response(server); if (address.startsWith('/api/sessions?')) return response({ items: [], next: null }); return response({}); }; return asked; } test('global choices come from the server inventory when no session exists', async (t) => { const asked = stub(t, { extension_inventory: [inventoryItem] }); const choices = await api.extensionChoices(); assert.deepEqual( choices.candidates.map((candidate) => candidate.id), ['work'], ); assert.equal(choices.candidates[0].global_preference, true); assert.equal(choices.candidates[0].effective_enabled, true); assert.equal(choices.globalETag, '"settings-1"'); assert.ok( asked.some((address) => address === '/api/server?include=extensions'), `expected the inventory read, saw ${JSON.stringify(asked)}`, ); }); test('a reply without a list of extensions is malformed, not an empty list', async (t) => { for (const reply of [{}, { extension_inventory: 'work' }]) { stub(t, reply); await assert.rejects( () => api.extensionChoices(), /malformed.*extension inventory/i, ); } }); test('a failed inventory read surfaces its status', async (t) => { stub(t, () => response( { code: 'bad_request', detail: 'unknown include' }, { ok: false, status: 400 }, ), ); await assert.rejects( () => api.extensionChoices(), (error) => error instanceof api.ApiError && error.status === 400, ); });