diff --git a/CHANGELOG.md b/CHANGELOG.md index bbefc0c..0e58f56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Git history: compare a file with `HEAD` or recent commits (`/api/git/log`, `/api/git/show`), Git change badges in the file tree and a "Git: 変更のみ" filter (`/api/git/status`). - Link check: broken relative links, images, reference definitions and wiki links across Markdown documents (`/api/links/check`), shown per document in the TOC panel and as a folder report. +### Performance + +- Text decoding skips the encoding detector for plain-ASCII files (which decode identically under every supported encoding): full-text search, backlinks and file loading spend far less CPU. +- Plain full-text search skips the per-line scan for files that do not contain the query. +- `/api/tree` stats directory entries concurrently (bounded per directory). +- The file tree coalesces SSE add/unlink bursts into at most one follow-up `/api/tree` reload instead of one per event. +- Content-hashed `/assets/*` bundles are served with `Cache-Control: immutable`, so reloads no longer re-download them. + ## 1.9.0 - 2026-07-30 ### Changed diff --git a/lib/concurrency.mjs b/lib/concurrency.mjs new file mode 100644 index 0000000..28a8d2d --- /dev/null +++ b/lib/concurrency.mjs @@ -0,0 +1,30 @@ +// Bounded concurrency for fan-out work (e.g. filesystem syscalls). + +/** + * Map `items` through async `fn(item, index)` with at most `max` calls in + * flight, resolving to results in input order (like Promise.all over + * `items.map(fn)`). Only `max` workers exist at a time, so no promise or + * closure is allocated per pending item. Rejects with the first error; workers + * stop picking up new items once an error has occurred. + */ +export async function mapWithConcurrency(items, max, fn) { + if (!Number.isInteger(max) || max < 1) throw new RangeError('max must be a positive integer'); + const results = new Array(items.length); + let next = 0; + let failed = false; + async function worker() { + while (!failed && next < items.length) { + const index = next++; + try { + results[index] = await fn(items[index], index); + } catch (err) { + failed = true; + throw err; + } + } + } + const workers = []; + for (let i = 0; i < Math.min(max, items.length); i++) workers.push(worker()); + await Promise.all(workers); + return results; +} diff --git a/lib/text-decode.mjs b/lib/text-decode.mjs new file mode 100644 index 0000000..daa301d --- /dev/null +++ b/lib/text-decode.mjs @@ -0,0 +1,75 @@ +// Text decoding helpers: encoding detection (jschardet) and buffer → string. +import { isAscii } from 'node:buffer'; +import jschardet from 'jschardet'; + +const ENCODING_MAP = { + 'utf-8': 'utf-8', + 'ascii': 'utf-8', + 'utf8': 'utf-8', + 'shift_jis': 'shift_jis', + 'shiftjis': 'shift_jis', + 'shift-jis': 'shift_jis', + 'windows-31j': 'shift_jis', + 'cp932': 'shift_jis', + 'euc-jp': 'euc-jp', + 'eucjp': 'euc-jp', + 'iso-2022-jp': 'iso-2022-jp', + 'euc-kr': 'euc-kr', + 'big5': 'big5', + 'gb2312': 'gbk', + 'gb18030': 'gb18030', + 'gbk': 'gbk', + 'windows-1252': 'windows-1252', + 'iso-8859-1': 'windows-1252', + 'iso-8859-2': 'iso-8859-2', + 'ibm866': 'ibm866', + 'koi8-r': 'koi8-r', +}; + +export function hasUtf8Bom(buf) { + return buf[0] === 0xEF && buf[1] === 0xBB && buf[2] === 0xBF; +} + +/** + * Detect encoding from a buffer and return a TextDecoder-compatible label. + */ +export function detectEncoding(buf) { + // BOM detection + if (hasUtf8Bom(buf)) return 'utf-8'; + if (buf[0] === 0xFF && buf[1] === 0xFE) return 'utf-16le'; + if (buf[0] === 0xFE && buf[1] === 0xFF) return 'utf-16be'; + + const detected = jschardet.detect(buf); + if (!detected || !detected.encoding) return 'utf-8'; + const key = detected.encoding.toLowerCase().replace(/[_\s]/g, match => match === '_' ? '_' : '-'); + return ENCODING_MAP[key] || 'utf-8'; +} + +/** + * True when every decoder `detectEncoding` can select yields the same text + * as UTF-8 for this buffer, so running the (slow) detector is pointless. + * + * All possible labels (every ENCODING_MAP value, the utf-8 fallback, and the + * utf-16 labels which need a non-ASCII BOM) map bytes 0x00–0x7F to the same + * code points — except ISO-2022-JP, which treats ESC (0x1B), SO (0x0E) and + * SI (0x0F) as shift sequences. A pure-ASCII buffer without those three bytes + * therefore decodes identically whatever the detector would have returned. + */ +function decodesAsPlainAscii(buf) { + return isAscii(buf) + && buf.indexOf(0x1B) === -1 + && buf.indexOf(0x0E) === -1 + && buf.indexOf(0x0F) === -1; +} + +/** + * Decode a file buffer to a string, auto-detecting its encoding. A UTF-8 BOM + * is dropped like TextDecoder does for the other encodings: kept, it defeats + * `^` anchors on line 1 in search and leaks into the first CSV header. + */ +export function decodeTextBuffer(buf) { + if (decodesAsPlainAscii(buf)) return buf.toString('utf-8'); + const encoding = detectEncoding(buf); + if (encoding === 'utf-8') return buf.toString('utf-8', hasUtf8Bom(buf) ? 3 : 0); + return new TextDecoder(encoding).decode(buf); +} diff --git a/server.mjs b/server.mjs index 7f6f8b9..31f9d1d 100644 --- a/server.mjs +++ b/server.mjs @@ -8,9 +8,10 @@ import { spawn, execFile } from 'node:child_process'; import { Readable } from 'node:stream'; import { isIP } from 'node:net'; import chokidar from 'chokidar'; -import jschardet from 'jschardet'; import Papa from 'papaparse'; import { createRegexSearch } from './lib/server-regex.mjs'; +import { hasUtf8Bom, detectEncoding, decodeTextBuffer } from './lib/text-decode.mjs'; +import { mapWithConcurrency } from './lib/concurrency.mjs'; import { parseDimensions, buildDimensions, parsePngTextChunksFromFile, extractExif, extractPngColorInfo, detectAiProvenance, @@ -127,68 +128,10 @@ function reportAndExit(err, { exitCode = 1 } = {}) { process.on('uncaughtException', (err) => reportAndExit(err)); process.on('unhandledRejection', (err) => reportAndExit(err instanceof Error ? err : new Error(String(err)))); -// --- Encoding detection helpers --- - -const ENCODING_MAP = { - 'utf-8': 'utf-8', - 'ascii': 'utf-8', - 'utf8': 'utf-8', - 'shift_jis': 'shift_jis', - 'shiftjis': 'shift_jis', - 'shift-jis': 'shift_jis', - 'windows-31j': 'shift_jis', - 'cp932': 'shift_jis', - 'euc-jp': 'euc-jp', - 'eucjp': 'euc-jp', - 'iso-2022-jp': 'iso-2022-jp', - 'euc-kr': 'euc-kr', - 'big5': 'big5', - 'gb2312': 'gbk', - 'gb18030': 'gb18030', - 'gbk': 'gbk', - 'windows-1252': 'windows-1252', - 'iso-8859-1': 'windows-1252', - 'iso-8859-2': 'iso-8859-2', - 'ibm866': 'ibm866', - 'koi8-r': 'koi8-r', -}; - -function hasUtf8Bom(buf) { - return buf[0] === 0xEF && buf[1] === 0xBB && buf[2] === 0xBF; -} - -/** - * Detect encoding from a buffer and return a TextDecoder-compatible label. - */ -function detectEncoding(buf) { - // BOM detection - if (hasUtf8Bom(buf)) return 'utf-8'; - if (buf[0] === 0xFF && buf[1] === 0xFE) return 'utf-16le'; - if (buf[0] === 0xFE && buf[1] === 0xFF) return 'utf-16be'; - - const detected = jschardet.detect(buf); - if (!detected || !detected.encoding) return 'utf-8'; - const key = detected.encoding.toLowerCase().replace(/[_\s]/g, match => match === '_' ? '_' : '-'); - return ENCODING_MAP[key] || 'utf-8'; -} - -/** - * Read a file and decode to UTF-8 string, auto-detecting encoding. - */ -function decodeTextBuffer(buf) { - const encoding = detectEncoding(buf); - if (encoding === 'utf-8') return buf.toString('utf-8', hasUtf8Bom(buf) ? 3 : 0); - return new TextDecoder(encoding).decode(buf); -} +// --- Encoding detection helpers (lib/text-decode.mjs) --- async function readFileText(filePath) { - const buf = await readFile(filePath); - const encoding = detectEncoding(buf); - // Drop a UTF-8 BOM like TextDecoder does for the other encodings: kept, it - // defeats `^` anchors on line 1 in search and leaks into the first CSV header. - if (encoding === 'utf-8') return buf.toString('utf-8', hasUtf8Bom(buf) ? 3 : 0); - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); + return decodeTextBuffer(await readFile(filePath)); } /** @@ -1144,38 +1087,47 @@ function buildZip(entries) { const sseClients = new Set(); // File tree builder +// Per-entry checks and stats within a directory are independent, so a few +// run concurrently instead of one syscall round trip at a time. +// Subdirectories are still walked one at a time, which keeps the in-flight +// work (and memory) per request bounded. Results keep readdir order before +// sorting, so the output is unchanged. +const TREE_STAT_CONCURRENCY = 8; + async function buildTree(dir, base = dir) { const entries = await readdir(dir, { withFileTypes: true }); - const items = []; + const items = await mapWithConcurrency(entries, TREE_STAT_CONCURRENCY, (entry) => buildTreeEntry(entry, dir, base)); + for (let i = 0; i < items.length; i++) { + const item = items[i]; + if (item && item.type === 'dir') { + const children = await buildTree(join(dir, entries[i].name), base); + if (children.length > 0) item.children = children; + else items[i] = null; + } + } + const kept = items.filter(Boolean); - for (const entry of entries) { - const fullPath = join(dir, entry.name); - const relPath = relative(base, fullPath).replace(/\\/g, '/'); - if (entry.isSymbolicLink() && !await safePath(relPath)) continue; - - if (entry.isDirectory()) { - if (isSupportedFilename(entry.name) && OFFICE_EXTENSIONS.has(extname(entry.name).toLowerCase())) { - if (shouldSkipFile(entry.name, relPath)) continue; - let size; - let mtime; - try { - const st = await stat(fullPath); - size = st.size; - mtime = st.mtime.toISOString(); - } catch { - // Directory package disappeared between readdir and stat — skip metadata - } - items.push({ name: entry.name, path: relPath, type: 'file', size, mtime }); - continue; - } - // Skip built-in/ignored/hidden dirs but allow hidden files (e.g. .env). - if (shouldSkipDir(entry.name, relPath)) continue; - const children = await buildTree(fullPath, base); - if (children.length > 0) { - items.push({ name: entry.name, path: relPath, type: 'dir', children }); - } - } else if (isSupportedFilename(entry.name)) { - if (shouldSkipFile(entry.name, relPath)) continue; + // Sort: dirs first, then files, alphabetically + kept.sort((a, b) => { + if (a.type !== b.type) return a.type === 'dir' ? -1 : 1; + return a.name.localeCompare(b.name); + }); + + return kept; +} + +/** + * Tree item for one directory entry, or null when it is not listed. + * Directories come back without `children`; buildTree walks them afterwards. + */ +async function buildTreeEntry(entry, dir, base) { + const fullPath = join(dir, entry.name); + const relPath = relative(base, fullPath).replace(/\\/g, '/'); + if (entry.isSymbolicLink() && !await safePath(relPath)) return null; + + if (entry.isDirectory()) { + if (isSupportedFilename(entry.name) && OFFICE_EXTENSIONS.has(extname(entry.name).toLowerCase())) { + if (shouldSkipFile(entry.name, relPath)) return null; let size; let mtime; try { @@ -1183,19 +1135,28 @@ async function buildTree(dir, base = dir) { size = st.size; mtime = st.mtime.toISOString(); } catch { - // File disappeared between readdir and stat — skip metadata + // Directory package disappeared between readdir and stat — skip metadata } - items.push({ name: entry.name, path: relPath, type: 'file', size, mtime }); + return { name: entry.name, path: relPath, type: 'file', size, mtime }; } + // Skip built-in/ignored/hidden dirs but allow hidden files (e.g. .env). + if (shouldSkipDir(entry.name, relPath)) return null; + return { name: entry.name, path: relPath, type: 'dir', children: null }; } - - // Sort: dirs first, then files, alphabetically - items.sort((a, b) => { - if (a.type !== b.type) return a.type === 'dir' ? -1 : 1; - return a.name.localeCompare(b.name); - }); - - return items; + if (isSupportedFilename(entry.name)) { + if (shouldSkipFile(entry.name, relPath)) return null; + let size; + let mtime; + try { + const st = await stat(fullPath); + size = st.size; + mtime = st.mtime.toISOString(); + } catch { + // File disappeared between readdir and stat — skip metadata + } + return { name: entry.name, path: relPath, type: 'file', size, mtime }; + } + return null; } // Safe path resolution (prevent traversal + symlink bypass) @@ -1520,21 +1481,31 @@ const MIME = { }; // Serve static file from dist +// Vite emits everything under dist/assets/ with a content hash in the file +// name, so a given URL never changes content: let the browser keep it instead +// of re-downloading several MB of JS/CSS on every page load. index.html and +// the unhashed public files (e.g. /highlight-api.css) are left uncached. +const HASHED_ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable'; + async function serveStatic(res, urlPath) { let filePath = join(distDir, urlPath === '/' ? 'index.html' : urlPath); + let hashedAsset = false; try { const s = await stat(filePath); if (s.isDirectory()) filePath = join(filePath, 'index.html'); + else hashedAsset = urlPath.startsWith('/assets/'); } catch { - // SPA fallback + // SPA fallback — never cacheable: the URL may later name a real asset. filePath = join(distDir, 'index.html'); } try { const content = await readFile(filePath); const ext = extname(filePath); - res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' }); + const headers = { 'Content-Type': MIME[ext] || 'application/octet-stream' }; + if (hashedAsset) headers['Cache-Control'] = HASHED_ASSET_CACHE_CONTROL; + res.writeHead(200, headers); res.end(content); } catch { res.writeHead(404, { 'Content-Type': 'text/plain' }); @@ -2366,6 +2337,10 @@ const server = createServer(async (req, res) => { const lowerQuery = query.toLowerCase(); matcher = { test: (s) => s.toLowerCase().includes(lowerQuery) }; } + // Plain search: a line can only match if the whole lowercased file + // contains the query (lowercasing is per character, and line breaks are + // not cased), so files without it skip the per-line split and scan. + const plainQuery = useRegex ? null : query.toLowerCase(); const regexSearch = useRegex ? createRegexSearch(query) : null; async function searchDir(dir) { @@ -2391,6 +2366,7 @@ const server = createServer(async (req, res) => { const st = await stat(fullPath); if (st.size > MAX_SEARCH_FILE_BYTES) continue; const content = await readFileText(fullPath); + if (plainQuery !== null && !content.toLowerCase().includes(plainQuery)) continue; // CRLF files would otherwise keep a trailing \r on every line, // which breaks `$` anchors and leaks into the result text. const lines = content.split(/\r?\n/); diff --git a/src/filetree.ts b/src/filetree.ts index 0f77ecf..7c1450f 100644 --- a/src/filetree.ts +++ b/src/filetree.ts @@ -219,6 +219,9 @@ export class FileTree { private treeData: FileNode[] = []; private filterQuery = ''; private loadSeq = 0; + /** refresh() coalescing: a load is running / another is owed after it. */ + private refreshRunning = false; + private refreshQueued = false; /** Max age in days for the mtime filter; 0 (or NaN) means no time filter. */ private mtimeMaxDays = 0; private gitOnly = false; @@ -669,8 +672,25 @@ export class FileTree { } } + /** + * Reload the tree (e.g. after an SSE add/unlink). Starts at once when idle; + * events arriving while a load is in flight collapse into one follow-up + * load, so a burst of N file events costs at most two /api/tree walks + * instead of N — and the last load still starts after the last event. + */ refresh() { - this.load(); + if (this.refreshRunning) { + this.refreshQueued = true; + return; + } + this.refreshRunning = true; + void this.load().finally(() => { + this.refreshRunning = false; + if (this.refreshQueued) { + this.refreshQueued = false; + this.refresh(); + } + }); } } diff --git a/tests/concurrency.test.mjs b/tests/concurrency.test.mjs new file mode 100644 index 0000000..40f05ea --- /dev/null +++ b/tests/concurrency.test.mjs @@ -0,0 +1,45 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mapWithConcurrency } from '../lib/concurrency.mjs'; + +const tick = (ms) => new Promise((r) => setTimeout(r, ms)); + +test('mapWithConcurrency never exceeds max in-flight calls and keeps input order', async () => { + let active = 0; + let peak = 0; + const items = Array.from({ length: 50 }, (_, i) => i); + const results = await mapWithConcurrency(items, 3, async (item, index) => { + active++; + peak = Math.max(peak, active); + await tick((7 * item) % 4); + active--; + return `${item}:${index}`; + }); + assert.equal(peak, 3); + assert.deepEqual(results, items.map((i) => `${i}:${i}`)); +}); + +test('mapWithConcurrency starts items in order and handles empty and small inputs', async () => { + const order = []; + await mapWithConcurrency([0, 1, 2, 3], 1, async (i) => { order.push(i); await tick(1); }); + assert.deepEqual(order, [0, 1, 2, 3]); + assert.deepEqual(await mapWithConcurrency([], 4, async () => 1), []); + assert.deepEqual(await mapWithConcurrency(['a'], 8, (x) => x.toUpperCase()), ['A']); +}); + +test('mapWithConcurrency rejects with the first error and stops taking new items', async () => { + const started = []; + await assert.rejects(mapWithConcurrency([0, 1, 2, 3, 4, 5], 2, async (i) => { + started.push(i); + await tick(1); + if (i === 1) throw new Error('boom'); + }), /boom/); + await tick(10); + assert.ok(started.length < 6, `started ${started}`); + await assert.rejects(mapWithConcurrency([1], 1, () => { throw new Error('sync boom'); }), /sync boom/); +}); + +test('mapWithConcurrency rejects an invalid max', async () => { + await assert.rejects(mapWithConcurrency([1], 0, (x) => x), RangeError); + await assert.rejects(mapWithConcurrency([1], 1.5, (x) => x), RangeError); +}); diff --git a/tests/server-audit.test.mjs b/tests/server-audit.test.mjs index b420c8b..36d8b8a 100644 --- a/tests/server-audit.test.mjs +++ b/tests/server-audit.test.mjs @@ -359,6 +359,48 @@ test('regex search anchors work on CRLF files and results omit carriage returns' assert.deepEqual(plain[0].contextLines, ['alpha end', 'beta end']); }); +test('plain search matches case-insensitively per line across encodings and files', async (t) => { + const directory = join(fixture, 'plain-search'); + await mkdir(join(directory, 'sub'), { recursive: true }); + await writeFile(join(directory, 'greek.md'), 'ΟΔΟΣ\r\nΟΔΟΣ ΜΑΣ\r\nnothing\n'); + await writeFile(join(directory, 'mixed.md'), 'First LINE\nsecond line\nthird\n'); + await writeFile(join(directory, 'sub', 'none.md'), 'no hits here\n'); + // Shift_JIS "あい line" — decoded before matching. + await writeFile(join(directory, 'sub', 'sjis.txt'), Buffer.from([0x82, 0xA0, 0x82, 0xA2, 0x20, 0x4C, 0x49, 0x4E, 0x45, 0x0A])); + const server = await startServer(t, { directory }); + const search = async (q) => (await (await server.request('/api/search?context=0&q=' + encodeURIComponent(q))).json()) + .map(({ path, line, text }) => `${path}:${line}:${text}`).sort(); + assert.deepEqual(await search('line'), ['mixed.md:1:First LINE', 'mixed.md:2:second line', 'sub/sjis.txt:1:あい LINE']); + assert.deepEqual(await search('οδος'), ['greek.md:1:ΟΔΟΣ', 'greek.md:2:ΟΔΟΣ ΜΑΣ']); + assert.deepEqual(await search('ς μ'), ['greek.md:2:ΟΔΟΣ ΜΑΣ']); + // A query spanning a line break never matches a single line. + assert.deepEqual(await search('line\nsecond'), []); + assert.deepEqual(await search('absent-term'), []); +}); + +test('file tree lists nested entries in order with metadata', async (t) => { + const directory = join(fixture, 'tree-order'); + await mkdir(join(directory, 'b-dir', 'deep'), { recursive: true }); + await mkdir(join(directory, 'a-dir'), { recursive: true }); + await mkdir(join(directory, 'empty-dir'), { recursive: true }); + await mkdir(join(directory, 'deck.key'), { recursive: true }); + for (const name of ['z.md', 'B.md', 'a.md', 'b-dir/deep/x.json', 'b-dir/y.yaml', 'a-dir/w.txt', 'skip.bin']) { + await writeFile(join(directory, name), name); + } + await symlink(join(fixture, 'outside.md'), join(directory, 'escape.md')); + await symlink(join(directory, 'a.md'), join(directory, 'alias.md')); + const server = await startServer(t, { directory }); + const { tree } = await (await server.request('/api/tree')).json(); + const flatten = (items) => items.flatMap((item) => (item.children + ? [`${item.path}/`, ...flatten(item.children)] + : [`${item.path}:${item.size}:${typeof item.mtime}`])); + assert.deepEqual(flatten(tree), [ + 'a-dir/', 'a-dir/w.txt:11:string', + 'b-dir/', 'b-dir/deep/', 'b-dir/deep/x.json:17:string', 'b-dir/y.yaml:12:string', + 'a.md:4:string', 'alias.md:4:string', 'B.md:4:string', 'deck.key:' + tree.find((i) => i.name === 'deck.key').size + ':string', 'z.md:4:string', + ]); +}); + test('backlinks resolve Markdown links like the viewer does', async (t) => { const directory = join(fixture, 'backlinks'); await mkdir(join(directory, 'sub'), { recursive: true }); diff --git a/tests/text-decode.test.mjs b/tests/text-decode.test.mjs new file mode 100644 index 0000000..17e35c6 --- /dev/null +++ b/tests/text-decode.test.mjs @@ -0,0 +1,78 @@ +// decodeTextBuffer must return exactly what the original detector-first +// algorithm returned; its pure-ASCII fast path is only an optimisation. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { decodeTextBuffer, detectEncoding, hasUtf8Bom } from '../lib/text-decode.mjs'; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); + +/** The pre-fast-path implementation: always consult the detector. */ +function referenceDecode(buf) { + const encoding = detectEncoding(buf); + if (encoding === 'utf-8') return buf.toString('utf-8', hasUtf8Bom(buf) ? 3 : 0); + return new TextDecoder(encoding).decode(buf); +} + +function assertSame(buf, label) { + assert.equal(decodeTextBuffer(buf), referenceDecode(buf), label); +} + +test('decodeTextBuffer matches the detector for crafted edge cases', () => { + const cases = { + empty: Buffer.alloc(0), + ascii: Buffer.from('# Title\n\nplain text with tabs\tand CRLF\r\n'), + asciiControls: Buffer.from('a\x00b\x07c\x7f\x0b\x0c'), + nullsUtf16Pattern: Buffer.from('a\x00b\x00c\x00d\x00e\x00f\x00g\x00h\x00'.repeat(20)), + metaShiftJis: Buffer.from('hello \\ ~'), + metaIso2022jp: Buffer.from('x'), + metaEucKr: Buffer.from('b'), + metaUtf16: Buffer.from('

