xz-compat 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/iterators/xz-compat/src/xz/Decoder.ts"],"sourcesContent":["/**\n * XZ Decompression Module\n *\n * XZ is a container format that wraps LZMA2 compressed data.\n * This module provides both synchronous and streaming XZ decoders.\n *\n * Pure JavaScript implementation, works on Node.js 0.8+\n *\n * IMPORTANT: Buffer Management Pattern\n *\n * When calling decodeLzma2(), use the direct return pattern:\n *\n * ✅ CORRECT - Fast path:\n * const output = decodeLzma2(data, props, size) as Buffer;\n *\n * ❌ WRONG - Slow path (do NOT buffer):\n * const chunks: Buffer[] = [];\n * decodeLzma2(data, props, size, { write: c => chunks.push(c) });\n * return Buffer.concat(chunks); // ← Unnecessary copies!\n */\n\nimport { Transform } from 'extract-base-iterator';\nimport type { Transform as TransformType } from 'stream';\nimport { decodeBcj } from '../filters/bcj/Bcj.ts';\nimport { decodeBcjArm } from '../filters/bcj/BcjArm.ts';\nimport { decodeBcjArm64 } from '../filters/bcj/BcjArm64.ts';\nimport { decodeBcjArmt } from '../filters/bcj/BcjArmt.ts';\nimport { decodeBcjIa64 } from '../filters/bcj/BcjIa64.ts';\nimport { decodeBcjPpc } from '../filters/bcj/BcjPpc.ts';\nimport { decodeBcjSparc } from '../filters/bcj/BcjSparc.ts';\nimport { decodeDelta } from '../filters/delta/Delta.ts';\nimport { decodeLzma2 } from '../lzma/index.ts';\nimport { tryLoadNative } from '../native.ts';\n\n// XZ magic bytes\nconst XZ_MAGIC = [0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00];\nconst XZ_FOOTER_MAGIC = [0x59, 0x5a]; // \"YZ\"\n\n// Filter IDs (from XZ specification)\nconst FILTER_DELTA = 0x03;\nconst FILTER_BCJ_X86 = 0x04;\nconst FILTER_BCJ_PPC = 0x05;\nconst FILTER_BCJ_IA64 = 0x06;\nconst FILTER_BCJ_ARM = 0x07;\nconst FILTER_BCJ_ARMT = 0x08;\nconst FILTER_BCJ_SPARC = 0x09;\nconst FILTER_BCJ_ARM64 = 0x0a;\nconst FILTER_LZMA2 = 0x21;\n\n// Filter info for parsing\ninterface FilterInfo {\n id: number;\n props: Buffer;\n}\n\n/**\n * Simple buffer comparison\n */\nfunction bufferEquals(buf: Buffer, offset: number, expected: number[]): boolean {\n if (offset + expected.length > buf.length) {\n return false;\n }\n for (let i = 0; i < expected.length; i++) {\n if (buf[offset + i] !== expected[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Decode variable-length integer (XZ multibyte encoding)\n * Returns number, but limits to 32-bit to work on Node 0.8+\n */\nfunction decodeMultibyte(buf: Buffer, offset: number): { value: number; bytesRead: number } {\n let value = 0;\n let i = 0;\n let byte: number;\n do {\n if (offset + i >= buf.length) {\n throw new Error('Truncated multibyte integer');\n }\n byte = buf[offset + i];\n value |= (byte & 0x7f) << (i * 7);\n i++;\n if (i > 4) {\n // Reduced to prevent overflow on Node 0.8\n throw new Error('Multibyte integer too large');\n }\n } while (byte & 0x80);\n return { value, bytesRead: i };\n}\n\n/**\n * Apply a preprocessing filter (BCJ/Delta) to decompressed data\n */\nfunction applyFilter(data: Buffer, filter: FilterInfo): Buffer {\n switch (filter.id) {\n case FILTER_BCJ_X86:\n return decodeBcj(data, filter.props);\n case FILTER_BCJ_ARM:\n return decodeBcjArm(data, filter.props);\n case FILTER_BCJ_ARM64:\n return decodeBcjArm64(data, filter.props);\n case FILTER_BCJ_ARMT:\n return decodeBcjArmt(data, filter.props);\n case FILTER_BCJ_PPC:\n return decodeBcjPpc(data, filter.props);\n case FILTER_BCJ_SPARC:\n return decodeBcjSparc(data, filter.props);\n case FILTER_BCJ_IA64:\n return decodeBcjIa64(data, filter.props);\n case FILTER_DELTA:\n return decodeDelta(data, filter.props);\n default:\n throw new Error(`Unsupported filter: 0x${filter.id.toString(16)}`);\n }\n}\n\n/**\n * Parse XZ Block Header to extract filters and LZMA2 properties\n */\nfunction parseBlockHeader(\n input: Buffer,\n offset: number,\n _checkSize: number\n): {\n filters: FilterInfo[];\n lzma2Props: Buffer;\n headerSize: number;\n dataStart: number;\n dataEnd: number;\n nextOffset: number;\n} {\n // Block header size\n const blockHeaderSizeRaw = input[offset];\n if (blockHeaderSizeRaw === 0) {\n throw new Error('Invalid block header size (index indicator found instead of block)');\n }\n const blockHeaderSize = (blockHeaderSizeRaw + 1) * 4;\n\n // Parse block header\n const blockHeaderStart = offset;\n offset++; // skip size byte\n\n const blockFlags = input[offset++];\n const numFilters = (blockFlags & 0x03) + 1;\n const hasCompressedSize = (blockFlags & 0x40) !== 0;\n const hasUncompressedSize = (blockFlags & 0x80) !== 0;\n\n // Skip optional sizes\n if (hasCompressedSize) {\n const result = decodeMultibyte(input, offset);\n offset += result.bytesRead;\n }\n\n if (hasUncompressedSize) {\n const result = decodeMultibyte(input, offset);\n offset += result.bytesRead;\n }\n\n // Parse all filters\n const filters: FilterInfo[] = [];\n let lzma2Props: Buffer | null = null;\n\n for (let i = 0; i < numFilters; i++) {\n const filterIdResult = decodeMultibyte(input, offset);\n const filterId = filterIdResult.value;\n offset += filterIdResult.bytesRead;\n\n const propsSizeResult = decodeMultibyte(input, offset);\n offset += propsSizeResult.bytesRead;\n\n const filterProps = input.slice(offset, offset + propsSizeResult.value);\n offset += propsSizeResult.value;\n\n if (filterId === FILTER_LZMA2) {\n // LZMA2 must be the last filter\n lzma2Props = filterProps;\n } else if (filterId === FILTER_DELTA || (filterId >= FILTER_BCJ_X86 && filterId <= FILTER_BCJ_ARM64)) {\n // Preprocessing filter - store for later application\n filters.push({ id: filterId, props: filterProps });\n } else {\n throw new Error(`Unsupported filter: 0x${filterId.toString(16)}`);\n }\n }\n\n if (!lzma2Props) {\n throw new Error('No LZMA2 filter found in XZ block');\n }\n\n // Skip to end of block header (must be aligned to 4 bytes)\n const blockDataStart = blockHeaderStart + blockHeaderSize;\n\n return {\n filters,\n lzma2Props,\n headerSize: blockHeaderSize,\n dataStart: blockDataStart,\n dataEnd: input.length,\n nextOffset: blockDataStart,\n };\n}\n\n/**\n * Parse XZ Index to get block positions\n *\n * XZ Index stores \"Unpadded Size\" for each block which equals:\n * Block Header Size + Compressed Data Size + Check Size\n * (does NOT include padding to 4-byte boundary)\n */\nfunction parseIndex(\n input: Buffer,\n indexStart: number,\n checkSize: number\n): Array<{\n compressedPos: number;\n compressedDataSize: number;\n uncompressedSize: number;\n}> {\n let offset = indexStart;\n\n // Index indicator (0x00)\n if (input[offset] !== 0x00) {\n throw new Error('Invalid index indicator');\n }\n offset++;\n\n // Number of records\n const countResult = decodeMultibyte(input, offset);\n const recordCount = countResult.value;\n offset += countResult.bytesRead;\n\n const records: Array<{\n compressedPos: number;\n unpaddedSize: number;\n compressedDataSize: number;\n uncompressedSize: number;\n }> = [];\n\n // Parse each record\n for (let i = 0; i < recordCount; i++) {\n // Unpadded Size (header + compressed data + check)\n const unpaddedResult = decodeMultibyte(input, offset);\n offset += unpaddedResult.bytesRead;\n\n // Uncompressed size\n const uncompressedResult = decodeMultibyte(input, offset);\n offset += uncompressedResult.bytesRead;\n\n records.push({\n compressedPos: 0, // will be calculated\n unpaddedSize: unpaddedResult.value,\n compressedDataSize: 0, // will be calculated\n uncompressedSize: uncompressedResult.value,\n });\n }\n\n // Calculate actual positions by walking through blocks\n let currentPos = 12; // After stream header\n for (let i = 0; i < records.length; i++) {\n const record = records[i];\n // Record where this block's header starts\n record.compressedPos = currentPos;\n\n // Get block header size from the actual data\n const headerSizeRaw = input[currentPos];\n const headerSize = (headerSizeRaw + 1) * 4;\n\n // Calculate compressed data size from unpadded size\n // unpaddedSize = headerSize + compressedDataSize + checkSize\n record.compressedDataSize = record.unpaddedSize - headerSize - checkSize;\n\n // Move to next block: unpaddedSize + padding to 4-byte boundary\n const paddedSize = Math.ceil(record.unpaddedSize / 4) * 4;\n currentPos += paddedSize;\n }\n\n return records;\n}\n\n/**\n * Decompress XZ data synchronously\n * Uses @napi-rs/lzma if available on Node 14+, falls back to pure JS\n * Properly handles multi-block XZ files and stream padding\n * @param input - XZ compressed data\n * @returns Decompressed data\n */\nexport function decodeXZ(input: Buffer): Buffer {\n // Try native acceleration first (Node 14+ with @napi-rs/lzma installed)\n const native = tryLoadNative();\n if (native) {\n return native.xz.decompressSync(input);\n }\n\n // Verify XZ magic\n if (input.length < 12 || !bufferEquals(input, 0, XZ_MAGIC)) {\n throw new Error('Invalid XZ magic bytes');\n }\n\n // Stream flags at offset 6-7\n const checkType = input[7] & 0x0f;\n\n // Check sizes based on check type\n const checkSizes: { [key: number]: number } = {\n 0: 0, // None\n 1: 4, // CRC32\n 4: 8, // CRC64\n 10: 32, // SHA-256\n };\n const checkSize = checkSizes[checkType] ?? 0;\n\n // Find footer by skipping stream padding (null bytes at end before footer)\n // Stream padding must be multiple of 4 bytes\n let footerEnd = input.length;\n while (footerEnd > 12 && input[footerEnd - 1] === 0x00) {\n footerEnd--;\n }\n // Align to 4-byte boundary (stream padding rules)\n while (footerEnd % 4 !== 0 && footerEnd > 12) {\n footerEnd++;\n }\n\n // Verify footer magic (at footerEnd - 2)\n if (!bufferEquals(input, footerEnd - 2, XZ_FOOTER_MAGIC)) {\n throw new Error('Invalid XZ footer magic');\n }\n\n // Get backward size (tells us where index starts) - at footerEnd - 8\n const backwardSize = (input.readUInt32LE(footerEnd - 8) + 1) * 4;\n const indexStart = footerEnd - 12 - backwardSize;\n\n // Parse Index to get block information\n const blockRecords = parseIndex(input, indexStart, checkSize);\n\n // Decompress each block\n const outputChunks: Buffer[] = [];\n let _totalOutputSize = 0;\n\n for (let i = 0; i < blockRecords.length; i++) {\n const record = blockRecords[i];\n const recordStart = record.compressedPos;\n\n // Parse block header\n const blockInfo = parseBlockHeader(input, recordStart, checkSize);\n\n // Extract compressed data for this block\n const dataStart = recordStart + blockInfo.headerSize;\n // compressedDataSize is calculated from the Index's Unpadded Size minus header and check\n const dataEnd = dataStart + record.compressedDataSize;\n\n // Note: XZ blocks have padding AFTER the check field to align to 4 bytes,\n // but the compressedSize from index is exact - no need to strip padding.\n // LZMA2 data includes a 0x00 end marker which must NOT be stripped.\n const compressedData = input.slice(dataStart, dataEnd);\n\n // Decompress this block with LZMA2 (fast path, no buffering)\n let blockOutput = decodeLzma2(compressedData, blockInfo.lzma2Props, record.uncompressedSize) as Buffer;\n\n // Apply preprocessing filters in reverse order (BCJ/Delta applied after LZMA2)\n // Filters are stored in order they were applied during compression,\n // so we need to reverse for decompression\n for (let j = blockInfo.filters.length - 1; j >= 0; j--) {\n blockOutput = applyFilter(blockOutput, blockInfo.filters[j]) as Buffer;\n }\n\n outputChunks.push(blockOutput);\n _totalOutputSize += blockOutput.length;\n }\n\n return Buffer.concat(outputChunks);\n}\n\n/**\n * Create an XZ decompression Transform stream\n * @returns Transform stream that decompresses XZ data\n */\nexport function createXZDecoder(): TransformType {\n const chunks: Buffer[] = [];\n\n return new Transform({\n transform(chunk: Buffer, _encoding: string, callback: (error?: Error | null) => void) {\n chunks.push(chunk);\n callback();\n },\n\n flush(callback: (error?: Error | null) => void) {\n try {\n const input = Buffer.concat(chunks);\n const output = decodeXZ(input);\n this.push(output);\n callback();\n } catch (err) {\n callback(err as Error);\n }\n },\n });\n}\n"],"names":["createXZDecoder","decodeXZ","XZ_MAGIC","XZ_FOOTER_MAGIC","FILTER_DELTA","FILTER_BCJ_X86","FILTER_BCJ_PPC","FILTER_BCJ_IA64","FILTER_BCJ_ARM","FILTER_BCJ_ARMT","FILTER_BCJ_SPARC","FILTER_BCJ_ARM64","FILTER_LZMA2","bufferEquals","buf","offset","expected","length","i","decodeMultibyte","value","byte","Error","bytesRead","applyFilter","data","filter","id","decodeBcj","props","decodeBcjArm","decodeBcjArm64","decodeBcjArmt","decodeBcjPpc","decodeBcjSparc","decodeBcjIa64","decodeDelta","toString","parseBlockHeader","input","_checkSize","blockHeaderSizeRaw","blockHeaderSize","blockHeaderStart","blockFlags","numFilters","hasCompressedSize","hasUncompressedSize","result","filters","lzma2Props","filterIdResult","filterId","propsSizeResult","filterProps","slice","push","blockDataStart","headerSize","dataStart","dataEnd","nextOffset","parseIndex","indexStart","checkSize","countResult","recordCount","records","unpaddedResult","uncompressedResult","compressedPos","unpaddedSize","compressedDataSize","uncompressedSize","currentPos","record","headerSizeRaw","paddedSize","Math","ceil","checkSizes","native","tryLoadNative","xz","decompressSync","checkType","footerEnd","backwardSize","readUInt32LE","blockRecords","outputChunks","_totalOutputSize","recordStart","blockInfo","compressedData","blockOutput","decodeLzma2","j","Buffer","concat","chunks","Transform","transform","chunk","_encoding","callback","flush","output","err"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC;;;;;;;;;;;QAsWeA;eAAAA;;QAzFAC;eAAAA;;;mCA3QU;qBAEA;wBACG;0BACE;yBACD;yBACA;wBACD;0BACE;uBACH;uBACA;wBACE;AAE9B,iBAAiB;AACjB,IAAMC,WAAW;IAAC;IAAM;IAAM;IAAM;IAAM;IAAM;CAAK;AACrD,IAAMC,kBAAkB;IAAC;IAAM;CAAK,EAAE,OAAO;AAE7C,qCAAqC;AACrC,IAAMC,eAAe;AACrB,IAAMC,iBAAiB;AACvB,IAAMC,iBAAiB;AACvB,IAAMC,kBAAkB;AACxB,IAAMC,iBAAiB;AACvB,IAAMC,kBAAkB;AACxB,IAAMC,mBAAmB;AACzB,IAAMC,mBAAmB;AACzB,IAAMC,eAAe;AAQrB;;CAEC,GACD,SAASC,aAAaC,GAAW,EAAEC,MAAc,EAAEC,QAAkB;IACnE,IAAID,SAASC,SAASC,MAAM,GAAGH,IAAIG,MAAM,EAAE;QACzC,OAAO;IACT;IACA,IAAK,IAAIC,IAAI,GAAGA,IAAIF,SAASC,MAAM,EAAEC,IAAK;QACxC,IAAIJ,GAAG,CAACC,SAASG,EAAE,KAAKF,QAAQ,CAACE,EAAE,EAAE;YACnC,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA;;;CAGC,GACD,SAASC,gBAAgBL,GAAW,EAAE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,SAAAA,MAAMD,QAAwC;YAC5C,IAAI;gBACF,IAAMlE,QAAQ2D,OAAOC,MAAM,CAACC;gBAC5B,IAAMO,SAAS1G,SAASsC;gBACxB,IAAI,CAACiB,IAAI,CAACmD;gBACVF;YACF,EAAE,OAAOG,KAAK;gBACZH,SAASG;YACX;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/iterators/xz-compat/src/xz/Decoder.ts"],"sourcesContent":["/**\n * XZ Decompression Module\n *\n * XZ is a container format that wraps LZMA2 compressed data.\n * This module provides both synchronous and streaming XZ decoders.\n *\n * Pure JavaScript implementation, works on Node.js 0.8+\n *\n * IMPORTANT: Buffer Management Pattern\n *\n * When calling decodeLzma2(), use the direct return pattern:\n *\n * ✅ CORRECT - Fast path:\n * const output = decodeLzma2(data, props, size) as Buffer;\n *\n * ❌ WRONG - Slow path (do NOT buffer):\n * const chunks: Buffer[] = [];\n * decodeLzma2(data, props, size, { write: c => chunks.push(c) });\n * return Buffer.concat(chunks); // ← Unnecessary copies!\n */\n\nimport { Transform } from 'extract-base-iterator';\nimport type { Transform as TransformType } from 'stream';\nimport { decodeBcj } from '../filters/bcj/Bcj.ts';\nimport { decodeBcjArm } from '../filters/bcj/BcjArm.ts';\nimport { decodeBcjArm64 } from '../filters/bcj/BcjArm64.ts';\nimport { decodeBcjArmt } from '../filters/bcj/BcjArmt.ts';\nimport { decodeBcjIa64 } from '../filters/bcj/BcjIa64.ts';\nimport { decodeBcjPpc } from '../filters/bcj/BcjPpc.ts';\nimport { decodeBcjSparc } from '../filters/bcj/BcjSparc.ts';\nimport { decodeDelta } from '../filters/delta/Delta.ts';\nimport { decodeLzma2 } from '../lzma/index.ts';\nimport { tryLoadNative } from '../native.ts';\n\n// XZ magic bytes\nconst XZ_MAGIC = [0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00];\nconst XZ_FOOTER_MAGIC = [0x59, 0x5a]; // \"YZ\"\n\n// Filter IDs (from XZ specification)\nconst FILTER_DELTA = 0x03;\nconst FILTER_BCJ_X86 = 0x04;\nconst FILTER_BCJ_PPC = 0x05;\nconst FILTER_BCJ_IA64 = 0x06;\nconst FILTER_BCJ_ARM = 0x07;\nconst FILTER_BCJ_ARMT = 0x08;\nconst FILTER_BCJ_SPARC = 0x09;\nconst FILTER_BCJ_ARM64 = 0x0a;\nconst FILTER_LZMA2 = 0x21;\n\n// Filter info for parsing\ninterface FilterInfo {\n id: number;\n props: Buffer;\n}\n\n/**\n * Simple buffer comparison\n */\nfunction bufferEquals(buf: Buffer, offset: number, expected: number[]): boolean {\n if (offset + expected.length > buf.length) {\n return false;\n }\n for (let i = 0; i < expected.length; i++) {\n if (buf[offset + i] !== expected[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Decode variable-length integer (XZ multibyte encoding)\n * Returns number, but limits to 32-bit to work on Node 0.8+\n */\nfunction decodeMultibyte(buf: Buffer, offset: number): { value: number; bytesRead: number } {\n let value = 0;\n let i = 0;\n let byte: number;\n do {\n if (offset + i >= buf.length) {\n throw new Error('Truncated multibyte integer');\n }\n byte = buf[offset + i];\n value |= (byte & 0x7f) << (i * 7);\n i++;\n if (i > 4) {\n // Reduced to prevent overflow on Node 0.8\n throw new Error('Multibyte integer too large');\n }\n } while (byte & 0x80);\n return { value, bytesRead: i };\n}\n\n/**\n * Apply a preprocessing filter (BCJ/Delta) to decompressed data\n */\nfunction applyFilter(data: Buffer, filter: FilterInfo): Buffer {\n switch (filter.id) {\n case FILTER_BCJ_X86:\n return decodeBcj(data, filter.props);\n case FILTER_BCJ_ARM:\n return decodeBcjArm(data, filter.props);\n case FILTER_BCJ_ARM64:\n return decodeBcjArm64(data, filter.props);\n case FILTER_BCJ_ARMT:\n return decodeBcjArmt(data, filter.props);\n case FILTER_BCJ_PPC:\n return decodeBcjPpc(data, filter.props);\n case FILTER_BCJ_SPARC:\n return decodeBcjSparc(data, filter.props);\n case FILTER_BCJ_IA64:\n return decodeBcjIa64(data, filter.props);\n case FILTER_DELTA:\n return decodeDelta(data, filter.props);\n default:\n throw new Error(`Unsupported filter: 0x${filter.id.toString(16)}`);\n }\n}\n\n/**\n * Parse XZ Block Header to extract filters and LZMA2 properties\n */\nfunction parseBlockHeader(\n input: Buffer,\n offset: number,\n _checkSize: number\n): {\n filters: FilterInfo[];\n lzma2Props: Buffer;\n headerSize: number;\n dataStart: number;\n dataEnd: number;\n nextOffset: number;\n} {\n // Block header size\n const blockHeaderSizeRaw = input[offset];\n if (blockHeaderSizeRaw === 0) {\n throw new Error('Invalid block header size (index indicator found instead of block)');\n }\n const blockHeaderSize = (blockHeaderSizeRaw + 1) * 4;\n\n // Parse block header\n const blockHeaderStart = offset;\n offset++; // skip size byte\n\n const blockFlags = input[offset++];\n const numFilters = (blockFlags & 0x03) + 1;\n const hasCompressedSize = (blockFlags & 0x40) !== 0;\n const hasUncompressedSize = (blockFlags & 0x80) !== 0;\n\n // Skip optional sizes\n if (hasCompressedSize) {\n const result = decodeMultibyte(input, offset);\n offset += result.bytesRead;\n }\n\n if (hasUncompressedSize) {\n const result = decodeMultibyte(input, offset);\n offset += result.bytesRead;\n }\n\n // Parse all filters\n const filters: FilterInfo[] = [];\n let lzma2Props: Buffer | null = null;\n\n for (let i = 0; i < numFilters; i++) {\n const filterIdResult = decodeMultibyte(input, offset);\n const filterId = filterIdResult.value;\n offset += filterIdResult.bytesRead;\n\n const propsSizeResult = decodeMultibyte(input, offset);\n offset += propsSizeResult.bytesRead;\n\n const filterProps = input.slice(offset, offset + propsSizeResult.value);\n offset += propsSizeResult.value;\n\n if (filterId === FILTER_LZMA2) {\n // LZMA2 must be the last filter\n lzma2Props = filterProps;\n } else if (filterId === FILTER_DELTA || (filterId >= FILTER_BCJ_X86 && filterId <= FILTER_BCJ_ARM64)) {\n // Preprocessing filter - store for later application\n filters.push({ id: filterId, props: filterProps });\n } else {\n throw new Error(`Unsupported filter: 0x${filterId.toString(16)}`);\n }\n }\n\n if (!lzma2Props) {\n throw new Error('No LZMA2 filter found in XZ block');\n }\n\n // Skip to end of block header (must be aligned to 4 bytes)\n const blockDataStart = blockHeaderStart + blockHeaderSize;\n\n return {\n filters,\n lzma2Props,\n headerSize: blockHeaderSize,\n dataStart: blockDataStart,\n dataEnd: input.length,\n nextOffset: blockDataStart,\n };\n}\n\n/**\n * Parse XZ Index to get block positions\n *\n * XZ Index stores \"Unpadded Size\" for each block which equals:\n * Block Header Size + Compressed Data Size + Check Size\n * (does NOT include padding to 4-byte boundary)\n */\nfunction parseIndex(\n input: Buffer,\n indexStart: number,\n checkSize: number\n): Array<{\n compressedPos: number;\n compressedDataSize: number;\n uncompressedSize: number;\n}> {\n let offset = indexStart;\n\n // Index indicator (0x00)\n if (input[offset] !== 0x00) {\n throw new Error('Invalid index indicator');\n }\n offset++;\n\n // Number of records\n const countResult = decodeMultibyte(input, offset);\n const recordCount = countResult.value;\n offset += countResult.bytesRead;\n\n const records: Array<{\n compressedPos: number;\n unpaddedSize: number;\n compressedDataSize: number;\n uncompressedSize: number;\n }> = [];\n\n // Parse each record\n for (let i = 0; i < recordCount; i++) {\n // Unpadded Size (header + compressed data + check)\n const unpaddedResult = decodeMultibyte(input, offset);\n offset += unpaddedResult.bytesRead;\n\n // Uncompressed size\n const uncompressedResult = decodeMultibyte(input, offset);\n offset += uncompressedResult.bytesRead;\n\n records.push({\n compressedPos: 0, // will be calculated\n unpaddedSize: unpaddedResult.value,\n compressedDataSize: 0, // will be calculated\n uncompressedSize: uncompressedResult.value,\n });\n }\n\n // Calculate actual positions by walking through blocks\n let currentPos = 12; // After stream header\n for (let i = 0; i < records.length; i++) {\n const record = records[i];\n // Record where this block's header starts\n record.compressedPos = currentPos;\n\n // Get block header size from the actual data\n const headerSizeRaw = input[currentPos];\n const headerSize = (headerSizeRaw + 1) * 4;\n\n // Calculate compressed data size from unpadded size\n // unpaddedSize = headerSize + compressedDataSize + checkSize\n record.compressedDataSize = record.unpaddedSize - headerSize - checkSize;\n\n // Move to next block: unpaddedSize + padding to 4-byte boundary\n const paddedSize = Math.ceil(record.unpaddedSize / 4) * 4;\n currentPos += paddedSize;\n }\n\n return records;\n}\n\n/**\n * Decompress XZ data synchronously\n * Uses @napi-rs/lzma if available on Node 14+, falls back to pure JS\n * Properly handles multi-block XZ files and stream padding\n * @param input - XZ compressed data\n * @returns Decompressed data\n */\nexport function decodeXZ(input: Buffer): Buffer {\n // Try native acceleration first (Node 14+ with @napi-rs/lzma installed)\n const native = tryLoadNative();\n if (native) {\n return native.xz.decompressSync(input);\n }\n\n // Verify XZ magic\n if (input.length < 12 || !bufferEquals(input, 0, XZ_MAGIC)) {\n throw new Error('Invalid XZ magic bytes');\n }\n\n // Stream flags at offset 6-7\n const checkType = input[7] & 0x0f;\n\n // Check sizes based on check type\n const checkSizes: { [key: number]: number } = {\n 0: 0, // None\n 1: 4, // CRC32\n 4: 8, // CRC64\n 10: 32, // SHA-256\n };\n const checkSize = checkSizes[checkType] ?? 0;\n\n // Find footer by skipping stream padding (null bytes at end before footer)\n // Stream padding must be multiple of 4 bytes\n let footerEnd = input.length;\n while (footerEnd > 12 && input[footerEnd - 1] === 0x00) {\n footerEnd--;\n }\n // Align to 4-byte boundary (stream padding rules)\n while (footerEnd % 4 !== 0 && footerEnd > 12) {\n footerEnd++;\n }\n\n // Verify footer magic (at footerEnd - 2)\n if (!bufferEquals(input, footerEnd - 2, XZ_FOOTER_MAGIC)) {\n throw new Error('Invalid XZ footer magic');\n }\n\n // Get backward size (tells us where index starts) - at footerEnd - 8\n const backwardSize = (input.readUInt32LE(footerEnd - 8) + 1) * 4;\n const indexStart = footerEnd - 12 - backwardSize;\n\n // Parse Index to get block information\n const blockRecords = parseIndex(input, indexStart, checkSize);\n\n // Decompress each block\n const outputChunks: Buffer[] = [];\n let _totalOutputSize = 0;\n\n for (let i = 0; i < blockRecords.length; i++) {\n const record = blockRecords[i];\n const recordStart = record.compressedPos;\n\n // Parse block header\n const blockInfo = parseBlockHeader(input, recordStart, checkSize);\n\n // Extract compressed data for this block\n const dataStart = recordStart + blockInfo.headerSize;\n // compressedDataSize is calculated from the Index's Unpadded Size minus header and check\n const dataEnd = dataStart + record.compressedDataSize;\n\n // Note: XZ blocks have padding AFTER the check field to align to 4 bytes,\n // but the compressedSize from index is exact - no need to strip padding.\n // LZMA2 data includes a 0x00 end marker which must NOT be stripped.\n const compressedData = input.slice(dataStart, dataEnd);\n\n // Decompress this block with LZMA2 (fast path, no buffering)\n let blockOutput = decodeLzma2(compressedData, blockInfo.lzma2Props, record.uncompressedSize) as Buffer;\n\n // Apply preprocessing filters in reverse order (BCJ/Delta applied after LZMA2)\n // Filters are stored in order they were applied during compression,\n // so we need to reverse for decompression\n for (let j = blockInfo.filters.length - 1; j >= 0; j--) {\n blockOutput = applyFilter(blockOutput, blockInfo.filters[j]) as Buffer;\n }\n\n outputChunks.push(blockOutput);\n _totalOutputSize += blockOutput.length;\n }\n\n return Buffer.concat(outputChunks);\n}\n\n/**\n * Parse XZ stream to get block information (without decompressing)\n * This allows streaming decompression by processing blocks one at a time.\n */\nfunction parseXZIndex(input: Buffer): Array<{\n compressedPos: number;\n compressedDataSize: number;\n uncompressedSize: number;\n checkSize: number;\n}> {\n // Stream header validation\n if (input.length < 12) {\n throw new Error('XZ file too small');\n }\n\n // Stream magic bytes (0xFD, '7zXZ', 0x00)\n if (input[0] !== 0xfd || input[1] !== 0x37 || input[2] !== 0x7a || input[3] !== 0x58 || input[4] !== 0x5a || input[5] !== 0x00) {\n throw new Error('Invalid XZ magic bytes');\n }\n\n // Stream flags at offset 6-7\n const checkType = input[7] & 0x0f;\n\n // Check sizes based on check type\n const checkSizes: { [key: number]: number } = {\n 0: 0, // None\n 1: 4, // CRC32\n 4: 8, // CRC64\n 10: 32, // SHA-256\n };\n const checkSize = checkSizes[checkType] ?? 0;\n\n // Find footer by skipping stream padding\n let footerEnd = input.length;\n while (footerEnd > 12 && input[footerEnd - 1] === 0x00) {\n footerEnd--;\n }\n while (footerEnd % 4 !== 0 && footerEnd > 12) {\n footerEnd++;\n }\n\n // Verify footer magic\n if (!bufferEquals(input, footerEnd - 2, XZ_FOOTER_MAGIC)) {\n throw new Error('Invalid XZ footer magic');\n }\n\n // Get backward size\n const backwardSize = (input.readUInt32LE(footerEnd - 8) + 1) * 4;\n const indexStart = footerEnd - 12 - backwardSize;\n\n // Parse Index to get block information\n return parseIndex(input, indexStart, checkSize).map((record) => ({\n ...record,\n checkSize,\n }));\n}\n\n/**\n * Create an XZ decompression Transform stream\n * @returns Transform stream that decompresses XZ data\n */\nexport function createXZDecoder(): TransformType {\n const chunks: Buffer[] = [];\n\n return new Transform({\n transform(chunk: Buffer, _encoding: string, callback: (error?: Error | null) => void) {\n chunks.push(chunk);\n callback();\n },\n\n flush(callback: (error?: Error | null) => void) {\n try {\n const input = Buffer.concat(chunks);\n\n // Stream decode each block instead of buffering all output\n const blockRecords = parseXZIndex(input);\n\n for (let i = 0; i < blockRecords.length; i++) {\n const record = blockRecords[i];\n const recordStart = record.compressedPos;\n\n // Parse block header\n const blockInfo = parseBlockHeader(input, recordStart, blockRecords[i].checkSize);\n\n // Extract compressed data for this block\n const dataStart = recordStart + blockInfo.headerSize;\n const dataEnd = dataStart + record.compressedDataSize;\n const compressedData = input.slice(dataStart, dataEnd);\n\n // Decompress this block\n let blockOutput = decodeLzma2(compressedData, blockInfo.lzma2Props, record.uncompressedSize) as Buffer;\n\n // Apply preprocessing filters in reverse order\n for (let j = blockInfo.filters.length - 1; j >= 0; j--) {\n blockOutput = applyFilter(blockOutput, blockInfo.filters[j]) as Buffer;\n }\n\n // Push block output immediately instead of buffering\n this.push(blockOutput);\n }\n\n callback();\n } catch (err) {\n callback(err as Error);\n }\n },\n });\n}\n"],"names":["createXZDecoder","decodeXZ","XZ_MAGIC","XZ_FOOTER_MAGIC","FILTER_DELTA","FILTER_BCJ_X86","FILTER_BCJ_PPC","FILTER_BCJ_IA64","FILTER_BCJ_ARM","FILTER_BCJ_ARMT","FILTER_BCJ_SPARC","FILTER_BCJ_ARM64","FILTER_LZMA2","bufferEquals","buf","offset","expected","length","i","decodeMultibyte","value","byte","Error","bytesRead","applyFilter","data","filter","id","decodeBcj","props","decodeBcjArm","decodeBcjArm64","decodeBcjArmt","decodeBcjPpc","decodeBcjSparc","decodeBcjIa64","decodeDelta","toString","parseBlockHeader","input","_checkSize","blockHeaderSizeRaw","blockHeaderSize","blockHeaderStart","blockFlags","numFilters","hasCompressedSize","hasUncompressedSize","result","filters","lzma2Props","filterIdResult","filterId","propsSizeResult","filterProps","slice","push","blockDataStart","headerSize","dataStart","dataEnd","nextOffset","parseIndex","indexStart","checkSize","countResult","recordCount","records","unpaddedResult","uncompressedResult","compressedPos","unpaddedSize","compressedDataSize","uncompressedSize","currentPos","record","headerSizeRaw","paddedSize","Math","ceil","checkSizes","native","tryLoadNative","xz","decompressSync","checkType","footerEnd","backwardSize","readUInt32LE","blockRecords","outputChunks","_totalOutputSize","recordStart","blockInfo","compressedData","blockOutput","decodeLzma2","j","Buffer","concat","parseXZIndex","map","chunks","Transform","transform","chunk","_encoding","callback","flush","err"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC;;;;;;;;;;;QA+ZeA;eAAAA;;QAlJAC;eAAAA;;;mCA3QU;qBAEA;wBACG;0BACE;yBACD;yBACA;wBACD;0BACE;uBACH;uBACA;wBACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,iBAAiB;AACjB,IAAMC,WAAW;IAAC;IAAM;IAAM;IAAM;IAAM;IAAM;CAAK;AACrD,IAAMC,kBAAkB;IAAC;IAAM;CAAK,EAAE,OAAO;AAE7C,qCAAqC;AACrC,IAAMC,eAAe;AACrB,IAAMC,iBAAiB;AACvB,IAAMC,iBAAiB;AACvB,IAAMC,kBAAkB;AACxB,IAAMC,iBAAiB;AACvB,IAAMC,kBAAkB;AACxB,IAAMC,mBAAmB;AACzB,IAAMC,mBAAmB;AACzB,IAAMC,eAAe;AAQrB;;CAEC,GACD,SAASC,aA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LzmaDecoder.js';
164
164
  }
