2.9 KiB
2.9 KiB
compression API (compressData / decompressData)
(no submodules)
Purpose
compressData and decompressData are the primary public surface of @suaveplan/bitpacker-compressed. They are algorithm-by-name helpers that route through a CompressionRegistry (defaulting to the process-wide singleton) so callers can switch between "gzip", "deflate", "none", and any custom registered adapter without touching adapter classes directly. They are the layer that hot-path consumers like CompressedBitPacker use; it is also the layer that wraps codec failures in BitpackerError codes so application code never has to handle a raw DOMException or platform-specific stream error.
Features
- Algorithm-by-name routing through a pluggable
CompressionRegistry. - Coded errors: unknown algorithm →
UNKNOWN_COMPRESSION_ALGORITHM, codec failure →COMPRESSION_FAILED/DECOMPRESSION_FAILEDwith the underlying error chained. - Optional registry parameter — pass a custom
CompressionRegistryfor isolation in tests. - Symmetric:
compressData(data, "gzip")round-trips throughdecompressData(bytes, "gzip").
Usage: Basic Example
import { compressData, decompressData } from "@suaveplan/bitpacker-compressed";
const data = new TextEncoder().encode("hello world".repeat(100));
const compressed = await compressData(data, "gzip");
const restored = await decompressData(compressed, "gzip");
Usage: Advanced Example
import {
compressData,
createCompressionRegistry,
} from "@suaveplan/bitpacker-compressed";
// Test isolation: create a fresh registry that ONLY has the "none" adapter
// registered, then prove the unknown-algorithm path throws coded errors.
const registry = createCompressionRegistry({ withDefaults: false });
try {
await compressData(data, "gzip", { registry });
} catch (err) {
// BitpackerError with code BITPACKER.UNKNOWN_COMPRESSION_ALGORITHM
}
API Reference
compressData(data, algorithm, options?): Promise<Uint8Array>
data: Uint8Array— bytes to compress.algorithm: string— registry key (e.g."gzip","deflate","none").options?: { registry?, level? }—registryoverrides the default singleton;levelis forwarded to the adapter.- Throws:
BitpackerError(UNKNOWN_COMPRESSION_ALGORITHM)orBitpackerError(COMPRESSION_FAILED, { cause }).
decompressData(data, algorithm, options?): Promise<Uint8Array>
- Inverse of
compressData. ThrowsBitpackerError(DECOMPRESSION_FAILED, { cause })on codec failure.
Implementation Notes
- The default singleton is initialized lazily; it registers
"none","gzip","deflate"only if the host supportsCompressionStream. - Adapters are async because
CompressionStreamis async;NoCompressionAdapterreturns immediately. - Hot-path callers should resolve the adapter once and call it directly to avoid the per-call registry lookup.