x

'), + iso2022jpEscapes: Buffer.from([0x1B, 0x24, 0x42, 0x46, 0x7C, 0x4B, 0x5C, 0x1B, 0x28, 0x42, 0x0A]), + shiftOut: Buffer.from('a\x0eb\x0fc'), + hz: Buffer.from('~{<:Ky2;S{#,NpJ)l6HK!#~}'), + utf7: Buffer.from('Hi Mom -+Jjo--!'), + utf8Bom: Buffer.from('# BOM title\n'), + utf8Japanese: Buffer.from('# 日本語ドキュメント\n本文です。\n'), + utf16leBom: Buffer.from([0xFF, 0xFE, 0x41, 0x00, 0x42, 0x00]), + utf16beBom: Buffer.from([0xFE, 0xFF, 0x00, 0x41, 0x00, 0x42]), + shiftJisBytes: Buffer.from([0x82, 0xA0, 0x82, 0xA2, 0x82, 0xA4, 0x0A, 0x93, 0xFA, 0x96, 0x7B]), + eucJpBytes: Buffer.from([0xA4, 0xA2, 0xA4, 0xA4, 0xA4, 0xA6, 0x0A, 0xC6, 0xFC, 0xCB, 0xDC]), + latin1Bytes: Buffer.from([0x63, 0x61, 0x66, 0xE9, 0x20, 0x6E, 0x61, 0xEF, 0x76, 0x65]), + pdfMagic: Buffer.from('%PDF-1.4\n1 0 obj\n'), + }; + for (const [label, buf] of Object.entries(cases)) assertSame(buf, label); +}); + +test('decodeTextBuffer matches the detector for random ASCII and near-ASCII input', () => { + let seed = 12345; + const rand = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed; }; + for (let i = 0; i < 400; i++) { + const len = rand() % 600; + const buf = Buffer.alloc(len); + // Mostly printable ASCII, sometimes any 7-bit byte, rarely a high byte. + for (let j = 0; j < len; j++) { + const r = rand() % 100; + buf[j] = r < 85 ? 0x20 + (rand() % 95) : r < 99 ? rand() % 128 : 0x80 + (rand() % 128); + } + assertSame(buf, `random #${i}`); + } +}); + +test('decodeTextBuffer matches the detector for every text file in the repo docs', () => { + const dirs = ['sample-docs', 'docs', 'tests'].map((d) => join(ROOT, d)); + let checked = 0; + const walk = (dir) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { walk(full); continue; } + if (!entry.isFile() || statSync(full).size > 2 * 1024 * 1024) continue; + assertSame(readFileSync(full), full); + checked++; + } + }; + for (const dir of dirs) { try { walk(dir); } catch (err) { if (err.code !== 'ENOENT') throw err; } } + assert.ok(checked > 0); +});