import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; import { streamJsonArray } from '../src/util/stream-json.mjs'; async function collect(filePath, options) { const items = []; for await (const item of streamJsonArray(filePath, options)) { items.push(item); } return items; } async function withTempFile(content, fn) { const file = path.join(os.tmpdir(), `gti-test-json-${Date.now()}-${Math.random().toString(36).slice(2)}.json`); await fs.writeFile(file, content, 'utf8'); try { return await fn(file); } finally { await fs.rm(file, { force: true }); } } test('streamJsonArray le array pretty-printed com chaves e aspas dentro de strings', async () => { const data = [ { nome: 'Empresa {teste} "aspas"', valor: 10, aninhado: { lista: [1, 2, { x: '}' }] } }, { nome: 'Segunda \\ barra', vazio: null } ]; await withTempFile(JSON.stringify(data, null, 2), async (file) => { const items = await collect(file); assert.deepEqual(items, data); }); }); test('streamJsonArray funciona com JSON compacto e BOM', async () => { const data = [{ a: 1 }, { b: '[{teste}]' }, { c: [{ d: 2 }] }]; await withTempFile('' + JSON.stringify(data), async (file) => { const items = await collect(file); assert.deepEqual(items, data); }); }); test('streamJsonArray processa elementos maiores que o chunk', async () => { const data = [ { texto: 'x'.repeat(500), fim: 'ok' }, { texto: 'y'.repeat(300) } ]; await withTempFile(JSON.stringify(data, null, 2), async (file) => { const items = await collect(file, { highWaterMark: 64 }); assert.deepEqual(items, data); }); }); test('streamJsonArray retorna vazio para array vazio', async () => { await withTempFile('[]', async (file) => { const items = await collect(file); assert.deepEqual(items, []); }); }); test('streamJsonArray falha com erro claro em arquivo truncado', async () => { await withTempFile('[\n { "a": 1 },\n { "b": 2', async (file) => { await assert.rejects(() => collect(file), /JSON truncado/); }); });