165
165
  // Determine solid mode - preserve dictionary if not resetting state or if only resetting state (not dict)
166
166
  const useSolid = !chunk.stateReset || chunk.stateReset && !chunk.dictReset;
167
- // Decode LZMA chunk
168
- const chunkData = input.slice(dataOffset, dataOffset + chunk.compSize);
169
- const decoded = this.lzmaDecoder.decode(chunkData, 0, chunk.uncompSize, useSolid);
170
- // Copy to output
167
+ // Decode LZMA chunk - use zero-copy when we have pre-allocated buffer
171
168
  if (outputBuffer) {
172
- decoded.copy(outputBuffer, outputPos);
173
- outputPos += decoded.length;
169
+ // Zero-copy: decode directly into caller's buffer
170
+ const bytesWritten = this.lzmaDecoder.decodeToBuffer(input, dataOffset, chunk.uncompSize, outputBuffer, outputPos, useSolid);
171
+ outputPos += bytesWritten;
174
172
  } else {
173
+ // No pre-allocation: decode to new buffer and collect chunks
174
+ const chunkData = input.slice(dataOffset, dataOffset + chunk.compSize);
175
+ const decoded = this.lzmaDecoder.decode(chunkData, 0, chunk.uncompSize, useSolid);
175
176
  outputChunks.push(decoded);
176
177
  }
