Files
TREK/server/tests/unit/plugins/atlas-layers.controller.test.ts
Maurice 6680bc7c74 Split PluginsModule into four, and gate coverage per domain
PluginsModule was 21 controllers, 24 domain imports and 10 providers in one
class, which made it the hub most of the Nest graph ran through: AdminModule
imported it for a single cascade-disable call and inherited all of it. It is now
PluginsRuntimeModule (supervisor, capability router, hook contracts),
PluginContributionsModule (the 14 read-only hook controllers, moved to
contributions/), PluginOAuthModule (the credential leaf, moved to oauth/) and a
composition root that keeps the install and delivery controllers. AdminModule
imports the runtime alone.

The three plugin files that reached for the db singleton alongside the injected
DatabaseService no longer do. plugin-host-state and signature-status take the
connection from the caller, and the three per-user settings functions that were
bare exports 'so the RPC host wiring can call them directly' are now
PluginUserSettingsService - the host wiring is providers, so it injects them.

Coverage moves from one repo-wide 80% to a per-domain ratchet. The single number
let a well-covered domain subsidise a thin one: booking-import sits at 50% and
integrations at 20%, and the aggregate still cleared the bar, so either could
have lost another ten points unnoticed. Each domain now carries its own measured
floor, regenerated by scripts/coverage-thresholds.mjs.

Two test-side findings on the way:

expect(undefined).toContain(SomeClass) PASSES in this vitest version - it only
throws for a string needle. Every '<X> is listed in its module providers' guard
was written that way, so all twelve of them silently stopped guarding the moment
their class moved. They go through expectRegisteredProvider now, which asserts
the array shape first.

The atlas region test paid for the one-off decompression of the multi-MB admin1
bundle inside its own 5s budget, which is why it failed under load and passed
alone. The bundle is warmed in beforeAll instead.
2026-08-09 18:44:59 +02:00

106 lines
4.7 KiB
TypeScript

/**
* AtlasLayersController (#plugins): country tint layers plugins draw over the
* Atlas world map via the atlasLayerProvider hook. USER-SCOPED — no tripId, the
* acting user is host-bound and the hook takes no target parameter. Mirrors the
* map-markers hardening — gate + fail-safe + server-side normalization: ISO
* alpha-2 code validation (uppercase-coerced), tone enum default, length caps,
* layer/country count caps.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
const { pluginsEnabled } = vi.hoisted(() => ({
pluginsEnabled: vi.fn(() => true),
}));
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () => undefined }) }, canAccessTrip: vi.fn() }));
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { AtlasLayersController } from '../../../src/nest/plugins/contributions/atlas-layers.controller';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
atlasLayers: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new AtlasLayersController(runtime), runtime };
}
const layer = (over: Record<string, unknown> = {}) => ({ id: 'l1', countries: [{ code: 'FR' }], ...over });
describe('AtlasLayersController', () => {
beforeEach(() => { pluginsEnabled.mockReturnValue(true); });
it('gates: disabled / no user return [] (no plugin calls on the first)', async () => {
pluginsEnabled.mockReturnValue(false);
const x = controller(() => [layer()]);
expect(await x.c.get(req(5))).toEqual({ layers: [] });
expect(x.runtime.providersOf).not.toHaveBeenCalled();
pluginsEnabled.mockReturnValue(true);
expect((await controller(() => [layer()]).c.get(req(undefined))).layers).toEqual([]);
});
it('keeps a valid layer, stamps pluginId, invokes the hook with NO target parameter', async () => {
const { c, runtime } = controller(() => [
layer({ name: 'Wishlist', countries: [{ code: 'FR', tone: 'success', label: 'Paris trip' }] }),
]);
const out = (await c.get(req(5))).layers;
expect(out).toEqual([{
pluginId: 'p1',
id: 'l1',
name: 'Wishlist',
countries: [{ code: 'FR', tone: 'success', label: 'Paris trip' }],
}]);
// user-scoped: empty args, the acting user is bound host-side
expect(runtime.atlasLayers).toHaveBeenCalledWith('p1', 5);
});
it('uppercase-coerces codes, drops anything that is not ISO alpha-2, defaults a bad tone', async () => {
const { c } = controller(() => [
layer({
countries: [
{ code: 'de' }, // lowercased -> DE
{ code: 'DEU' }, // alpha-3 -> dropped
{ code: '1x' }, // digits -> dropped
{ code: '' }, // empty -> dropped
null, // non-object -> dropped
{ code: 'JP', tone: 'evil', label: 'L'.repeat(200) },
],
}),
]);
const out = (await c.get(req(5))).layers[0].countries;
expect(out.map((x) => x.code)).toEqual(['DE', 'JP']);
expect(out[0].tone).toBe('default');
expect(out[0].label).toBeUndefined();
expect(out[1].tone).toBe('default'); // unknown tone -> default
expect(out[1].label!.length).toBe(80); // capped
});
it('drops id-less layers and non-objects, caps the name, tolerates non-array results', async () => {
const { c } = controller(() => [
layer({ id: '' }), // no id -> can't key it
null, // non-object
layer({ id: 'ok', name: 'N'.repeat(200), countries: 'not an array' }),
]);
const out = (await c.get(req(5))).layers;
expect(out).toHaveLength(1);
expect(out[0].id).toBe('ok');
expect(out[0].name!.length).toBe(60);
expect(out[0].countries).toEqual([]);
expect((await controller(() => 'garbage').c.get(req(5))).layers).toEqual([]);
});
it('caps at 3 layers per plugin and 300 countries per layer, and skips a failing provider', async () => {
const many = Array.from({ length: 5 }, (_, i) => layer({
id: `l${i}`,
countries: Array.from({ length: 350 }, () => ({ code: 'US' })),
}));
const { c } = controller((id) => (id === 'bad' ? (() => { throw new Error('boom'); })() : many), ['good', 'bad']);
const out = (await c.get(req(5))).layers;
expect(out).toHaveLength(3); // good capped to 3; bad contributes nothing
expect(out[0].countries).toHaveLength(300);
});
});