import { createHash } from 'node:crypto'; import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement } from 'react'; import type { Root } from 'react-dom/client'; import type { StrategyVersionPackage } from '@stock-bot/types'; import { tableFixture } from '../../scripts/benchmark-experiment-tables'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const; const originals = keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const); const familyId = '11111111-1111-4111-8111-111111111111'; const versionId = '22222222-2222-4222-8222-222222222222'; let createRoot: typeof import('react-dom/client').createRoot; let Publication: typeof import('../../apps/stock/web-app/src/features/strategies/components/CandidatePublication').CandidatePublication; let readPackage: typeof import('../../apps/stock/web-app/src/features/strategies/services/candidatePublication').readCandidatePackage; let publish: typeof import('../../apps/stock/web-app/src/features/strategies/services/candidatePublication').publishCandidate; let root: Root | undefined; let host: HTMLDivElement; const saved: unknown[] = []; const dirty: boolean[] = []; type Pending = { url: string; body: { package: StrategyVersionPackage; parentVersionId: string | null }; key: string; resolve: (response: Response) => void; reject: (error: Error) => void; settled: boolean; }; const calls: Pending[] = []; function pkg(label = 'first'): StrategyVersionPackage { const value = structuredClone(tableFixture(1).preview.request.strategy.package); value.execution = { kind: 'isolated-candidate/v1', warmupBars: 0 }; value.artifact.content = `globalThis.__candidatePublicationExecuted = '${label}';`; value.artifact.sha256 = createHash('sha256').update(value.artifact.content).digest('hex'); value.dependencyLock.sha256 = createHash('sha256') .update(value.dependencyLock.content) .digest('hex'); return value; } async function flush(action = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } function button(text: string) { return [...host.querySelectorAll('button')].find(item => item.textContent?.trim() === text)!; } const fileField = () => host.querySelector('input[type="file"]') as HTMLInputElement; async function choose(value: { name: string; text: () => Promise }) { await flush(() => { Object.defineProperty(fileField(), 'files', { configurable: true, value: [value] }); fileField().dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event); }); } async function upload(value = pkg()) { await choose({ name: 'candidate.json', text: async () => JSON.stringify(value) }); } function reply(request: Pending, body: unknown, status: number) { request.settled = true; request.resolve(Response.json(body, { status })); } function receipt(request: Pending) { return { version: { id: versionId, strategyId: familyId, ordinal: 1, origin: 'candidate', parentVersionId: request.body.parentVersionId, package: request.body.package, }, }; } async function mount(parentVersionId: string | null = null) { root = createRoot(host); await flush(() => root!.render( createElement(Publication, { strategyId: familyId, parentVersionId, disabled: false, onDirtyChange: value => dirty.push(value), onPublished: value => saved.push(value), }) ) ); } beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, IS_REACT_ACT_ENVIRONMENT: true, })) { Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); } ({ createRoot } = await import('react-dom/client')); ({ CandidatePublication: Publication } = await import( '../../apps/stock/web-app/src/features/strategies/components/CandidatePublication' )); ({ readCandidatePackage: readPackage, publishCandidate: publish } = await import( '../../apps/stock/web-app/src/features/strategies/services/candidatePublication' )); }); beforeEach(() => { calls.length = 0; saved.length = 0; dirty.length = 0; host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); browser.fetch = ((url: unknown, init?: RequestInit) => new Promise((resolve, reject) => { calls.push({ url: String(url), body: JSON.parse(String(init?.body)), key: new Headers(init?.headers).get('Idempotency-Key')!, resolve, reject, settled: false, }); })) as unknown as typeof browser.fetch; }); afterEach(async () => { await flush(() => root?.unmount()); root = undefined; host.remove(); }); afterAll(() => { for (const [key, descriptor] of originals) { if (descriptor) { Object.defineProperty(globalThis, key, descriptor); } else { Reflect.deleteProperty(globalThis, key); } } browser.happyDOM.abort(); }); test('package upload verifies retained hashes and declaration without executing generated source', async () => { await mount(); expect(button('Publish immutable candidate').disabled).toBe(true); const value = pkg(); await upload(value); expect(host.textContent).toContain(value.artifact.sha256); expect(host.textContent).toContain('Author-declared warmup bars'); expect((globalThis as Record).__candidatePublicationExecuted).toBeUndefined(); expect(calls).toHaveLength(0); await flush(() => button('Publish immutable candidate').click()); expect(calls[0]!.body).toEqual({ package: value, parentVersionId: null }); expect(calls[0]!.key).not.toBe(''); await flush(() => reply(calls[0]!, receipt(calls[0]!), 201)); expect(saved).toEqual([{ id: versionId, strategyId: familyId, ordinal: 1 }]); expect(dirty.at(-1)).toBe(false); expect(button('Publish immutable candidate').disabled).toBe(true); }); test('invalid bytes, absent execution declaration and stale file reads never become a publication', async () => { const invalid = pkg(); invalid.artifact.sha256 = 'f'.repeat(64); await expect(readPackage(JSON.stringify(invalid))).rejects.toThrow('hash does not match'); const legacy = pkg(); delete legacy.execution; await expect(readPackage(JSON.stringify(legacy))).rejects.toThrow('must declare'); await mount(); await upload(invalid); expect(host.querySelector('[role="alert"]')).not.toBeNull(); expect(button('Publish immutable candidate').disabled).toBe(true); let release!: (text: string) => void; await choose({ name: 'old.json', text: () => new Promise(resolve => { release = resolve; }), }); const current = pkg('current'); await upload(current); await flush(() => release(JSON.stringify(pkg('old')))); expect(host.textContent).toContain(current.artifact.sha256); expect(host.textContent).not.toContain(pkg('old').artifact.sha256); await flush(() => button('Clear package').click()); expect(button('Publish immutable candidate').disabled).toBe(true); expect(calls).toHaveLength(0); }); test('lost publication freezes package, lineage and key; repeated clicks recover one receipt', async () => { const parent = '33333333-3333-4333-8333-333333333333'; await mount(parent); await upload(); await flush(() => { button('Publish immutable candidate').click(); button('Publish immutable candidate').click(); }); expect(calls).toHaveLength(1); await flush(() => { calls[0]!.settled = true; calls[0]!.reject(new Error('Connection lost')); }); expect(fileField().disabled).toBe(true); expect(button('Clear package').disabled).toBe(true); await upload(pkg('changed')); await flush(() => button('Retry same publication').click()); expect(calls).toHaveLength(2); expect(calls[1]!.body).toEqual(calls[0]!.body); expect(calls[1]!.key).toBe(calls[0]!.key); expect(calls[1]!.body.parentVersionId).toBe(parent); await flush(() => reply(calls[1]!, receipt(calls[1]!), 201)); expect(saved).toHaveLength(1); }); test('definitive rejection permits correction; wrong success receipt remains uncertain', async () => { await mount(); await upload(); await flush(() => button('Publish immutable candidate').click()); await flush(() => reply(calls[0]!, { error: 'Archived family' }, 409)); expect(fileField().disabled).toBe(false); expect(host.textContent).toContain('Archived family'); await flush(() => button('Publish immutable candidate').click()); expect(calls[1]!.key).not.toBe(calls[0]!.key); const wrong = receipt(calls[1]!); wrong.version.strategyId = versionId; await flush(() => reply(calls[1]!, wrong, 201)); expect(fileField().disabled).toBe(true); expect(button('Retry same publication')).not.toBeUndefined(); expect(saved).toHaveLength(0); }); test('unmounted publication cannot navigate or replace a new family', async () => { await mount(); await upload(); await flush(() => button('Publish immutable candidate').click()); await flush(() => root!.unmount()); root = undefined; await flush(() => reply(calls[0]!, receipt(calls[0]!), 201)); expect(saved).toHaveLength(0); expect(host.textContent).toBe(''); }); test('same-event Publish then Clear preserves the only recoverable package and receipt', async () => { await mount(); const value = pkg(); await upload(value); await flush(() => { button('Publish immutable candidate').click(); button('Clear package').click(); }); expect(calls).toHaveLength(1); expect(host.textContent).toContain(value.artifact.sha256); await flush(() => calls[0]!.reject(new Error('Lost accepted response'))); expect(button('Retry same publication').disabled).toBe(false); await flush(() => button('Retry same publication').click()); expect(calls[1]!.key).toBe(calls[0]!.key); expect(calls[1]!.body).toEqual(calls[0]!.body); await flush(() => reply(calls[1]!, receipt(calls[1]!), 201)); expect(saved).toHaveLength(1); }); test('later archive or eligibility loss blocks new publication but preserves an accepted receipt retry', async () => { await mount(); await upload(); await flush(() => button('Publish immutable candidate').click()); await flush(() => calls[0]!.reject(new Error('Lost accepted response'))); await flush(() => root!.render( createElement(Publication, { strategyId: familyId, parentVersionId: null, disabled: true, onDirtyChange: value => dirty.push(value), onPublished: value => saved.push(value), }) ) ); expect(fileField().disabled).toBe(true); expect(button('Retry same publication').disabled).toBe(false); await flush(() => button('Retry same publication').click()); expect(calls[1]!.body).toEqual(calls[0]!.body); expect(calls[1]!.key).toBe(calls[0]!.key); await flush(() => reply(calls[1]!, receipt(calls[1]!), 201)); expect(saved).toHaveLength(1); expect(button('Publish immutable candidate').disabled).toBe(true); }); test('uppercase family and parent identities normalize before sending and checking publication', async () => { const family = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef'; const parent = 'fabcdefa-abcd-4bcd-8bcd-abcdefabcdef'; const published = publish(family.toUpperCase(), pkg(), parent.toUpperCase(), 'case-normalized'); const call = calls[0]!; expect(call.url).toContain(`/strategies/${family}/versions`); expect(call.body.parentVersionId).toBe(parent); const body = receipt(call); body.version.strategyId = family; reply(call, body, 201); expect((await published).strategyId).toBe(family); });