177
178
  offset = dataOffset + chunk.compSize;
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/iterators/xz-compat/src/lzma/sync/Lzma2Decoder.ts"],"sourcesContent":["/**\n * Synchronous LZMA2 Decoder\n *\n * LZMA2 is a container format that wraps LZMA chunks with framing.\n * Decodes LZMA2 data from a buffer.\n */\n\nimport { allocBufferUnsafe } from 'extract-base-iterator';\nimport { parseLzma2ChunkHeader } from '../Lzma2ChunkParser.ts';\nimport { type OutputSink, parseLzma2DictionarySize } from '../types.ts';\nimport { LzmaDecoder } from './LzmaDecoder.ts';\n\n/**\n * Synchronous LZMA2 decoder\n */\nexport class Lzma2Decoder {\n private lzmaDecoder: LzmaDecoder;\n private dictionarySize: number;\n private propsSet: boolean;\n\n constructor(properties: Buffer | Uint8Array, outputSink?: OutputSink) {\n if (!properties || properties.length < 1) {\n throw new Error('LZMA2 requires properties byte');\n }\n\n this.dictionarySize = parseLzma2DictionarySize(properties[0]);\n this.lzmaDecoder = new LzmaDecoder(outputSink);\n this.lzmaDecoder.setDictionarySize(this.dictionarySize);\n this.propsSet = false;\n }\n\n /**\n * Reset the dictionary (for stream boundaries)\n */\n resetDictionary(): void {\n this.lzmaDecoder.resetDictionary();\n }\n\n /**\n * Reset all probability models (for stream boundaries)\n */\n resetProbabilities(): void {\n this.lzmaDecoder.resetProbabilities();\n }\n\n /**\n * Set LZMA properties\n */\n setLcLpPb(lc: number, lp: number, pb: number): boolean {\n return this.lzmaDecoder.setLcLpPb(lc, lp, pb);\n }\n\n /**\n * Feed uncompressed data to the dictionary (for subsequent LZMA chunks)\n */\n feedUncompressed(data: Buffer): void {\n this.lzmaDecoder.feedUncompressed(data);\n }\n\n /**\n * Decode raw LZMA data (used internally for LZMA2 chunks)\n * @param input - LZMA compressed data\n * @param offset - Input offset\n * @param outSize - Expected output size\n * @param solid - Use solid mode\n * @returns Decompressed data\n */\n decodeLzmaData(input: Buffer, offset: number, outSize: number, solid = false): Buffer {\n return this.lzmaDecoder.decode(input, offset, outSize, solid);\n }\n\n /**\n * Decode LZMA2 data with streaming output\n * @param input - LZMA2 compressed data\n * @returns Total number of bytes written to sink\n */\n decodeWithSink(input: Buffer): number {\n let totalBytes = 0;\n let offset = 0;\n\n while (offset < input.length) {\n const result = parseLzma2ChunkHeader(input, offset);\n\n if (!result.success) {\n throw new Error('Truncated LZMA2 chunk header');\n }\n\n const chunk = result.chunk;\n\n if (chunk.type === 'end') {\n break;\n }\n\n // Validate we have enough data for the chunk\n const dataSize = chunk.type === 'uncompressed' ? chunk.uncompSize : chunk.compSize;\n if (offset + chunk.headerSize + dataSize > input.length) {\n throw new Error(`Truncated LZMA2 ${chunk.type} data`);\n }\n\n // Handle dictionary reset\n if (chunk.dictReset) {\n this.lzmaDecoder.resetDictionary();\n }\n\n const dataOffset = offset + chunk.headerSize;\n\n if (chunk.type === 'uncompressed') {\n const uncompData = input.slice(dataOffset, dataOffset + chunk.uncompSize);\n\n // Feed uncompressed data to dictionary so subsequent LZMA chunks can reference it\n this.lzmaDecoder.feedUncompressed(uncompData);\n\n totalBytes += uncompData.length;\n offset = dataOffset + chunk.uncompSize;\n } else {\n // LZMA compressed chunk\n\n // Apply new properties if present\n if (chunk.newProps) {\n const { lc, lp, pb } = chunk.newProps;\n if (!this.lzmaDecoder.setLcLpPb(lc, lp, pb)) {\n throw new Error(`Invalid LZMA properties: lc=${lc} lp=${lp} pb=${pb}`);\n }\n this.propsSet = true;\n }\n\n if (!this.propsSet) {\n throw new Error('LZMA chunk without properties');\n }\n\n // Reset probabilities if state reset\n if (chunk.stateReset) {\n this.lzmaDecoder.resetProbabilities();\n }\n\n // Determine solid mode\n const useSolid = !chunk.stateReset || (chunk.stateReset && !chunk.dictReset);\n\n // Decode LZMA chunk directly to sink\n totalBytes += this.lzmaDecoder.decodeWithSink(input, dataOffset, chunk.uncompSize, useSolid);\n\n offset = dataOffset + chunk.compSize;\n }\n }\n\n // Flush any remaining data in the OutWindow\n this.lzmaDecoder.flushOutWindow();\n\n return totalBytes;\n }\n\n /**\n * Decode LZMA2 data\n * @param input - LZMA2 compressed data\n * @param unpackSize - Expected output size (optional, for pre-allocation)\n * @returns Decompressed data\n */\n decode(input: Buffer, unpackSize?: number): Buffer {\n // Pre-allocate output buffer if size is known\n let outputBuffer: Buffer | null = null;\n let outputPos = 0;\n const outputChunks: Buffer[] = [];\n\n if (unpackSize && unpackSize > 0) {\n outputBuffer = allocBufferUnsafe(unpackSize);\n }\n\n let offset = 0;\n\n while (offset < input.length) {\n const result = parseLzma2ChunkHeader(input, offset);\n\n if (!result.success) {\n throw new Error('Truncated LZMA2 chunk header');\n }\n\n const chunk = result.chunk;\n\n if (chunk.type === 'end') {\n break;\n }\n\n // Validate we have enough data for the chunk\n const dataSize = chunk.type === 'uncompressed' ? chunk.uncompSize : chunk.compSize;\n if (offset + chunk.headerSize + dataSize > input.length) {\n throw new Error(`Truncated LZMA2 ${chunk.type} data`);\n }\n\n // Handle dictionary reset\n if (chunk.dictReset) {\n this.lzmaDecoder.resetDictionary();\n }\n\n const dataOffset = offset + chunk.headerSize;\n\n if (chunk.type === 'uncompressed') {\n const uncompData = input.slice(dataOffset, dataOffset + chunk.uncompSize);\n\n // Copy to output\n if (outputBuffer) {\n uncompData.copy(outputBuffer, outputPos);\n outputPos += uncompData.length;\n } else {\n outputChunks.push(uncompData);\n }\n\n // Feed uncompressed data to dictionary so subsequent LZMA chunks can reference it\n this.lzmaDecoder.feedUncompressed(uncompData);\n\n offset = dataOffset + chunk.uncompSize;\n } else {\n // LZMA compressed chunk\n\n // Apply new properties if present\n if (chunk.newProps) {\n const { lc, lp, pb } = chunk.newProps;\n if (!this.lzmaDecoder.setLcLpPb(lc, lp, pb)) {\n throw new Error(`Invalid LZMA properties: lc=${lc} lp=${lp} pb=${pb}`);\n }\n this.propsSet = true;\n }\n\n if (!this.propsSet) {\n throw new Error('LZMA chunk without properties');\n }\n\n // Reset probabilities if state reset\n if (chunk.stateReset) {\n this.lzmaDecoder.resetProbabilities();\n }\n\n // Determine solid mode - preserve dictionary if not resetting state or if only resetting state (not dict)\n const useSolid = !chunk.stateReset || (chunk.stateReset && !chunk.dictReset);\n\n // Decode LZMA chunk\n const chunkData = input.slice(dataOffset, dataOffset + chunk.compSize);\n const decoded = this.lzmaDecoder.decode(chunkData, 0, chunk.uncompSize, useSolid);\n\n // Copy to output\n if (outputBuffer) {\n decoded.copy(outputBuffer, outputPos);\n outputPos += decoded.length;\n } else {\n outputChunks.push(decoded);\n }\n\n offset = dataOffset + chunk.compSize;\n }\n }\n\n // Return pre-allocated buffer or concatenated chunks\n if (outputBuffer) {\n return outputPos < outputBuffer.length ? outputBuffer.slice(0, outputPos) : outputBuffer;\n }\n return Buffer.concat(outputChunks);\n }\n}\n\n/**\n * Decode LZMA2 data synchronously\n * @param input - LZMA2 compressed data\n * @param properties - 1-byte properties (dictionary size)\n * @param unpackSize - Expected output size (optional, autodetects if not provided)\n * @param outputSink - Optional output sink with write callback for streaming (returns bytes written)\n * @returns Decompressed data (or bytes written if outputSink provided)\n */\nexport function decodeLzma2(input: Buffer, properties: Buffer | Uint8Array, unpackSize?: number, outputSink?: { write(buffer: Buffer): void }): Buffer | number {\n const decoder = new Lzma2Decoder(properties, outputSink as OutputSink);\n if (outputSink) {\n // Zero-copy mode: write to sink during decode\n return decoder.decodeWithSink(input);\n }\n // Buffering mode: returns Buffer (zero-copy)\n return decoder.decode(input, unpackSize);\n}\n"],"names":["allocBufferUnsafe","parseLzma2ChunkHeader","parseLzma2DictionarySize","LzmaDecoder","Lzma2Decoder","resetDictionary","lzmaDecoder","resetProbabilities","setLcLpPb","lc","lp","pb","feedUncompressed","data","decodeLzmaData","input","offset","outSize","solid","decode","decodeWithSink","totalBytes","length","result","success","Error","chunk","type","dataSize","uncompSize","compSize","headerSize","dictReset","dataOffset","uncompData","slice","newProps","propsSet","stateReset","useSolid","flushOutWindow","unpackSize","outputBuffer","outputPos","outputChunks","copy","push","chunkData","decoded","Buffer","concat","properties","outputSink","dictionarySize","setDictionarySize","decodeLzma2","decoder"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,qBAAqB,QAAQ,yBAAyB;AAC/D,SAA0BC,wBAAwB,QAAQ,cAAc;AACxE,SAASC,WAAW,QAAQ,mBAAmB;AAE/C;;CAEC,GACD,OAAO,MAAMC;IAgBX;;GAEC,GACDC,kBAAwB;QACtB,IAAI,CAACC,WAAW,CAACD,eAAe;IAClC;IAEA;;GAEC,GACDE,qBAA2B;QACzB,IAAI,CAACD,WAAW,CAACC,kBAAkB;IACrC;IAEA;;GAEC,GACDC,UAAUC,EAAU,EAAEC,EAAU,EAAEC,EAAU,EAAW;QACrD,OAAO,IAAI,CAACL,WAAW,CAACE,SAAS,CAACC,IAAIC,IAAIC;IAC5C;IAEA;;GAEC,GACDC,iBAAiBC,IAAY,EAAQ;QACnC,IAAI,CAAC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C,YAAYC;IAC7C,IAAIA,YAAY;QACd,8CAA8C;QAC9C,OAAOI,QAAQpC,cAAc,CAACL;IAChC;IACA,6CAA6C;IAC7C,OAAOyC,QAAQrC,MAAM,CAACJ,OAAO0B;AAC/B"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/iterators/xz-compat/src/lzma/sync/Lzma2Decoder.ts"],"sourcesContent":["/**\n * Synchronous LZMA2 Decoder\n *\n * LZMA2 is a container format that wraps LZMA chunks with framing.\n * Decodes LZMA2 data from a buffer.\n */\n\nimport { allocBufferUnsafe } from 'extract-base-iterator';\nimport { parseLzma2ChunkHeader } from '../Lzma2ChunkParser.ts';\nimport { type OutputSink, parseLzma2DictionarySize } from '../types.ts';\nimport { LzmaDecoder } from './LzmaDecoder.ts';\n\n/**\n * Synchronous LZMA2 decoder\n */\nexport class Lzma2Decoder {\n private lzmaDecoder: LzmaDecoder;\n private dictionarySize: number;\n private propsSet: boolean;\n\n constructor(properties: Buffer | Uint8Array, outputSink?: OutputSink) {\n if (!properties || properties.length < 1) {\n throw new Error('LZMA2 requires properties byte');\n }\n\n this.dictionarySize = parseLzma2DictionarySize(properties[0]);\n this.lzmaDecoder = new LzmaDecoder(outputSink);\n this.lzmaDecoder.setDictionarySize(this.dictionarySize);\n this.propsSet = false;\n }\n\n /**\n * Reset the dictionary (for stream boundaries)\n */\n resetDictionary(): void {\n this.lzmaDecoder.resetDictionary();\n }\n\n /**\n * Reset all probability models (for stream boundaries)\n */\n resetProbabilities(): void {\n this.lzmaDecoder.resetProbabilities();\n }\n\n /**\n * Set LZMA properties\n */\n setLcLpPb(lc: number, lp: number, pb: number): boolean {\n return this.lzmaDecoder.setLcLpPb(lc, lp, pb);\n }\n\n /**\n * Feed uncompressed data to the dictionary (for subsequent LZMA chunks)\n */\n feedUncompressed(data: Buffer): void {\n this.lzmaDecoder.feedUncompressed(data);\n }\n\n /**\n * Decode raw LZMA data (used internally for LZMA2 chunks)\n * @param input - LZMA compressed data\n * @param offset - Input offset\n * @param outSize - Expected output size\n * @param solid - Use solid mode\n * @returns Decompressed data\n */\n decodeLzmaData(input: Buffer, offset: number, outSize: number, solid = false): Buffer {\n return this.lzmaDecoder.decode(input, offset, outSize, solid);\n }\n\n /**\n * Decode LZMA2 data with streaming output\n * @param input - LZMA2 compressed data\n * @returns Total number of bytes written to sink\n */\n decodeWithSink(input: Buffer): number {\n let totalBytes = 0;\n let offset = 0;\n\n while (offset < input.length) {\n const result = parseLzma2ChunkHeader(input, offset);\n\n if (!result.success) {\n throw new Error('Truncated LZMA2 chunk header');\n }\n\n const chunk = result.chunk;\n\n if (chunk.type === 'end') {\n break;\n }\n\n // Validate we have enough data for the chunk\n const dataSize = chunk.type === 'uncompressed' ? chunk.uncompSize : chunk.compSize;\n if (offset + chunk.headerSize + dataSize > input.length) {\n throw new Error(`Truncated LZMA2 ${chunk.type} data`);\n }\n\n // Handle dictionary reset\n if (chunk.dictReset) {\n this.lzmaDecoder.resetDictionary();\n }\n\n const dataOffset = offset + chunk.headerSize;\n\n if (chunk.type === 'uncompressed') {\n const uncompData = input.slice(dataOffset, dataOffset + chunk.uncompSize);\n\n // Feed uncompressed data to dictionary so subsequent LZMA chunks can reference it\n this.lzmaDecoder.feedUncompressed(uncompData);\n\n totalBytes += uncompData.length;\n offset = dataOffset + chunk.uncompSize;\n } else {\n // LZMA compressed chunk\n\n // Apply new properties if present\n if (chunk.newProps) {\n const { lc, lp, pb } = chunk.newProps;\n if (!this.lzmaDecoder.setLcLpPb(lc, lp, pb)) {\n throw new Error(`Invalid LZMA properties: lc=${lc} lp=${lp} pb=${pb}`);\n }\n this.propsSet = true;\n }\n\n if (!this.propsSet) {\n throw new Error('LZMA chunk without properties');\n }\n\n // Reset probabilities if state reset\n if (chunk.stateReset) {\n this.lzmaDecoder.resetProbabilities();\n }\n\n // Determine solid mode\n const useSolid = !chunk.stateReset || (chunk.stateReset && !chunk.dictReset);\n\n // Decode LZMA chunk directly to sink\n totalBytes += this.lzmaDecoder.decodeWithSink(input, dataOffset, chunk.uncompSize, useSolid);\n\n offset = dataOffset + chunk.compSize;\n }\n }\n\n // Flush any remaining data in the OutWindow\n this.lzmaDecoder.flushOutWindow();\n\n return totalBytes;\n }\n\n /**\n * Decode LZMA2 data\n * @param input - LZMA2 compressed data\n * @param unpackSize - Expected output size (optional, for pre-allocation)\n * @returns Decompressed data\n */\n decode(input: Buffer, unpackSize?: number): Buffer {\n // Pre-allocate output buffer if size is known\n let outputBuffer: Buffer | null = null;\n let outputPos = 0;\n const outputChunks: Buffer[] = [];\n\n if (unpackSize && unpackSize > 0) {\n outputBuffer = allocBufferUnsafe(unpackSize);\n }\n\n let offset = 0;\n\n while (offset < input.length) {\n const result = parseLzma2ChunkHeader(input, offset);\n\n if (!result.success) {\n throw new Error('Truncated LZMA2 chunk header');\n }\n\n const chunk = result.chunk;\n\n if (chunk.type === 'end') {\n break;\n }\n\n // Validate we have enough data for the chunk\n const dataSize = chunk.type === 'uncompressed' ? chunk.uncompSize : chunk.compSize;\n if (offset + chunk.headerSize + dataSize > input.length) {\n throw new Error(`Truncated LZMA2 ${chunk.type} data`);\n }\n\n // Handle dictionary reset\n if (chunk.dictReset) {\n this.lzmaDecoder.resetDictionary();\n }\n\n const dataOffset = offset + chunk.headerSize;\n\n if (chunk.type === 'uncompressed') {\n const uncompData = input.slice(dataOffset, dataOffset + chunk.uncompSize);\n\n // Copy to output\n if (outputBuffer) {\n uncompData.copy(outputBuffer, outputPos);\n outputPos += uncompData.length;\n } else {\n outputChunks.push(uncompData);\n }\n\n // Feed uncompressed data to dictionary so subsequent LZMA chunks can reference it\n this.lzmaDecoder.feedUncompressed(uncompData);\n\n offset = dataOffset + chunk.uncompSize;\n } else {\n // LZMA compressed chunk\n\n // Apply new properties if present\n if (chunk.newProps) {\n const { lc, lp, pb } = chunk.newProps;\n if (!this.lzmaDecoder.setLcLpPb(lc, lp, pb)) {\n throw new Error(`Invalid LZMA properties: lc=${lc} lp=${lp} pb=${pb}`);\n }\n this.propsSet = true;\n }\n\n if (!this.propsSet) {\n throw new Error('LZMA chunk without properties');\n }\n\n // Reset probabilities if state reset\n if (chunk.stateReset) {\n this.lzmaDecoder.resetProbabilities();\n }\n\n // Determine solid mode - preserve dictionary if not resetting state or if only resetting state (not dict)\n const useSolid = !chunk.stateReset || (chunk.stateReset && !chunk.dictReset);\n\n // Decode LZMA chunk - use zero-copy when we have pre-allocated buffer\n if (outputBuffer) {\n // Zero-copy: decode directly into caller's buffer\n const bytesWritten = this.lzmaDecoder.decodeToBuffer(input, dataOffset, chunk.uncompSize, outputBuffer, outputPos, useSolid);\n outputPos += bytesWritten;\n } else {\n // No pre-allocation: decode to new buffer and collect chunks\n const chunkData = input.slice(dataOffset, dataOffset + chunk.compSize);\n const decoded = this.lzmaDecoder.decode(chunkData, 0, chunk.uncompSize, useSolid);\n outputChunks.push(decoded);\n }\n\n offset = dataOffset + chunk.compSize;\n }\n }\n\n // Return pre-allocated buffer or concatenated chunks\n if (outputBuffer) {\n return outputPos < outputBuffer.length ? outputBuffer.slice(0, outputPos) : outputBuffer;\n }\n return Buffer.concat(outputChunks);\n }\n}\n\n/**\n * Decode LZMA2 data synchronously\n * @param input - LZMA2 compressed data\n * @param properties - 1-byte properties (dictionary size)\n * @param unpackSize - Expected output size (optional, autodetects if not provided)\n * @param outputSink - Optional output sink with write callback for streaming (returns bytes written)\n * @returns Decompressed data (or bytes written if outputSink provided)\n */\nexport function decodeLzma2(input: Buffer, properties: Buffer | Uint8Array, unpackSize?: number, outputSink?: { write(buffer: Buffer): void }): Buffer | number {\n const decoder = new Lzma2Decoder(properties, outputSink as OutputSink);\n if (outputSink) {\n // Zero-copy mode: write to sink during decode\n return decoder.decodeWithSink(input);\n }\n // Buffering mode: returns Buffer (zero-copy)\n return decoder.decode(input, unpackSize);\n}\n"],"names":["allocBufferUnsafe","parseLzma2ChunkHeader","parseLzma2DictionarySize","LzmaDecoder","Lzma2Decoder","resetDictionary","lzmaDecoder","resetProbabilities","setLcLpPb","lc","lp","pb","feedUncompressed","data","decodeLzmaData","input","offset","outSize","solid","decode","decodeWithSink","totalBytes","length","result","success","Error","chunk","type","dataSize","uncompSize","compSize","headerSize","dictReset","dataOffset","uncompData","slice","newProps","propsSet","stateReset","useSolid","flushOutWindow","unpackSize","outputBuffer","outputPos","outputChunks","copy","push","bytesWritten","decodeToBuffer","chunkData","decoded","Buffer","concat","properties","outputSink","dictionarySize","setDictionarySize","decodeLzma2","decoder"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,qBAAqB,QAAQ,yBAAyB;AAC/D,SAA0BC,wBAAwB,QAAQ,cAAc;AACxE,SAASC,WAAW,QAAQ,mBAAmB;AAE/C;;CAEC,GACD,OAAO,MAAMC;IAgBX;;GAEC,GACDC,kBAAwB;QACtB,IAAI,CAACC,WAAW,CAACD,eAAe;IAClC;IAEA;;GAEC,GACDE,qBAA2B;QACzB,IAAI,CAACD,WAAW,CAACC,kBAAkB;IACrC;IAEA;;GAEC,GACDC,UAAUC,EAAU,EAAEC,EAAU,EAAEC,EAAU,EAAW;QACrD,OAAO,IAAI,CAACL,WAAW,CAACE,SAAS,CAACC,IAAIC,IAAIC;IAC5C;IAEA;;GAEC,GACDC,iBAAiBC,IAAY,EAAQ;QACnC,IAAI,CAACP,WAAW,CAACM,gBAAgB,CAACC;IACpC;IAEA;;;;;;;GAOC,GACDC,eAAeC,KAAa,EAAEC,MAAc,EAAEC,OAAe,EAAEC,QAAQ,KAAK,EAAU;QACpF,OAAO,IAAI,CAACZ,WAAW,CAACa,MAAM,CAACJ,OAAOC,QAAQC,SAASC;IACzD;IAEA;;;;GAIC,GACDE,eAAeL,KAAa,EAAU;QACpC,IAAIM,aAAa;QACjB,IAAIL,SAAS;QAEb,MAAOA,SAASD,MAAMO,MAAM,CAAE;YAC5B,MAAMC,SAAStB,sBAAsBc,OAAOC;YAE5C,IAAI,CAACO,OAAOC,OAAO,EAAE;gBACnB,MAA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AA6D;oBAC7D,MAAME,YAAYlC,MAAMoB,KAAK,CAACF,YAAYA,aAAaP,MAAMI,QAAQ;oBACrE,MAAMoB,UAAU,IAAI,CAAC5C,WAAW,CAACa,MAAM,CAAC8B,WAAW,GAAGvB,MAAMG,UAAU,EAAEU;oBACxEK,aAAaE,IAAI,CAACI;gBACpB;gBAEAlC,SAASiB,aAAaP,MAAMI,QAAQ;YACtC;QACF;QAEA,qDAAqD;QACrD,IAAIY,cAAc;YAChB,OAAOC,YAAYD,aAAapB,MAAM,GAAGoB,aAAaP,KAAK,CAAC,GAAGQ,aAAaD;QAC9E;QACA,OAAOS,OAAOC,MAAM,CAACR;IACvB;IA3OA,YAAYS,UAA+B,EAAEC,UAAuB,CAAE;QACpE,IAAI,CAACD,cAAcA,WAAW/B,MAAM,GAAG,GAAG;YACxC,MAAM,IAAIG,MAAM;QAClB;QAEA,IAAI,CAAC8B,cAAc,GAAGrD,yBAAyBmD,UAAU,CAAC,EAAE;QAC5D,IAAI,CAAC/C,WAAW,GAAG,IAAIH,YAAYmD;QACnC,IAAI,CAAChD,WAAW,CAACkD,iBAAiB,CAAC,IAAI,CAACD,cAAc;QACtD,IAAI,CAAClB,QAAQ,GAAG;IAClB;AAmOF;AAEA;;;;;;;CAOC,GACD,OAAO,SAASoB,YAAY1C,KAAa,EAAEsC,UAA+B,EAAEZ,UAAmB,EAAEa,UAA4C;IAC3I,MAAMI,UAAU,IAAItD,aAAaiD,YAAYC;IAC7C,IAAIA,YAAY;QACd,8CAA8C;QAC9C,OAAOI,QAAQtC,cAAc,CAACL;IAChC;IACA,6CAA6C;IAC7C,OAAO2C,QAAQvC,MAAM,CAACJ,OAAO0B;AAC/B"}
@@ -76,6 +76,17 @@ export declare class LzmaDecoder {
76
76
  * @returns Number of bytes written to sink
77
77
  */
78
78
  decodeWithSink(input: Buffer, inputOffset: number, outSize: number, solid?: boolean): number;
79
+ /**
80
+ * Decode LZMA data directly into caller's buffer (zero-copy)
81
+ * @param input - Compressed input buffer
82
+ * @param inputOffset - Offset into input buffer
83
+ * @param outSize - Expected output size
84
+ * @param output - Pre-allocated output buffer to write to
85
+ * @param outputOffset - Offset in output buffer to start writing
86
+ * @param solid - If true, preserve state from previous decode
87
+ * @returns Number of bytes written
88
+ */
89
+ decodeToBuffer(input: Buffer, inputOffset: number, outSize: number, output: Buffer, outputOffset: number, solid?: boolean): number;
79
90
  /**
80
91
  * Decode LZMA data
81
92
  * @param input - Compressed input buffer
@@ -383,13 +383,15 @@ import { BitTreeDecoder, RangeDecoder, reverseDecodeFromArray } from './RangeDec
383
383
  return outPos;
384
384
  }
385
385
  /**
386
- * Decode LZMA data
386
+ * Decode LZMA data directly into caller's buffer (zero-copy)
387
387
  * @param input - Compressed input buffer
388
388
  * @param inputOffset - Offset into input buffer
389
389
  * @param outSize - Expected output size
390
+ * @param output - Pre-allocated output buffer to write to
391
+ * @param outputOffset - Offset in output buffer to start writing
390
392
  * @param solid - If true, preserve state from previous decode
391
- * @returns Decompressed data
392
- */ decode(input, inputOffset, outSize, solid = false) {
393
+ * @returns Number of bytes written
394
+ */ decodeToBuffer(input, inputOffset, outSize, output, outputOffset, solid = false) {
393
395
  this.rangeDecoder.setInput(input, inputOffset);
394
396
  if (!solid) {
395
397
  this.outWindow.init(false);
@@ -405,10 +407,10 @@ import { BitTreeDecoder, RangeDecoder, reverseDecodeFromArray } from './RangeDec
405
407
  // Solid mode: preserve dictionary state but reinitialize range decoder
406
408
  this.outWindow.init(true);
407
409
  }
408
- const output = allocBufferUnsafe(outSize);
409
- let outPos = 0;
410
+ let outPos = outputOffset;
411
+ const outEnd = outputOffset + outSize;
410
412
  let cumPos = this.totalPos;
411
- while(outPos < outSize){
413
+ while(outPos < outEnd){
412
414
  const posState = cumPos & this.posStateMask;
413
415
  if (this.rangeDecoder.decodeBit(this.isMatchDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {
414
416
  // Literal
@@ -492,6 +494,18 @@ import { BitTreeDecoder, RangeDecoder, reverseDecodeFromArray } from './RangeDec
492
494
  }
493
495
  }
494
496
  this.totalPos = cumPos;
497
+ return outPos - outputOffset;
498
+ }
499
+ /**
500
+ * Decode LZMA data
501
+ * @param input - Compressed input buffer
502
+ * @param inputOffset - Offset into input buffer
503
+ * @param outSize - Expected output size
504
+ * @param solid - If true, preserve state from previous decode
505
+ * @returns Decompressed data
506
+ */ decode(input, inputOffset, outSize, solid = false) {
507
+ const output = allocBufferUnsafe(outSize);
508
+ this.decodeToBuffer(input, inputOffset, outSize, output, 0, solid);
495
509
  return output;
496
510
  }
497
511
  constructor(outputSink){
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/iterators/xz-compat/src/lzma/sync/LzmaDecoder.ts"],"sourcesContent":["/**\n * Synchronous LZMA1 Decoder\n *\n * Decodes LZMA1 compressed data from a buffer.\n * All operations are synchronous.\n */\n\nimport { allocBufferUnsafe, bufferFrom } from 'extract-base-iterator';\nimport {\n getLenToPosState,\n initBitModels,\n kEndPosModelIndex,\n kMatchMinLen,\n kNumAlignBits,\n kNumFullDistances,\n kNumLenToPosStates,\n kNumLitContextBitsMax,\n kNumPosSlotBits,\n kNumPosStatesBitsMax,\n kNumStates,\n kStartPosModelIndex,\n type OutputSink,\n parseProperties,\n stateIsCharState,\n stateUpdateChar,\n stateUpdateMatch,\n stateUpdateRep,\n stateUpdateShortRep,\n} from '../types.ts';\nimport { BitTreeDecoder, RangeDecoder, reverseDecodeFromArray } from './RangeDecoder.ts';\n\n/**\n * Length decoder for match/rep lengths\n */\nclass LenDecoder {\n private choice: Uint16Array;\n private lowCoder: BitTreeDecoder[];\n private midCoder: BitTreeDecoder[];\n private highCoder: BitTreeDecoder;\n private numPosStates: number;\n\n constructor() {\n this.choice = initBitModels(null, 2);\n this.lowCoder = [];\n this.midCoder = [];\n this.highCoder = new BitTreeDecoder(8);\n this.numPosStates = 0;\n }\n\n create(numPosStates: number): void {\n for (; this.numPosStates < numPosStates; this.numPosStates++) {\n this.lowCoder[this.numPosStates] = new BitTreeDecoder(3);\n this.midCoder[this.numPosStates] = new BitTreeDecoder(3);\n }\n }\n\n init(): void {\n initBitModels(this.choice);\n for (let i = this.numPosStates - 1; i >= 0; i--) {\n this.lowCoder[i].init();\n this.midCoder[i].init();\n }\n this.highCoder.init();\n }\n\n decode(rangeDecoder: RangeDecoder, posState: number): number {\n if (rangeDecoder.decodeBit(this.choice, 0) === 0) {\n return this.lowCoder[posState].decode(rangeDecoder);\n }\n if (rangeDecoder.decodeBit(this.choice, 1) === 0) {\n return 8 + this.midCoder[posState].decode(rangeDecoder);\n }\n return 16 + this.highCoder.decode(rangeDecoder);\n }\n}\n\n/**\n * Single literal decoder (decodes one byte)\n */\nclass LiteralDecoder2 {\n private decoders: Uint16Array;\n\n constructor() {\n this.decoders = initBitModels(null, 0x300);\n }\n\n init(): void {\n initBitModels(this.decoders);\n }\n\n decodeNormal(rangeDecoder: RangeDecoder): number {\n let symbol = 1;\n do {\n symbol = (symbol << 1) | rangeDecoder.decodeBit(this.decoders, symbol);\n } while (symbol < 0x100);\n return symbol & 0xff;\n }\n\n decodeWithMatchByte(rangeDecoder: RangeDecoder, matchByte: number): number {\n let symbol = 1;\n do {\n const matchBit = (matchByte >> 7) & 1;\n matchByte <<= 1;\n const bit = rangeDecoder.decodeBit(this.decoders, ((1 + matchBit) << 8) + symbol);\n symbol = (symbol << 1) | bit;\n if (matchBit !== bit) {\n while (symbol < 0x100) {\n symbol = (symbol << 1) | rangeDecoder.decodeBit(this.decoders, symbol);\n }\n break;\n }\n } while (symbol < 0x100);\n return symbol & 0xff;\n }\n}\n\n/**\n * Literal decoder (array of single decoders)\n */\nclass LiteralDecoder {\n private numPosBits: number;\n private numPrevBits: number;\n private posMask: number;\n private coders: (LiteralDecoder2 | undefined)[];\n\n constructor() {\n this.numPosBits = 0;\n this.numPrevBits = 0;\n this.posMask = 0;\n this.coders = [];\n }\n\n create(numPosBits: number, numPrevBits: number): void {\n if (this.coders.length > 0 && this.numPrevBits === numPrevBits && this.numPosBits === numPosBits) {\n return;\n }\n this.numPosBits = numPosBits;\n this.posMask = (1 << numPosBits) - 1;\n this.numPrevBits = numPrevBits;\n this.coders = [];\n }\n\n init(): void {\n for (let i = 0; i < this.coders.length; i++) {\n if (this.coders[i]) {\n this.coders[i]?.init();\n }\n }\n }\n\n getDecoder(pos: number, prevByte: number): LiteralDecoder2 {\n const index = ((pos & this.posMask) << this.numPrevBits) + ((prevByte & 0xff) >>> (8 - this.numPrevBits));\n let decoder = this.coders[index];\n if (!decoder) {\n decoder = new LiteralDecoder2();\n this.coders[index] = decoder;\n }\n return decoder;\n }\n}\n\n/**\n * Output window (sliding dictionary)\n */\nclass OutWindow {\n private buffer: Buffer;\n private windowSize: number;\n private pos: number;\n private sink?: {\n write(buffer: Buffer): void;\n };\n private streamPos: number;\n\n constructor(sink?: OutputSink) {\n this.buffer = allocBufferUnsafe(0); // Replaced by create() before use\n this.windowSize = 0;\n this.pos = 0;\n this.sink = sink;\n this.streamPos = 0;\n }\n\n create(windowSize: number): void {\n if (!this.buffer || this.windowSize !== windowSize) {\n this.buffer = allocBufferUnsafe(windowSize);\n }\n this.windowSize = windowSize;\n this.pos = 0;\n this.streamPos = 0;\n }\n\n init(solid: boolean): void {\n if (!solid) {\n this.pos = 0;\n this.streamPos = 0;\n }\n }\n\n putByte(b: number): void {\n this.buffer[this.pos++] = b;\n if (this.pos >= this.windowSize) {\n if (this.sink) {\n this.flush();\n this.pos = 0;\n this.streamPos = 0; // Reset streamPos after wrap to track new data from pos 0\n } else {\n this.pos = 0;\n }\n }\n }\n\n flush(): void {\n const size = this.pos - this.streamPos;\n if (size > 0 && this.sink) {\n // Use bufferFrom to create a COPY, not a view - the buffer is reused after wrapping\n const chunk = bufferFrom(this.buffer.slice(this.streamPos, this.streamPos + size));\n this.sink.write(chunk);\n this.streamPos = this.pos;\n }\n }\n\n getByte(distance: number): number {\n let pos = this.pos - distance - 1;\n if (pos < 0) {\n pos += this.windowSize;\n }\n return this.buffer[pos];\n }\n\n copyBlock(distance: number, len: number): void {\n let pos = this.pos - distance - 1;\n if (pos < 0) {\n pos += this.windowSize;\n }\n for (let i = 0; i < len; i++) {\n if (pos >= this.windowSize) {\n pos = 0;\n }\n this.putByte(this.buffer[pos++]);\n }\n }\n\n /**\n * Copy decoded data to output buffer\n */\n copyTo(output: Buffer, outputOffset: number, count: number): void {\n const srcPos = this.pos - count;\n if (srcPos < 0) {\n // Wrap around case - data spans end and beginning of buffer\n const firstPart = -srcPos;\n this.buffer.copy(output, outputOffset, this.windowSize + srcPos, this.windowSize);\n this.buffer.copy(output, outputOffset + firstPart, 0, count - firstPart);\n } else {\n this.buffer.copy(output, outputOffset, srcPos, srcPos + count);\n }\n }\n}\n\n/**\n * Synchronous LZMA1 decoder\n */\nexport class LzmaDecoder {\n private outWindow: OutWindow;\n private rangeDecoder: RangeDecoder;\n\n // Probability models\n private isMatchDecoders: Uint16Array;\n private isRepDecoders: Uint16Array;\n private isRepG0Decoders: Uint16Array;\n private isRepG1Decoders: Uint16Array;\n private isRepG2Decoders: Uint16Array;\n private isRep0LongDecoders: Uint16Array;\n private posSlotDecoder: BitTreeDecoder[];\n private posDecoders: Uint16Array;\n private posAlignDecoder: BitTreeDecoder;\n private lenDecoder: LenDecoder;\n private repLenDecoder: LenDecoder;\n private literalDecoder: LiteralDecoder;\n\n // Properties\n private dictionarySize: number;\n private dictionarySizeCheck: number;\n private posStateMask: number;\n\n // State (preserved across solid calls)\n private state: number;\n private rep0: number;\n private rep1: number;\n private rep2: number;\n private rep3: number;\n private prevByte: number;\n private totalPos: number;\n\n constructor(outputSink?: OutputSink) {\n this.outWindow = new OutWindow(outputSink);\n this.rangeDecoder = new RangeDecoder();\n\n this.isMatchDecoders = initBitModels(null, kNumStates << kNumPosStatesBitsMax);\n this.isRepDecoders = initBitModels(null, kNumStates);\n this.isRepG0Decoders = initBitModels(null, kNumStates);\n this.isRepG1Decoders = initBitModels(null, kNumStates);\n this.isRepG2Decoders = initBitModels(null, kNumStates);\n this.isRep0LongDecoders = initBitModels(null, kNumStates << kNumPosStatesBitsMax);\n this.posSlotDecoder = [];\n this.posDecoders = initBitModels(null, kNumFullDistances - kEndPosModelIndex);\n this.posAlignDecoder = new BitTreeDecoder(kNumAlignBits);\n this.lenDecoder = new LenDecoder();\n this.repLenDecoder = new LenDecoder();\n this.literalDecoder = new LiteralDecoder();\n\n for (let i = 0; i < kNumLenToPosStates; i++) {\n this.posSlotDecoder[i] = new BitTreeDecoder(kNumPosSlotBits);\n }\n\n this.dictionarySize = -1;\n this.dictionarySizeCheck = -1;\n this.posStateMask = 0;\n\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n this.prevByte = 0;\n this.totalPos = 0;\n }\n\n /**\n * Set dictionary size\n */\n setDictionarySize(dictionarySize: number): boolean {\n if (dictionarySize < 0) return false;\n if (this.dictionarySize !== dictionarySize) {\n this.dictionarySize = dictionarySize;\n this.dictionarySizeCheck = Math.max(dictionarySize, 1);\n this.outWindow.create(Math.max(this.dictionarySizeCheck, 1 << 12));\n }\n return true;\n }\n\n /**\n * Set lc, lp, pb properties\n */\n setLcLpPb(lc: number, lp: number, pb: number): boolean {\n if (lc > kNumLitContextBitsMax || lp > 4 || pb > kNumPosStatesBitsMax) {\n return false;\n }\n const numPosStates = 1 << pb;\n this.literalDecoder.create(lp, lc);\n this.lenDecoder.create(numPosStates);\n this.repLenDecoder.create(numPosStates);\n this.posStateMask = numPosStates - 1;\n return true;\n }\n\n /**\n * Set decoder properties from 5-byte buffer\n */\n setDecoderProperties(properties: Buffer | Uint8Array): boolean {\n const props = parseProperties(properties);\n if (!this.setLcLpPb(props.lc, props.lp, props.pb)) return false;\n return this.setDictionarySize(props.dictionarySize);\n }\n\n /**\n * Initialize probability tables\n */\n private initProbabilities(): void {\n initBitModels(this.isMatchDecoders);\n initBitModels(this.isRepDecoders);\n initBitModels(this.isRepG0Decoders);\n initBitModels(this.isRepG1Decoders);\n initBitModels(this.isRepG2Decoders);\n initBitModels(this.isRep0LongDecoders);\n initBitModels(this.posDecoders);\n this.literalDecoder.init();\n for (let i = kNumLenToPosStates - 1; i >= 0; i--) {\n this.posSlotDecoder[i].init();\n }\n this.lenDecoder.init();\n this.repLenDecoder.init();\n this.posAlignDecoder.init();\n }\n\n /**\n * Reset probabilities only (for LZMA2 state reset)\n */\n resetProbabilities(): void {\n this.initProbabilities();\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n }\n\n /**\n * Reset dictionary position (for LZMA2 dictionary reset)\n */\n resetDictionary(): void {\n this.outWindow.init(false);\n this.totalPos = 0;\n }\n\n /**\n * Feed uncompressed data into the dictionary (for LZMA2 uncompressed chunks)\n * This updates the sliding window so subsequent LZMA chunks can reference this data.\n */\n feedUncompressed(data: Buffer): void {\n for (let i = 0; i < data.length; i++) {\n this.outWindow.putByte(data[i]);\n }\n this.totalPos += data.length;\n if (data.length > 0) {\n this.prevByte = data[data.length - 1];\n }\n }\n\n /**\n * Flush any remaining data in the OutWindow to the sink\n */\n flushOutWindow(): void {\n this.outWindow.flush();\n }\n\n /**\n * Decode LZMA data with streaming output (no buffer accumulation)\n * @param input - Compressed input buffer\n * @param inputOffset - Offset into input buffer\n * @param outSize - Expected output size\n * @param solid - If true, preserve state from previous decode\n * @returns Number of bytes written to sink\n */\n decodeWithSink(input: Buffer, inputOffset: number, outSize: number, solid = false): number {\n this.rangeDecoder.setInput(input, inputOffset);\n\n if (!solid) {\n this.outWindow.init(false);\n this.initProbabilities();\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n this.prevByte = 0;\n this.totalPos = 0;\n } else {\n this.outWindow.init(true);\n }\n\n let outPos = 0;\n let cumPos = this.totalPos;\n\n while (outPos < outSize) {\n const posState = cumPos & this.posStateMask;\n\n if (this.rangeDecoder.decodeBit(this.isMatchDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n // Literal\n const decoder2 = this.literalDecoder.getDecoder(cumPos, this.prevByte);\n if (!stateIsCharState(this.state)) {\n this.prevByte = decoder2.decodeWithMatchByte(this.rangeDecoder, this.outWindow.getByte(this.rep0));\n } else {\n this.prevByte = decoder2.decodeNormal(this.rangeDecoder);\n }\n this.outWindow.putByte(this.prevByte);\n outPos++;\n this.state = stateUpdateChar(this.state);\n cumPos++;\n } else {\n // Match or rep\n let len: number;\n\n if (this.rangeDecoder.decodeBit(this.isRepDecoders, this.state) === 1) {\n // Rep match\n len = 0;\n if (this.rangeDecoder.decodeBit(this.isRepG0Decoders, this.state) === 0) {\n if (this.rangeDecoder.decodeBit(this.isRep0LongDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n this.state = stateUpdateShortRep(this.state);\n len = 1;\n }\n } else {\n let distance: number;\n if (this.rangeDecoder.decodeBit(this.isRepG1Decoders, this.state) === 0) {\n distance = this.rep1;\n } else {\n if (this.rangeDecoder.decodeBit(this.isRepG2Decoders, this.state) === 0) {\n distance = this.rep2;\n } else {\n distance = this.rep3;\n this.rep3 = this.rep2;\n }\n this.rep2 = this.rep1;\n }\n this.rep1 = this.rep0;\n this.rep0 = distance;\n }\n if (len === 0) {\n len = kMatchMinLen + this.repLenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateRep(this.state);\n }\n } else {\n // Normal match\n this.rep3 = this.rep2;\n this.rep2 = this.rep1;\n this.rep1 = this.rep0;\n len = kMatchMinLen + this.lenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateMatch(this.state);\n\n const posSlot = this.posSlotDecoder[getLenToPosState(len)].decode(this.rangeDecoder);\n if (posSlot >= kStartPosModelIndex) {\n const numDirectBits = (posSlot >> 1) - 1;\n this.rep0 = (2 | (posSlot & 1)) << numDirectBits;\n if (posSlot < kEndPosModelIndex) {\n this.rep0 += reverseDecodeFromArray(this.posDecoders, this.rep0 - posSlot - 1, this.rangeDecoder, numDirectBits);\n } else {\n this.rep0 += this.rangeDecoder.decodeDirectBits(numDirectBits - kNumAlignBits) << kNumAlignBits;\n this.rep0 += this.posAlignDecoder.reverseDecode(this.rangeDecoder);\n if (this.rep0 < 0) {\n if (this.rep0 === -1) break;\n throw new Error('LZMA: Invalid distance');\n }\n }\n } else {\n this.rep0 = posSlot;\n }\n }\n\n if (this.rep0 >= cumPos || this.rep0 >= this.dictionarySizeCheck) {\n throw new Error('LZMA: Invalid distance');\n }\n\n // Copy match bytes\n for (let i = 0; i < len; i++) {\n const b = this.outWindow.getByte(this.rep0);\n this.outWindow.putByte(b);\n outPos++;\n }\n cumPos += len;\n this.prevByte = this.outWindow.getByte(0);\n }\n }\n\n this.totalPos = cumPos;\n return outPos;\n }\n\n /**\n * Decode LZMA data\n * @param input - Compressed input buffer\n * @param inputOffset - Offset into input buffer\n * @param outSize - Expected output size\n * @param solid - If true, preserve state from previous decode\n * @returns Decompressed data\n */\n decode(input: Buffer, inputOffset: number, outSize: number, solid = false): Buffer {\n this.rangeDecoder.setInput(input, inputOffset);\n\n if (!solid) {\n this.outWindow.init(false);\n this.initProbabilities();\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n this.prevByte = 0;\n this.totalPos = 0;\n } else {\n // Solid mode: preserve dictionary state but reinitialize range decoder\n this.outWindow.init(true);\n }\n\n const output = allocBufferUnsafe(outSize);\n let outPos = 0;\n let cumPos = this.totalPos;\n\n while (outPos < outSize) {\n const posState = cumPos & this.posStateMask;\n\n if (this.rangeDecoder.decodeBit(this.isMatchDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n // Literal\n const decoder2 = this.literalDecoder.getDecoder(cumPos, this.prevByte);\n if (!stateIsCharState(this.state)) {\n this.prevByte = decoder2.decodeWithMatchByte(this.rangeDecoder, this.outWindow.getByte(this.rep0));\n } else {\n this.prevByte = decoder2.decodeNormal(this.rangeDecoder);\n }\n this.outWindow.putByte(this.prevByte);\n output[outPos++] = this.prevByte;\n this.state = stateUpdateChar(this.state);\n cumPos++;\n } else {\n // Match or rep\n let len: number;\n\n if (this.rangeDecoder.decodeBit(this.isRepDecoders, this.state) === 1) {\n // Rep match\n len = 0;\n if (this.rangeDecoder.decodeBit(this.isRepG0Decoders, this.state) === 0) {\n if (this.rangeDecoder.decodeBit(this.isRep0LongDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n this.state = stateUpdateShortRep(this.state);\n len = 1;\n }\n } else {\n let distance: number;\n if (this.rangeDecoder.decodeBit(this.isRepG1Decoders, this.state) === 0) {\n distance = this.rep1;\n } else {\n if (this.rangeDecoder.decodeBit(this.isRepG2Decoders, this.state) === 0) {\n distance = this.rep2;\n } else {\n distance = this.rep3;\n this.rep3 = this.rep2;\n }\n this.rep2 = this.rep1;\n }\n this.rep1 = this.rep0;\n this.rep0 = distance;\n }\n if (len === 0) {\n len = kMatchMinLen + this.repLenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateRep(this.state);\n }\n } else {\n // Normal match\n this.rep3 = this.rep2;\n this.rep2 = this.rep1;\n this.rep1 = this.rep0;\n len = kMatchMinLen + this.lenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateMatch(this.state);\n\n const posSlot = this.posSlotDecoder[getLenToPosState(len)].decode(this.rangeDecoder);\n if (posSlot >= kStartPosModelIndex) {\n const numDirectBits = (posSlot >> 1) - 1;\n this.rep0 = (2 | (posSlot & 1)) << numDirectBits;\n if (posSlot < kEndPosModelIndex) {\n this.rep0 += reverseDecodeFromArray(this.posDecoders, this.rep0 - posSlot - 1, this.rangeDecoder, numDirectBits);\n } else {\n this.rep0 += this.rangeDecoder.decodeDirectBits(numDirectBits - kNumAlignBits) << kNumAlignBits;\n this.rep0 += this.posAlignDecoder.reverseDecode(this.rangeDecoder);\n if (this.rep0 < 0) {\n if (this.rep0 === -1) break; // End marker\n throw new Error('LZMA: Invalid distance');\n }\n }\n } else {\n this.rep0 = posSlot;\n }\n }\n\n if (this.rep0 >= cumPos || this.rep0 >= this.dictionarySizeCheck) {\n throw new Error('LZMA: Invalid distance');\n }\n\n // Copy match bytes\n for (let i = 0; i < len; i++) {\n const b = this.outWindow.getByte(this.rep0);\n this.outWindow.putByte(b);\n output[outPos++] = b;\n }\n cumPos += len;\n this.prevByte = this.outWindow.getByte(0);\n }\n }\n\n this.totalPos = cumPos;\n return output;\n }\n}\n\n/**\n * Decode LZMA1 data synchronously\n *\n * Note: LZMA1 is a low-level format. @napi-rs/lzma expects self-describing\n * data (like XZ), but here we accept raw LZMA with properties specified separately.\n * Pure JS implementation is used for LZMA1.\n *\n * @param input - Compressed data (without 5-byte properties header)\n * @param properties - 5-byte LZMA properties\n * @param outSize - Expected output size\n * @param outputSink - Optional output sink with write callback for streaming (returns bytes written)\n * @returns Decompressed data (or bytes written if outputSink provided)\n */\nexport function decodeLzma(input: Buffer, properties: Buffer | Uint8Array, outSize: number, outputSink?: { write(buffer: Buffer): void }): Buffer | number {\n const decoder = new LzmaDecoder(outputSink as OutputSink);\n decoder.setDecoderProperties(properties);\n if (outputSink) {\n // Zero-copy mode: write to sink during decode\n const bytesWritten = decoder.decodeWithSink(input, 0, outSize, false);\n decoder.flushOutWindow();\n return bytesWritten;\n }\n // Buffering mode: pre-allocated buffer, direct writes (zero-copy)\n return decoder.decode(input, 0, outSize, false);\n}\n"],"names":["allocBufferUnsafe","bufferFrom","getLenToPosState","initBitModels","kEndPosModelIndex","kMatchMinLen","kNumAlignBits","kNumFullDistances","kNumLenToPosStates","kNumLitContextBitsMax","kNumPosSlotBits","kNumPosStatesBitsMax","kNumStates","kStartPosModelIndex","parseProperties","stateIsCharState","stateUpdateChar","stateUpdateMatch","stateUpdateRep","stateUpdateShortRep","BitTreeDecoder","RangeDecoder","reverseDecodeFromArray","LenDecoder","create","numPosStates","lowCoder","midCoder","init","choice","i","highCoder","decode","rangeDecoder","posState","decodeBit","LiteralDecoder2","decoders","decodeNormal","symbol","decodeWithMatchByte","matchByte","matchBit","bit","LiteralDecoder","numPosBits","numPrevBits","coders","length","posMask","getDecoder","pos","prevByte","index","decoder","OutWindow","windowSize","buffer","streamPos","solid","putByte","b","sink","flush","size","chunk","slice","write","getByte","distance","copyBlock","len","copyTo","output","outputOffset","count","srcPos","firstPart","copy","LzmaDecoder","setDictionarySize","dictionarySize","dictionarySizeCheck","Math","max","outWindow","setLcLpPb","lc","lp","pb","literalDecoder","lenDecoder","repLenDecoder","posStateMask","setDecoderProperties","properties","props","initProbabilities","isMatchDecoders","isRepDecoders","isRepG0Decoders","isRepG1Decoders","isRepG2Decoders","isRep0LongDecoders","posDecoders","posSlotDecoder","posAlignDecoder","resetProbabilities","state","rep0","rep1","rep2","rep3","resetDictionary","totalPos","feedUncompressed","data","flushOutWindow","decodeWithSink","input","inputOffset","outSize","setInput","outPos","cumPos","decoder2","posSlot","numDirectBits","decodeDirectBits","reverseDecode","Error","outputSink","decodeLzma","bytesWritten"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,iBAAiB,EAAEC,UAAU,QAAQ,wBAAwB;AACtE,SACEC,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,iBAAiB,EACjBC,kBAAkB,EAClBC,qBAAqB,EACrBC,eAAe,EACfC,oBAAoB,EACpBC,UAAU,EACVC,mBAAmB,EAEnBC,eAAe,EACfC,gBAAgB,EAChBC,eAAe,EACfC,gBAAgB,EAChBC,cAAc,EACdC,mBAAmB,QACd,cAAc;AACrB,SAASC,cAAc,EAAEC,YAAY,EAAEC,sBAAsB,QAAQ,oBAAoB;AAEzF;;CAEC,GACD,IAAA,AAAMC,aAAN,MAAMA;IAeJC,OAAOC,YAAoB,EAAQ;QACjC,MAAO,IAAI,CAACA,YAAY,GAAGA,cAAc,IAAI,CAACA,YAAY,GAAI;YAC5D,IAAI,CAACC,QAAQ,CAAC,IAAI,CAACD,YAAY,CAAC,GAAG,IAAIL,eAAe;YACtD,IAAI,CAACO,QAAQ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;QACZ,IAAI,CAACC,IAAI,GAAG;QACZ,IAAI,CAAC5D,QAAQ,GAAG;QAChB,IAAI,CAAC8D,QAAQ,GAAG;IAClB;AAuVF;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASkB,WAAWb,KAAa,EAAExB,UAA+B,EAAE0B,OAAe,EAAEU,UAA4C;IACtI,MAAM7E,UAAU,IAAIyB,YAAYoD;IAChC7E,QAAQwC,oBAAoB,CAACC;IAC7B,IAAIoC,YAAY;QACd,8CAA8C;QAC9C,MAAME,eAAe/E,QAAQgE,cAAc,CAACC,OAAO,GAAGE,SAAS;QAC/DnE,QAAQ+D,cAAc;QACtB,OAAOgB;IACT;IACA,kEAAkE;IAClE,OAAO/E,QAAQtB,MAAM,CAACuF,OAAO,GAAGE,SAAS;AAC3C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/iterators/xz-compat/src/lzma/sync/LzmaDecoder.ts"],"sourcesContent":["/**\n * Synchronous LZMA1 Decoder\n *\n * Decodes LZMA1 compressed data from a buffer.\n * All operations are synchronous.\n */\n\nimport { allocBufferUnsafe, bufferFrom } from 'extract-base-iterator';\nimport {\n getLenToPosState,\n initBitModels,\n kEndPosModelIndex,\n kMatchMinLen,\n kNumAlignBits,\n kNumFullDistances,\n kNumLenToPosStates,\n kNumLitContextBitsMax,\n kNumPosSlotBits,\n kNumPosStatesBitsMax,\n kNumStates,\n kStartPosModelIndex,\n type OutputSink,\n parseProperties,\n stateIsCharState,\n stateUpdateChar,\n stateUpdateMatch,\n stateUpdateRep,\n stateUpdateShortRep,\n} from '../types.ts';\nimport { BitTreeDecoder, RangeDecoder, reverseDecodeFromArray } from './RangeDecoder.ts';\n\n/**\n * Length decoder for match/rep lengths\n */\nclass LenDecoder {\n private choice: Uint16Array;\n private lowCoder: BitTreeDecoder[];\n private midCoder: BitTreeDecoder[];\n private highCoder: BitTreeDecoder;\n private numPosStates: number;\n\n constructor() {\n this.choice = initBitModels(null, 2);\n this.lowCoder = [];\n this.midCoder = [];\n this.highCoder = new BitTreeDecoder(8);\n this.numPosStates = 0;\n }\n\n create(numPosStates: number): void {\n for (; this.numPosStates < numPosStates; this.numPosStates++) {\n this.lowCoder[this.numPosStates] = new BitTreeDecoder(3);\n this.midCoder[this.numPosStates] = new BitTreeDecoder(3);\n }\n }\n\n init(): void {\n initBitModels(this.choice);\n for (let i = this.numPosStates - 1; i >= 0; i--) {\n this.lowCoder[i].init();\n this.midCoder[i].init();\n }\n this.highCoder.init();\n }\n\n decode(rangeDecoder: RangeDecoder, posState: number): number {\n if (rangeDecoder.decodeBit(this.choice, 0) === 0) {\n return this.lowCoder[posState].decode(rangeDecoder);\n }\n if (rangeDecoder.decodeBit(this.choice, 1) === 0) {\n return 8 + this.midCoder[posState].decode(rangeDecoder);\n }\n return 16 + this.highCoder.decode(rangeDecoder);\n }\n}\n\n/**\n * Single literal decoder (decodes one byte)\n */\nclass LiteralDecoder2 {\n private decoders: Uint16Array;\n\n constructor() {\n this.decoders = initBitModels(null, 0x300);\n }\n\n init(): void {\n initBitModels(this.decoders);\n }\n\n decodeNormal(rangeDecoder: RangeDecoder): number {\n let symbol = 1;\n do {\n symbol = (symbol << 1) | rangeDecoder.decodeBit(this.decoders, symbol);\n } while (symbol < 0x100);\n return symbol & 0xff;\n }\n\n decodeWithMatchByte(rangeDecoder: RangeDecoder, matchByte: number): number {\n let symbol = 1;\n do {\n const matchBit = (matchByte >> 7) & 1;\n matchByte <<= 1;\n const bit = rangeDecoder.decodeBit(this.decoders, ((1 + matchBit) << 8) + symbol);\n symbol = (symbol << 1) | bit;\n if (matchBit !== bit) {\n while (symbol < 0x100) {\n symbol = (symbol << 1) | rangeDecoder.decodeBit(this.decoders, symbol);\n }\n break;\n }\n } while (symbol < 0x100);\n return symbol & 0xff;\n }\n}\n\n/**\n * Literal decoder (array of single decoders)\n */\nclass LiteralDecoder {\n private numPosBits: number;\n private numPrevBits: number;\n private posMask: number;\n private coders: (LiteralDecoder2 | undefined)[];\n\n constructor() {\n this.numPosBits = 0;\n this.numPrevBits = 0;\n this.posMask = 0;\n this.coders = [];\n }\n\n create(numPosBits: number, numPrevBits: number): void {\n if (this.coders.length > 0 && this.numPrevBits === numPrevBits && this.numPosBits === numPosBits) {\n return;\n }\n this.numPosBits = numPosBits;\n this.posMask = (1 << numPosBits) - 1;\n this.numPrevBits = numPrevBits;\n this.coders = [];\n }\n\n init(): void {\n for (let i = 0; i < this.coders.length; i++) {\n if (this.coders[i]) {\n this.coders[i]?.init();\n }\n }\n }\n\n getDecoder(pos: number, prevByte: number): LiteralDecoder2 {\n const index = ((pos & this.posMask) << this.numPrevBits) + ((prevByte & 0xff) >>> (8 - this.numPrevBits));\n let decoder = this.coders[index];\n if (!decoder) {\n decoder = new LiteralDecoder2();\n this.coders[index] = decoder;\n }\n return decoder;\n }\n}\n\n/**\n * Output window (sliding dictionary)\n */\nclass OutWindow {\n private buffer: Buffer;\n private windowSize: number;\n private pos: number;\n private sink?: {\n write(buffer: Buffer): void;\n };\n private streamPos: number;\n\n constructor(sink?: OutputSink) {\n this.buffer = allocBufferUnsafe(0); // Replaced by create() before use\n this.windowSize = 0;\n this.pos = 0;\n this.sink = sink;\n this.streamPos = 0;\n }\n\n create(windowSize: number): void {\n if (!this.buffer || this.windowSize !== windowSize) {\n this.buffer = allocBufferUnsafe(windowSize);\n }\n this.windowSize = windowSize;\n this.pos = 0;\n this.streamPos = 0;\n }\n\n init(solid: boolean): void {\n if (!solid) {\n this.pos = 0;\n this.streamPos = 0;\n }\n }\n\n putByte(b: number): void {\n this.buffer[this.pos++] = b;\n if (this.pos >= this.windowSize) {\n if (this.sink) {\n this.flush();\n this.pos = 0;\n this.streamPos = 0; // Reset streamPos after wrap to track new data from pos 0\n } else {\n this.pos = 0;\n }\n }\n }\n\n flush(): void {\n const size = this.pos - this.streamPos;\n if (size > 0 && this.sink) {\n // Use bufferFrom to create a COPY, not a view - the buffer is reused after wrapping\n const chunk = bufferFrom(this.buffer.slice(this.streamPos, this.streamPos + size));\n this.sink.write(chunk);\n this.streamPos = this.pos;\n }\n }\n\n getByte(distance: number): number {\n let pos = this.pos - distance - 1;\n if (pos < 0) {\n pos += this.windowSize;\n }\n return this.buffer[pos];\n }\n\n copyBlock(distance: number, len: number): void {\n let pos = this.pos - distance - 1;\n if (pos < 0) {\n pos += this.windowSize;\n }\n for (let i = 0; i < len; i++) {\n if (pos >= this.windowSize) {\n pos = 0;\n }\n this.putByte(this.buffer[pos++]);\n }\n }\n\n /**\n * Copy decoded data to output buffer\n */\n copyTo(output: Buffer, outputOffset: number, count: number): void {\n const srcPos = this.pos - count;\n if (srcPos < 0) {\n // Wrap around case - data spans end and beginning of buffer\n const firstPart = -srcPos;\n this.buffer.copy(output, outputOffset, this.windowSize + srcPos, this.windowSize);\n this.buffer.copy(output, outputOffset + firstPart, 0, count - firstPart);\n } else {\n this.buffer.copy(output, outputOffset, srcPos, srcPos + count);\n }\n }\n}\n\n/**\n * Synchronous LZMA1 decoder\n */\nexport class LzmaDecoder {\n private outWindow: OutWindow;\n private rangeDecoder: RangeDecoder;\n\n // Probability models\n private isMatchDecoders: Uint16Array;\n private isRepDecoders: Uint16Array;\n private isRepG0Decoders: Uint16Array;\n private isRepG1Decoders: Uint16Array;\n private isRepG2Decoders: Uint16Array;\n private isRep0LongDecoders: Uint16Array;\n private posSlotDecoder: BitTreeDecoder[];\n private posDecoders: Uint16Array;\n private posAlignDecoder: BitTreeDecoder;\n private lenDecoder: LenDecoder;\n private repLenDecoder: LenDecoder;\n private literalDecoder: LiteralDecoder;\n\n // Properties\n private dictionarySize: number;\n private dictionarySizeCheck: number;\n private posStateMask: number;\n\n // State (preserved across solid calls)\n private state: number;\n private rep0: number;\n private rep1: number;\n private rep2: number;\n private rep3: number;\n private prevByte: number;\n private totalPos: number;\n\n constructor(outputSink?: OutputSink) {\n this.outWindow = new OutWindow(outputSink);\n this.rangeDecoder = new RangeDecoder();\n\n this.isMatchDecoders = initBitModels(null, kNumStates << kNumPosStatesBitsMax);\n this.isRepDecoders = initBitModels(null, kNumStates);\n this.isRepG0Decoders = initBitModels(null, kNumStates);\n this.isRepG1Decoders = initBitModels(null, kNumStates);\n this.isRepG2Decoders = initBitModels(null, kNumStates);\n this.isRep0LongDecoders = initBitModels(null, kNumStates << kNumPosStatesBitsMax);\n this.posSlotDecoder = [];\n this.posDecoders = initBitModels(null, kNumFullDistances - kEndPosModelIndex);\n this.posAlignDecoder = new BitTreeDecoder(kNumAlignBits);\n this.lenDecoder = new LenDecoder();\n this.repLenDecoder = new LenDecoder();\n this.literalDecoder = new LiteralDecoder();\n\n for (let i = 0; i < kNumLenToPosStates; i++) {\n this.posSlotDecoder[i] = new BitTreeDecoder(kNumPosSlotBits);\n }\n\n this.dictionarySize = -1;\n this.dictionarySizeCheck = -1;\n this.posStateMask = 0;\n\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n this.prevByte = 0;\n this.totalPos = 0;\n }\n\n /**\n * Set dictionary size\n */\n setDictionarySize(dictionarySize: number): boolean {\n if (dictionarySize < 0) return false;\n if (this.dictionarySize !== dictionarySize) {\n this.dictionarySize = dictionarySize;\n this.dictionarySizeCheck = Math.max(dictionarySize, 1);\n this.outWindow.create(Math.max(this.dictionarySizeCheck, 1 << 12));\n }\n return true;\n }\n\n /**\n * Set lc, lp, pb properties\n */\n setLcLpPb(lc: number, lp: number, pb: number): boolean {\n if (lc > kNumLitContextBitsMax || lp > 4 || pb > kNumPosStatesBitsMax) {\n return false;\n }\n const numPosStates = 1 << pb;\n this.literalDecoder.create(lp, lc);\n this.lenDecoder.create(numPosStates);\n this.repLenDecoder.create(numPosStates);\n this.posStateMask = numPosStates - 1;\n return true;\n }\n\n /**\n * Set decoder properties from 5-byte buffer\n */\n setDecoderProperties(properties: Buffer | Uint8Array): boolean {\n const props = parseProperties(properties);\n if (!this.setLcLpPb(props.lc, props.lp, props.pb)) return false;\n return this.setDictionarySize(props.dictionarySize);\n }\n\n /**\n * Initialize probability tables\n */\n private initProbabilities(): void {\n initBitModels(this.isMatchDecoders);\n initBitModels(this.isRepDecoders);\n initBitModels(this.isRepG0Decoders);\n initBitModels(this.isRepG1Decoders);\n initBitModels(this.isRepG2Decoders);\n initBitModels(this.isRep0LongDecoders);\n initBitModels(this.posDecoders);\n this.literalDecoder.init();\n for (let i = kNumLenToPosStates - 1; i >= 0; i--) {\n this.posSlotDecoder[i].init();\n }\n this.lenDecoder.init();\n this.repLenDecoder.init();\n this.posAlignDecoder.init();\n }\n\n /**\n * Reset probabilities only (for LZMA2 state reset)\n */\n resetProbabilities(): void {\n this.initProbabilities();\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n }\n\n /**\n * Reset dictionary position (for LZMA2 dictionary reset)\n */\n resetDictionary(): void {\n this.outWindow.init(false);\n this.totalPos = 0;\n }\n\n /**\n * Feed uncompressed data into the dictionary (for LZMA2 uncompressed chunks)\n * This updates the sliding window so subsequent LZMA chunks can reference this data.\n */\n feedUncompressed(data: Buffer): void {\n for (let i = 0; i < data.length; i++) {\n this.outWindow.putByte(data[i]);\n }\n this.totalPos += data.length;\n if (data.length > 0) {\n this.prevByte = data[data.length - 1];\n }\n }\n\n /**\n * Flush any remaining data in the OutWindow to the sink\n */\n flushOutWindow(): void {\n this.outWindow.flush();\n }\n\n /**\n * Decode LZMA data with streaming output (no buffer accumulation)\n * @param input - Compressed input buffer\n * @param inputOffset - Offset into input buffer\n * @param outSize - Expected output size\n * @param solid - If true, preserve state from previous decode\n * @returns Number of bytes written to sink\n */\n decodeWithSink(input: Buffer, inputOffset: number, outSize: number, solid = false): number {\n this.rangeDecoder.setInput(input, inputOffset);\n\n if (!solid) {\n this.outWindow.init(false);\n this.initProbabilities();\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n this.prevByte = 0;\n this.totalPos = 0;\n } else {\n this.outWindow.init(true);\n }\n\n let outPos = 0;\n let cumPos = this.totalPos;\n\n while (outPos < outSize) {\n const posState = cumPos & this.posStateMask;\n\n if (this.rangeDecoder.decodeBit(this.isMatchDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n // Literal\n const decoder2 = this.literalDecoder.getDecoder(cumPos, this.prevByte);\n if (!stateIsCharState(this.state)) {\n this.prevByte = decoder2.decodeWithMatchByte(this.rangeDecoder, this.outWindow.getByte(this.rep0));\n } else {\n this.prevByte = decoder2.decodeNormal(this.rangeDecoder);\n }\n this.outWindow.putByte(this.prevByte);\n outPos++;\n this.state = stateUpdateChar(this.state);\n cumPos++;\n } else {\n // Match or rep\n let len: number;\n\n if (this.rangeDecoder.decodeBit(this.isRepDecoders, this.state) === 1) {\n // Rep match\n len = 0;\n if (this.rangeDecoder.decodeBit(this.isRepG0Decoders, this.state) === 0) {\n if (this.rangeDecoder.decodeBit(this.isRep0LongDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n this.state = stateUpdateShortRep(this.state);\n len = 1;\n }\n } else {\n let distance: number;\n if (this.rangeDecoder.decodeBit(this.isRepG1Decoders, this.state) === 0) {\n distance = this.rep1;\n } else {\n if (this.rangeDecoder.decodeBit(this.isRepG2Decoders, this.state) === 0) {\n distance = this.rep2;\n } else {\n distance = this.rep3;\n this.rep3 = this.rep2;\n }\n this.rep2 = this.rep1;\n }\n this.rep1 = this.rep0;\n this.rep0 = distance;\n }\n if (len === 0) {\n len = kMatchMinLen + this.repLenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateRep(this.state);\n }\n } else {\n // Normal match\n this.rep3 = this.rep2;\n this.rep2 = this.rep1;\n this.rep1 = this.rep0;\n len = kMatchMinLen + this.lenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateMatch(this.state);\n\n const posSlot = this.posSlotDecoder[getLenToPosState(len)].decode(this.rangeDecoder);\n if (posSlot >= kStartPosModelIndex) {\n const numDirectBits = (posSlot >> 1) - 1;\n this.rep0 = (2 | (posSlot & 1)) << numDirectBits;\n if (posSlot < kEndPosModelIndex) {\n this.rep0 += reverseDecodeFromArray(this.posDecoders, this.rep0 - posSlot - 1, this.rangeDecoder, numDirectBits);\n } else {\n this.rep0 += this.rangeDecoder.decodeDirectBits(numDirectBits - kNumAlignBits) << kNumAlignBits;\n this.rep0 += this.posAlignDecoder.reverseDecode(this.rangeDecoder);\n if (this.rep0 < 0) {\n if (this.rep0 === -1) break;\n throw new Error('LZMA: Invalid distance');\n }\n }\n } else {\n this.rep0 = posSlot;\n }\n }\n\n if (this.rep0 >= cumPos || this.rep0 >= this.dictionarySizeCheck) {\n throw new Error('LZMA: Invalid distance');\n }\n\n // Copy match bytes\n for (let i = 0; i < len; i++) {\n const b = this.outWindow.getByte(this.rep0);\n this.outWindow.putByte(b);\n outPos++;\n }\n cumPos += len;\n this.prevByte = this.outWindow.getByte(0);\n }\n }\n\n this.totalPos = cumPos;\n return outPos;\n }\n\n /**\n * Decode LZMA data directly into caller's buffer (zero-copy)\n * @param input - Compressed input buffer\n * @param inputOffset - Offset into input buffer\n * @param outSize - Expected output size\n * @param output - Pre-allocated output buffer to write to\n * @param outputOffset - Offset in output buffer to start writing\n * @param solid - If true, preserve state from previous decode\n * @returns Number of bytes written\n */\n decodeToBuffer(input: Buffer, inputOffset: number, outSize: number, output: Buffer, outputOffset: number, solid = false): number {\n this.rangeDecoder.setInput(input, inputOffset);\n\n if (!solid) {\n this.outWindow.init(false);\n this.initProbabilities();\n this.state = 0;\n this.rep0 = 0;\n this.rep1 = 0;\n this.rep2 = 0;\n this.rep3 = 0;\n this.prevByte = 0;\n this.totalPos = 0;\n } else {\n // Solid mode: preserve dictionary state but reinitialize range decoder\n this.outWindow.init(true);\n }\n\n let outPos = outputOffset;\n const outEnd = outputOffset + outSize;\n let cumPos = this.totalPos;\n\n while (outPos < outEnd) {\n const posState = cumPos & this.posStateMask;\n\n if (this.rangeDecoder.decodeBit(this.isMatchDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n // Literal\n const decoder2 = this.literalDecoder.getDecoder(cumPos, this.prevByte);\n if (!stateIsCharState(this.state)) {\n this.prevByte = decoder2.decodeWithMatchByte(this.rangeDecoder, this.outWindow.getByte(this.rep0));\n } else {\n this.prevByte = decoder2.decodeNormal(this.rangeDecoder);\n }\n this.outWindow.putByte(this.prevByte);\n output[outPos++] = this.prevByte;\n this.state = stateUpdateChar(this.state);\n cumPos++;\n } else {\n // Match or rep\n let len: number;\n\n if (this.rangeDecoder.decodeBit(this.isRepDecoders, this.state) === 1) {\n // Rep match\n len = 0;\n if (this.rangeDecoder.decodeBit(this.isRepG0Decoders, this.state) === 0) {\n if (this.rangeDecoder.decodeBit(this.isRep0LongDecoders, (this.state << kNumPosStatesBitsMax) + posState) === 0) {\n this.state = stateUpdateShortRep(this.state);\n len = 1;\n }\n } else {\n let distance: number;\n if (this.rangeDecoder.decodeBit(this.isRepG1Decoders, this.state) === 0) {\n distance = this.rep1;\n } else {\n if (this.rangeDecoder.decodeBit(this.isRepG2Decoders, this.state) === 0) {\n distance = this.rep2;\n } else {\n distance = this.rep3;\n this.rep3 = this.rep2;\n }\n this.rep2 = this.rep1;\n }\n this.rep1 = this.rep0;\n this.rep0 = distance;\n }\n if (len === 0) {\n len = kMatchMinLen + this.repLenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateRep(this.state);\n }\n } else {\n // Normal match\n this.rep3 = this.rep2;\n this.rep2 = this.rep1;\n this.rep1 = this.rep0;\n len = kMatchMinLen + this.lenDecoder.decode(this.rangeDecoder, posState);\n this.state = stateUpdateMatch(this.state);\n\n const posSlot = this.posSlotDecoder[getLenToPosState(len)].decode(this.rangeDecoder);\n if (posSlot >= kStartPosModelIndex) {\n const numDirectBits = (posSlot >> 1) - 1;\n this.rep0 = (2 | (posSlot & 1)) << numDirectBits;\n if (posSlot < kEndPosModelIndex) {\n this.rep0 += reverseDecodeFromArray(this.posDecoders, this.rep0 - posSlot - 1, this.rangeDecoder, numDirectBits);\n } else {\n this.rep0 += this.rangeDecoder.decodeDirectBits(numDirectBits - kNumAlignBits) << kNumAlignBits;\n this.rep0 += this.posAlignDecoder.reverseDecode(this.rangeDecoder);\n if (this.rep0 < 0) {\n if (this.rep0 === -1) break; // End marker\n throw new Error('LZMA: Invalid distance');\n }\n }\n } else {\n this.rep0 = posSlot;\n }\n }\n\n if (this.rep0 >= cumPos || this.rep0 >= this.dictionarySizeCheck) {\n throw new Error('LZMA: Invalid distance');\n }\n\n // Copy match bytes\n for (let i = 0; i < len; i++) {\n const b = this.outWindow.getByte(this.rep0);\n this.outWindow.putByte(b);\n output[outPos++] = b;\n }\n cumPos += len;\n this.prevByte = this.outWindow.getByte(0);\n }\n }\n\n this.totalPos = cumPos;\n return outPos - outputOffset;\n }\n\n /**\n * Decode LZMA data\n * @param input - Compressed input buffer\n * @param inputOffset - Offset into input buffer\n * @param outSize - Expected output size\n * @param solid - If true, preserve state from previous decode\n * @returns Decompressed data\n */\n decode(input: Buffer, inputOffset: number, outSize: number, solid = false): Buffer {\n const output = allocBufferUnsafe(outSize);\n this.decodeToBuffer(input, inputOffset, outSize, output, 0, solid);\n return output;\n }\n}\n\n/**\n * Decode LZMA1 data synchronously\n *\n * Note: LZMA1 is a low-level format. @napi-rs/lzma expects self-describing\n * data (like XZ), but here we accept raw LZMA with properties specified separately.\n * Pure JS implementation is used for LZMA1.\n *\n * @param input - Compressed data (without 5-byte properties header)\n * @param properties - 5-byte LZMA properties\n * @param outSize - Expected output size\n * @param outputSink - Optional output sink with write callback for streaming (returns bytes written)\n * @returns Decompressed data (or bytes written if outputSink provided)\n */\nexport function decodeLzma(input: Buffer, properties: Buffer | Uint8Array, outSize: number, outputSink?: { write(buffer: Buffer): void }): Buffer | number {\n const decoder = new LzmaDecoder(outputSink as OutputSink);\n decoder.setDecoderProperties(properties);\n if (outputSink) {\n // Zero-copy mode: write to sink during decode\n const bytesWritten = decoder.decodeWithSink(input, 0, outSize, false);\n decoder.flushOutWindow();\n return bytesWritten;\n }\n // Buffering mode: pre-allocated buffer, direct writes (zero-copy)\n return decoder.decode(input, 0, outSize, false);\n}\n"],"names":["allocBufferUnsafe","bufferFrom","getLenToPosState","initBitModels","kEndPosModelIndex","kMatchMinLen","kNumAlignBits","kNumFullDistances","kNumLenToPosStates","kNumLitContextBitsMax","kNumPosSlotBits","kNumPosStatesBitsMax","kNumStates","kStartPosModelIndex","parseProperties","stateIsCharState","stateUpdateChar","stateUpdateMatch","stateUpdateRep","stateUpdateShortRep","BitTreeDecoder","RangeDecoder","reverseDecodeFromArray","LenDecoder","create","numPosStates","lowCoder","midCoder","init","choice","i","highCoder","decode","rangeDecoder","posState","decodeBit","LiteralDecoder2","decoders","decodeNormal","symbol","decodeWithMatchByte","matchByte","matchBit","bit","LiteralDecoder","numPosBits","numPrevBits","coders","length","posMask","getDecoder","pos","prevByte","index","decoder","OutWindow","windowSize","buffer","streamPos","solid","putByte","b","sink","flush","size","chunk","slice","write","getByte","distance","copyBlock","len","copyTo","output","outputOffset","count","srcPos","firstPart","copy","LzmaDecoder","setDictionarySize","dictionarySize","dictionarySizeCheck","Math","max","outWindow","setLcLpPb","lc","lp","pb","literalDecoder","lenDecoder","repLenDecoder","posStateMask","setDecoderProperties","properties","props","initProbabilities","isMatchDecoders","isRepDecoders","isRepG0Decoders","isRepG1Decoders","isRepG2Decoders","isRep0LongDecoders","posDecoders","posSlotDecoder","posAlignDecoder","resetProbabilities","state","rep0","rep1","rep2","rep3","resetDictionary","totalPos","feedUncompressed","data","flushOutWindow","decodeWithSink","input","inputOffset","outSize","setInput","outPos","cumPos","decoder2","posSlot","numDirectBits","decodeDirectBits","reverseDecode","Error","decodeToBuffer","outEnd","outputSink","decodeLzma","bytesWritten"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,iBAAiB,EAAEC,UAAU,QAAQ,wBAAwB;AACtE,SACEC,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,iBAAiB,EACj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}
@@ -301,6 +301,50 @@ const FILTER_LZMA2 = 0x21;
301
301
  }
302
302
  return Buffer.concat(outputChunks);
303
303
  }
304
+ /**
305
+ * Parse XZ stream to get block information (without decompressing)
306
+ * This allows streaming decompression by processing blocks one at a time.
307
+ */ function parseXZIndex(input) {
308
+ var _checkSizes_checkType;
309
+ // Stream header validation
310
+ if (input.length < 12) {
311
+ throw new Error('XZ file too small');
312
+ }
313
+ // Stream magic bytes (0xFD, '7zXZ', 0x00)
314
+ if (input[0] !== 0xfd || input[1] !== 0x37 || input[2] !== 0x7a || input[3] !== 0x58 || input[4] !== 0x5a || input[5] !== 0x00) {
315
+ throw new Error('Invalid XZ magic bytes');
316
+ }
317
+ // Stream flags at offset 6-7
318
+ const checkType = input[7] & 0x0f;
319
+ // Check sizes based on check type
320
+ const checkSizes = {
321
+ 0: 0,
322
+ 1: 4,
323
+ 4: 8,
324
+ 10: 32
325
+ };
326
+ const checkSize = (_checkSizes_checkType = checkSizes[checkType]) !== null && _checkSizes_checkType !== void 0 ? _checkSizes_checkType : 0;
327
+ // Find footer by skipping stream padding
328
+ let footerEnd = input.length;
329
+ while(footerEnd > 12 && input[footerEnd - 1] === 0x00){
330
+ footerEnd--;
331
+ }
332
+ while(footerEnd % 4 !== 0 && footerEnd > 12){
333
+ footerEnd++;
334
+ }
335
+ // Verify footer magic
336
+ if (!bufferEquals(input, footerEnd - 2, XZ_FOOTER_MAGIC)) {
337
+ throw new Error('Invalid XZ footer magic');
338
+ }
339
+ // Get backward size
340
+ const backwardSize = (input.readUInt32LE(footerEnd - 8) + 1) * 4;
341
+ const indexStart = footerEnd - 12 - backwardSize;
342
+ // Parse Index to get block information
343
+ return parseIndex(input, indexStart, checkSize).map((record)=>({
344
+ ...record,
345
+ checkSize
346
+ }));
347
+ }
304
348
  /**
305
349
  * Create an XZ decompression Transform stream
306
350
  * @returns Transform stream that decompresses XZ data
@@ -314,8 +358,26 @@ const FILTER_LZMA2 = 0x21;
314
358
  flush (callback) {
315
359
  try {
316
360
  const input = Buffer.concat(chunks);
317
- const output = decodeXZ(input);
318
- this.push(output);
361
+ // Stream decode each block instead of buffering all output
362
+ const blockRecords = parseXZIndex(input);
363
+ for(let i = 0; i < blockRecords.length; i++){
364
+ const record = blockRecords[i];
365
+ const recordStart = record.compressedPos;
366
+ // Parse block header
367
+ const blockInfo = parseBlockHeader(input, recordStart, blockRecords[i].checkSize);
368
+ // Extract compressed data for this block
369
+ const dataStart = recordStart + blockInfo.headerSize;
370
+ const dataEnd = dataStart + record.compressedDataSize;
371
+ const compressedData = input.slice(dataStart, dataEnd);
372
+ // Decompress this block
373
+ let blockOutput = decodeLzma2(compressedData, blockInfo.lzma2Props, record.uncompressedSize);
374
+ // Apply preprocessing filters in reverse order
375
+ for(let j = blockInfo.filters.length - 1; j >= 0; j--){
376
+ blockOutput = applyFilter(blockOutput, blockInfo.filters[j]);
377
+ }
378
+ // Push block output immediately instead of buffering
379
+ this.push(blockOutput);
380
+ }
319
381
  callback();
320
382
  } catch (err) {
321
383
  callback(err);