{"_id":"@tokenizer/inflate@0.6.0","bugs":{"url":"hhttps://github.com/Borewit/tokenizer-inflate/issues"},"dist":{"shasum":"e249321793cb6c4e5fd58b8fc79cb23465f3d0c5","tarball":"http://registry-npm.ywwl.com/@tokenizer/inflate/download/@tokenizer/inflate-0.6.0.tgz","fileCount":13,"integrity":"sha512-+0RDxhBkyT9xMnGdJAwmats9yxRLR8ypJrQgrnLqOu4Gv/aHlnxYgdGVy2QTwvBl6IF/w2Hr+ZNirH+iMUbVZA==","signatures":[{"sig":"MEUCIQCOBZovx0odC0AA6JektaPiXpSNDNIIt5dYX1N5MXHZUwIgKXmbr5jntjX6kHVSOxRF4ltG9yKWqaxXEbImjKi7vpI=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDS0nmQo4yXClNL+vfQxQ/R8oQ6gxbm8TwmAFTwahNfpQIhAOMJLMmO5WbTVTSnP4dvYnnBP+5qvwnKIgjG6nObcVys"}],"unpackedSize":42877,"size":11430,"noattachment":false,"key":"/@tokenizer/inflate/-/@tokenizer/inflate-0.6.0.tgz"},"name":"@tokenizer/inflate","type":"module","author":{"url":"https://github.com/Borewit","name":"Borewit"},"engines":{"node":">=18"},"exports":"./lib/index.js","funding":{"url":"https://github.com/sponsors/Borewit","type":"github"},"gitHead":"516fe05820d9214747133def065f4dad2a27ab49","license":"MIT","scripts":{"fix":"yarn run lint:ts:fix","test":"mocha","build":"yarn run clean && yarn run compile","clean":"del-cli 'lib/**/*.js' 'lib/**/*.js.map' 'lib/**/*.d.ts' 'test/**/*.js' 'test/**/*.js.map'","start":"yarn run compile && yarn run lint && yarn run cover-test","eslint":"eslint lib test","compile":"yarn run compile-src && yarn run compile-test","lint:md":"remark -u preset-lint-recommended .","lint:ts":"biome check","compile-src":"tsc -p lib","lint:ts:fix":"biome check --write","compile-test":"tsc -p test","update-biome":"yarn add -D --exact @biomejs/biome && npx @biomejs/biome migrate --write","prepublishOnly":"yarn run build"},"version":"0.6.0","_npmUser":{"name":"borewit","email":"borewit@xs4all.nl"},"homepage":"https://github.com/Borewit/tokenizer-inflate#readme","keywords":["zip","unzip","decompress","inflate","strtok3","tokenizer","stream","S3"],"repository":{"url":"git+https://github.com/Borewit/tokenizer-inflate.git","type":"git"},"_npmVersion":"10.9.9","description":"Tokenized zip support","directories":{},"maintainers":[{"name":"borewit","email":"borewit@xs4all.nl"}],"_nodeVersion":"22.23.3","dependencies":{"debug":"^4.4.3","strtok3":"^10.6.2","token-types":"^6.1.2"},"_hasShrinkwrap":false,"packageManager":"yarn@4.18.1","devDependencies":{"tsx":"^4.23.15","chai":"^6.3.0","mocha":"^12.0.3","del-cli":"^8.0.1","file-type":"^22.2.0","typescript":"^7.0.2","@types/chai":"^5.2.3","@types/node":"^26.6.5","@types/debug":"^4","@types/mocha":"^10.0.10","@tokenizer/s3":"^1.0.4","@biomejs/biome":"2.5.15","@aws-sdk/client-s3":"^3.1152.0"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/inflate_0.6.0_1792839272103_0.1049837996719849"},"readme":"[![Node.js CI](https://github.com/Borewit/tokenizer-inflate/actions/workflows/nodejs-ci.yml/badge.svg)](https://github.com/Borewit/tokenizer-inflate/actions/workflows/nodejs-ci.yml)\n[![NPM version](https://badge.fury.io/js/%40tokenizer%2Finflate.svg)](https://npmjs.org/package/@tokenizer/inflate)\n[![npm downloads](https://img.shields.io/npm/dm/@tokenizer%2Finflate.svg)](https://npmcharts.com/compare/%40tokenizer%2Finflate?start=1200&interval=30)\n\n# @tokenizer/inflate\n\n`@tokenizer/inflate` is a package designed for handling and extracting data from ZIP files efficiently using a tokenizer-based approach.\nThe library provides a customizable way to parse ZIP archives and extract compressed data while minimizing memory usage.\n\n## Features\n- Efficient Decompression: Handles streams compressed with DEFLATE and related formats (e.g., gzip).\n- Tokenizer Compatibility: Seamlessly integrates with [strtok3](https://github.com/Borewit/strtok3). For example, use  [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3) for efficient partial extraction of a Zip stored on AWS S3 cloud file storage.\n- Streamlined Interface: Provides an intuitive API for working with compressed data in streaming and random-access scenarios.\n- Chunked Data Access: Leverages the underlying media's capabilities to offer chunked or random access to data, unlike traditional streams.\n- Plug-and-Play: Easily integrate with existing tokenizer-based workflows for parsing file metadata or binary structures.\n- Interrupt the extraction process conditionally.\n\n## Installation\n```bash\nnpm install @tokenizer/inflate\n```\n\n## Usage\n\n### Example: Extracting Specific Files\n\nThe following example demonstrates how to use the library to extract .txt files and stop processing when encountering a .stop file.\n\n```js\nimport { ZipHandler } from '@tokenizer/inflate';\nimport { fromFile } from 'strtok3';\n\nconst fileFilter = (file) => {\n  console.log(`Processing file: ${file.filename}`);\n\n  if (file.filename?.endsWith(\".stop\")) {\n    console.log(`Stopping processing due to file: ${file.filename}`);\n    return { handler: false, stop: true }; // Stop the unzip process\n  }\n\n  if (file.filename?.endsWith(\".txt\")) {\n    return {\n      handler: async (data) => {\n        console.log(`Extracted text file: ${file.filename}`);\n        console.log(new TextDecoder().decode(data));\n      },\n    };\n  }\n\n  return { handler: false }; // Ignore other files\n};\n\nasync function extractFiles(zipFilePath) {\n  const tokenizer = await fromFile(zipFilePath);\n  try {\n    const zipHandler = new ZipHandler(tokenizer);\n    await zipHandler.unzip(fileFilter);\n  } finally {\n    await tokenizer.close();\n  }\n}\n\nextractFiles('example.zip').catch(console.error);\n```\n\n## API\n\n### `ZipHandler`\nA class for handling ZIP file parsing and extraction.\n#### Constructor\n```ts\nnew ZipHandler(tokenizer: ITokenizer, options?: ZipHandlerOptions)\n```\n- **tokenizer**: An instance of ITokenizer to read the ZIP archive.\n- **options**: Optional processing limits and traversal settings. Each numeric limit accepts a positive safe integer or `Infinity`.\n  Omitted limits default to `Infinity`, preserving unlimited processing.\n\n```ts\nconst zipHandler = new ZipHandler(tokenizer, {\n  maxEntryCount: 1024,\n  maxTotalScanBytes: 16 * 1024 * 1024,\n  maxTotalDataDescriptorScanBytes: 1024 * 1024,\n  maxSkippedEntrySize: 1024 * 1024,\n  maxDataDescriptorScanBytes: 1024 * 1024,\n  maxCompressedSize: 1024 * 1024,\n  maxUncompressedSize: 4 * 1024 * 1024\n});\n```\n\n`maxDataDescriptorScanBytes` bounds bytes before the descriptor signature when the compressed\nsize is unknown, even for ignored entries. Descriptor candidates are checked against their\ncompressed-size field so an embedded signature with a different size does not end the scan.\nLookahead uses up to 16 additional bytes to validate a candidate descriptor.\n`maxCompressedSize` bounds compressed data buffered for selected entries, and\n`maxUncompressedSize` bounds their decompressed output, including stored entries.\nLimits apply to local-header and central-directory sizes before allocation, and to actual\noutput before retaining chunks or combining buffers. Decompression is canceled on overflow.\n`maxEntryCount` bounds entries visited, including ignored entries. `maxTotalScanBytes` bounds\nmetadata and compressed data consumed across one traversal, including ignored local-header\npayloads. Random-access seek distances are excluded; the end-of-directory search and record\nare included, and bytes read again during extraction count again. Ignored central-directory\npayloads are not read or counted. `maxTotalDataDescriptorScanBytes` bounds cumulative payload\nbytes scanned for unknown-size entries, excluding their descriptors. `maxSkippedEntrySize`\nbounds a single ignored payload when local-header traversal must pass over it.\nCounters reset for each `unzip()` or `readCentralDirectory()` call.\n\nThese limits are not a total process memory budget; tokenizer lookahead and native\ndecompression have their own buffers. Configure tokenizer limits separately where available.\n\nA limit violation throws the exported `ZipLimitError` (a `RangeError`), with `limit`,\n`requestedSize`, and `maxSize` properties. Sizes are byte counts except for `maxEntryCount`.\nNo data handler is called for an entry rejected by a limit; earlier handlers may already have run.\nInvalid numeric limit options throw `RangeError` when constructing the handler. Invalid\nnon-boolean values for `useCentralDirectory` or `allowTruncatedDataDescriptor` throw `TypeError`\nduring construction. After a processing failure, close the tokenizer; extraction is not resumable.\n\nFor random-access sources, central-directory entries are parsed within the directory's declared\nbyte range using a borrowed tokenizer view. An entry crossing that range throws\n`strtok3.TokenizerBoundaryError`. Reading the directory restores the source position on both\nsuccess and failure, and leaves the source open. `unzip()` processes directory entries one at a\ntime and stops parsing when the callback returns `stop: true`, restoring the original source\nposition on completion or failure. `readCentralDirectory()` still explicitly collects an array.\n\nSet `useCentralDirectory: false` to scan local headers even on random-access sources. This is\nuseful for detectors that need consistent local-header ordering and support partial archives.\nIt does not disable entry or byte limits.\n\n`allowTruncatedDataDescriptor: true` lets a detector receive the available entry data when a\ndescriptor is missing or truncated at EOF. Extraction still rejects the incomplete descriptor\nafter the handler returns; the caller can retain a detection result. All configured limits\nstill apply. The default is `false`, which rejects incomplete descriptors before delivering data.\n\n#### Methods\n \n- `isZip(): Promise<boolean>`\n\n   Determines whether the input file is a ZIP archive.\n\n- `unzip(fileCb: InflateFileFilter): Promise<void>`\n\n  Extracts files from the ZIP archive, applying the provided [InflateFileFilter](#inflatefilefilter) callback to each file.\n  To extract a file, return an object whose `handler` is an [InflatedDataHandler](#inflateddatahandler).\n  Return `{ handler: false }` to skip the file.\n\n## Types\n\n### `InflateFileFilter`\n```ts\ntype InflateFileFilter = (file: ILocalFileHeader) => InflateFileFilterResult;\n```\nCallback function that receives the ZIP entry header and returns an [InflateFileFilterResult](#inflatefilefilterresult) to select or skip the entry.\n\n### `InflateFileFilterResult`\n```ts\ntype InflateFileFilterResult = {\n  handler: InflatedDataHandler | false; // Handle file data or ignore\n  stop?: boolean; // Stop processing further files\n};\n```\nReturned from [InflateFileFilter](#inflatefilefilter) to control file handling and extraction flow.\nSet `handler` to an [InflatedDataHandler](#inflateddatahandler) to receive the entry data, or `false` to skip it.\nSet `stop: true` to stop after the current entry has been handled or skipped.\n\n### `InflatedDataHandler`\n```ts\ntype InflatedDataHandler = (fileData: Uint8Array) => Promise<void>;\n```\nAsynchronous callback assigned to `InflateFileFilterResult.handler` for a selected entry.\nIt receives the complete uncompressed entry data as a `Uint8Array`, including for stored (uncompressed) entries.\nExtraction awaits the returned promise before processing the next entry.\n\n## Compatibility\n\nThis module is a [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).\nThe distributed JavaScript codebase is compliant with the [ECMAScript 2020 (11th Edition)](https://en.wikipedia.org/wiki/ECMAScript_version_history#11th_Edition_%E2%80%93_ECMAScript_2020) standard.\nIf used with Node.js, it requires version ≥ 18.\n\n## Contributing\n\nSee the [contribution guide](CONTRIBUTING.md) for code style and development checks.\n\n## License\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n","publish_time":1792839272200,"_cnpm_publish_time":1792839272200,"dist-tags":{"latest":"0.6.0"}}