import { test } from 'node:test' import assert from 'node:assert/strict' import { readR2Source, R2_SINGLE_PUT_MAX_BYTES } from '../src/r2-source.ts' test('small R2 source stays exact with strong identity', async () => assert.deepEqual( await readR2Source( 'https://fixture.test/source', undefined, async () => new Response(new Uint8Array([0, 255]), { headers: { etag: '"strong"' } }), ), new Uint8Array([0, 255]), )) test('missing validator fails closed without returning capability URLs', async () => { await assert.rejects( readR2Source( 'https://example.test/?private=DO_NOT_PRINT', undefined, async () => new Response('x'), ), (e) => !String(e).includes('DO_NOT_PRINT') && /strong ETag/.test(String(e)), ) }) test('oversized response is cancelled before reading', async () => { let cancelled = false await assert.rejects( readR2Source( 'https://fixture.test/source', undefined, async () => new Response( new ReadableStream({ cancel() { cancelled = true }, }), { headers: { etag: '"s"', 'content-length': String(R2_SINGLE_PUT_MAX_BYTES + 1) } }, ), ), /8 MiB/, ) assert(cancelled) }) test('checksum pins source when no validator exists; mismatch fails', async () => { const bytes = new TextEncoder().encode('hello') const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (x) => x.toString(16).padStart(2, '0'), ).join('') assert.deepEqual( await readR2Source('https://fixture.test/source', hash, async () => new Response(bytes)), bytes, ) await assert.rejects( readR2Source('https://fixture.test/source', '0'.repeat(64), async () => new Response(bytes)), /mismatch/, ) }) test('partial declared source is refused', async () => assert.rejects( readR2Source( 'https://fixture.test/source', undefined, async () => new Response('x', { headers: { etag: '"s"', 'content-length': '3' } }), ), /partial/, ))