{"_id":"strtok3@10.5.0","bugs":{"url":"https://github.com/Borewit/strtok3/issues"},"dist":{"shasum":"fcc4387817fb2f0a12ee03ae1c3c54490fd180c6","tarball":"http://registry-npm.ywwl.com/strtok3/download/strtok3-10.5.0.tgz","fileCount":43,"integrity":"sha512-PgAsgIuizbZN/r4+g4UNvbVCTpJWdoIdI71kIWwKmdIH0vJ0q7ylMVGU8PWj2s9O98y4MtFWiDTIrtNukZMMgQ==","signatures":[{"sig":"MEQCIGMM3lXPVB34VoCbJhuS99hhJLJvpEGOzldoxhcyiUNtAiBNfAOLt3H1kmK7eejDD9QNPHn4k/EZe1XUF50U5IdBMg==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIDc0ZNzPvHXWSWo+ujzQNCiiM2eMFusNHnwty8KzGexnAiA+89z458LDH0QEkAvu6Qpud8PDfpkgr45g54ZJ9HRVIg=="}],"unpackedSize":94014,"size":20796,"noattachment":false,"key":"/strtok3/-/strtok3-10.5.0.tgz"},"name":"strtok3","type":"module","types":"lib/index.d.ts","author":{"url":"https://github.com/Borewit","name":"Borewit"},"engines":{"node":">=18"},"exports":{".":{"node":"./lib/index.js","default":"./lib/core.js"},"./core":"./lib/core.js"},"funding":{"url":"https://github.com/sponsors/Borewit","type":"github"},"gitHead":"7ea99b99f932c51cdc132b7f675d48289ff12c46","license":"MIT","scripts":{"fix":"yarn run lint:ts:fix","lint":"yarn run lint:md && yarn run lint:ts","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","bun:test":"bun run --bun test","compile-src":"tsc -p lib  --sourceMap false","lint:ts:fix":"biome check --write","send-codacy":"c8 report --reporter=text-lcov | codacy-coverage","compile-test":"tsc -p test","update-biome":"yarn add -D --exact @biomejs/biome && npx @biomejs/biome migrate --write","test-coverage":"c8 yarn run test","prepublishOnly":"yarn run build"},"version":"10.5.0","_npmUser":{"name":"borewit","email":"borewit@xs4all.nl"},"homepage":"https://github.com/Borewit/strtok3#readme","keywords":["tokenizer","reader","token","async","promise","parser","decoder","binary","endian","uint","stream","streaming"],"repository":{"url":"git+https://github.com/Borewit/strtok3.git","type":"git"},"_npmVersion":"10.9.9","description":"A promise based streaming tokenizer","directories":{},"maintainers":[{"name":"borewit","email":"borewit@xs4all.nl"}],"_nodeVersion":"22.23.3","dependencies":{"@tokenizer/token":"^0.3.0"},"_hasShrinkwrap":false,"packageManager":"yarn@4.18.1","devDependencies":{"c8":"^12.0.0","tsx":"^4.23.15","chai":"^6.3.0","mocha":"^11","del-cli":"^7.0.0","remark-cli":"^12.0.1","typescript":"^7.0.2","@types/chai":"^5.2.2","@types/node":"^24.19.1","token-types":"^6.1.2","@types/debug":"^4.1.12","@types/mocha":"^10.0.10","@biomejs/biome":"2.5.15","chai-as-promised":"^8.0.2","uint8array-extras":"^1.6.0","@types/chai-as-promised":"^8.0.2","remark-preset-lint-recommended":"^7.0.1","node-readable-to-web-readable-stream":"^0.4.2"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/strtok3_10.5.0_1791907086430_0.023210426620090097"},"readme":"[![Node.js CI](https://github.com/Borewit/strtok3/actions/workflows/ci.yml/badge.svg)](https://github.com/Borewit/strtok3/actions/workflows/ci.yml)\n[![CodeQL](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml/badge.svg?branch=master)](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml)\n[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3)\n[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30)\n[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329)\n[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Borewit/strtok3&amp;utm_campaign=Badge_Grade)\n# strtok3\n\nA promise-based streaming [*tokenizer*](#tokenizer-object) for [Node.js](https://nodejs.org) and browsers.\n\nThe `strtok3` module provides several methods for creating a [*tokenizer*](#tokenizer-object) from various input sources. \nDesigned for:\n* Seamless support in streaming environments.\n* Efficiently decode binary data, strings, and numbers.\n* Reading [predefined](https://github.com/Borewit/token-types) or custom tokens.\n* Offering [*tokenizers*](#tokenizer-object) for reading from [files](#fromfile-function), [streams](#fromstream-function) or [Uint8Arrays](#frombuffer-function).\n\n### Features\n`strtok3` can read from:\n* Files, using a file path as input.\n* Node.js [streams](https://nodejs.org/api/stream.html).\n* WHATWG [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) objects containing `Uint8Array` chunks.\n* [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).\n* [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects.\n* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http).\n* [Amazon S3](https://aws.amazon.com/s3) chunks with [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3).\n\n## Installation\n\n```sh\nnpm install strtok3\n```\n\n### Compatibility\n\nStarting with version 7, the module has migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [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.\n\nRequires a modern browser, Node.js (V8) ≥ 18 engine or Bun (JavaScriptCore) ≥ 1.2.\nIt can also be used in a browser environment when bundled with a module bundler.\n\nFor TypeScript CommonJS backward compatibility, you can use [load-esm](https://github.com/Borewit/load-esm).\n\nUse Node.js 24 LTS to build the project and install development dependencies.\nThis build requirement is separate from the Node.js ≥ 18 runtime requirement in `package.json`.\nCI builds once with Node.js 24, then runs the compiled JavaScript unit tests across the Node.js compatibility matrix and Bun 1.2.x, 1.3.x, and 1.4.x.\nCoverage is collected in a separate Node.js 24 job.\n\nFor local development, running the TypeScript tests with `tsx` requires Node.js 18.19+ (18.x) or Node.js ≥ 20.6.0.\n\n## Support the Project\nIf you find this project useful and would like to support its development, consider sponsoring or contributing:\n\n- [Become a sponsor to Borewit](https://github.com/sponsors/Borewit)\n\n- Buy me a coffee:\n\n  <a href=\"https://www.buymeacoffee.com/borewit\" target=\"_blank\"><img src=\"https://cdn.buymeacoffee.com/buttons/default-orange.png\" alt=\"Buy me A coffee\" height=\"41\" width=\"174\"></a>\n\n## API Documentation\n\n### strtok3 methods\n\nUse one of the methods to instantiate an [*abstract tokenizer*](#tokenizer-object):\n- [fromBlob](#fromblob-function)\n- [fromBuffer](#frombuffer-function)\n- [fromFile](#fromfile-function)*\n- [fromStream](#fromstream-function)*\n- [fromWebStream](#fromwebstream-function)\n\n> [!NOTE]\n> `fromFile` requires Node.js file-system APIs, and `fromStream` requires a Node.js readable stream.\n> In browsers, use `fromBlob`, `fromBuffer`, or `fromWebStream`.\n\nAll methods return a [`Tokenizer`](#tokenizer-object), either directly or via a promise.\n\n#### `fromBlob()` function\n\nCreate a tokenizer from a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\n```ts\nfunction fromBlob(blob: Blob, options?: ITokenizerOptions): BlobTokenizer\n```\n\n| Parameter | Optional  | Type                                              | Description                                                                            |\n|-----------|-----------|---------------------------------------------------|----------------------------------------------------------------------------------------|\n| blob      | no        | [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)  | [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [File](https://developer.mozilla.org/en-US/docs/Web/API/File) to read from |\n| options   | yes       | [ITokenizerOptions](#itokenizeroptions-interface)           | Tokenizer options                                                                      |\n\nReturns a [*tokenizer*](#tokenizer-object).\n\n```js\nimport { fromBlob } from 'strtok3';\nimport * as Token from 'token-types';\n\nasync function parse() {\n  const blob = new Blob([new Uint8Array([42])]);\n\n  const tokenizer = fromBlob(blob);\n\n  const myUint8Number = await tokenizer.readToken(Token.UINT8);\n  console.log(`My number: ${myUint8Number}`);   \n}\n\nparse();\n\n```\n\n#### `fromBuffer()` function\n\nCreate a tokenizer from memory ([Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or Node.js [Buffer](https://nodejs.org/api/buffer.html)).\n\n```ts\nfunction fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer\n```\n\n| Parameter  | Optional | Type                                             | Description                       |\n|------------|----------|--------------------------------------------------|-----------------------------------|\n| uint8Array | no       | [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | Buffer or Uint8Array to read from |\n| options    | yes      | [ITokenizerOptions](#itokenizeroptions-interface)          | Tokenizer options                 |\n\nReturns a [*tokenizer*](#tokenizer-object).\n\n```js\nimport { fromBuffer } from 'strtok3';\nimport * as Token from 'token-types';\n\nconst tokenizer = fromBuffer(new Uint8Array([42]));\n\nasync function parse() {\n  const myUint8Number = await tokenizer.readToken(Token.UINT8);\n  console.log(`My number: ${myUint8Number}`);\n}\n\nparse();\n```\n\n#### `fromFile` function\n\nCreates a [*tokenizer*](#tokenizer-object) from a local file.\n\n```ts\nfunction fromFile(sourceFilePath: string, options?: IFromFileOptions): Promise<FileTokenizer>\n```  \n\n| Parameter      | Type     | Description                |\n|----------------|----------|----------------------------|\n| sourceFilePath | `string` | Path to file to read from  |\n| options | [IFromFileOptions](#ifromfileoptions-interface) | Optional file tokenizer options |\n\n> [!NOTE]\n> - Only available for Node.js engines\n> - `fromFile` automatically embeds [file information](#ifileinfo-interface)\n\nA Promise resolving to a [*tokenizer*](#tokenizer-object) which can be used to parse a file.\n\n```js\nimport { fromFile } from 'strtok3';\nimport * as Token from 'token-types';\n\nasync function parse() {\n  const tokenizer = await fromFile('somefile.bin');\n  try {\n    const myNumber = await tokenizer.readToken(Token.UINT8);\n    console.log(`My number: ${myNumber}`);\n  } finally {\n    await tokenizer.close(); // Close the file\n  }\n}\n\nparse();\n\n\n```\n\n#### `fromStream()` function\n\nCreate a tokenizer from a Node.js [readable stream](https://nodejs.org/api/stream.html#readable-streams) containing binary data.\n\n```ts\nfunction fromStream(stream: Readable, options?: ITokenizerOptions): Promise<ReadStreamTokenizer>\n```\n\n| Parameter | Optional | Type | Description |\n|-----------|----------|------|-------------|\n| stream | no | Readable | Node.js readable stream to read from |\n| options | yes | [ITokenizerOptions](#itokenizeroptions-interface) | Tokenizer options |\n\nWhen importing from `strtok3` in Node.js, returns a promise resolving to a [*tokenizer*](#tokenizer-object).\nFor streams created by `createReadStream`, the file path and size are added to `tokenizer.fileInfo`.\nThe `strtok3/core` entry point also exports `fromStream`, but returns the tokenizer synchronously without looking up file information.\n\n```js\nimport { createReadStream } from 'node:fs';\nimport { fromStream } from 'strtok3';\nimport * as Token from 'token-types';\n\nasync function parse() {\n  const stream = createReadStream('somefile.bin');\n  try {\n    const tokenizer = await fromStream(stream);\n    try {\n      const myNumber = await tokenizer.readToken(Token.UINT8);\n      console.log(`My number: ${myNumber}`);\n    } finally {\n      await tokenizer.close();\n    }\n  } finally {\n    stream.destroy();\n  }\n}\n\nparse();\n```\n\n#### `fromWebStream()` function\n\nCreate a tokenizer from a [WHATWG ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) containing `Uint8Array` chunks.\n\nUses a BYOB reader when supported by the stream, otherwise a default reader. Source cleanup differs between these readers; see [`close()`](#close-function) and [`abort()`](#abort-function).\n\n```ts\nfunction fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer\n```\n\n| Parameter      | Optional | Type                                                                     | Description                        |\n|----------------|----------|--------------------------------------------------------------------------|------------------------------------|\n| webStream      | no       | [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) | WHATWG ReadableStream to read from |\n| options        | yes      | [ITokenizerOptions](#itokenizeroptions-interface)                                   | Tokenizer options                  |\n\nReturns a [*tokenizer*](#tokenizer-object).\n\n```js\nimport { fromWebStream } from 'strtok3';\nimport * as Token from 'token-types';\n\nasync function parse() {\n  const tokenizer = fromWebStream(readableStream);\n  try {\n    const myUint8Number = await tokenizer.readToken(Token.UINT8);\n    console.log(`My number: ${myUint8Number}`);\n  } finally {\n    await tokenizer.close();\n  }\n}\n\nparse();\n```\n\n### `Tokenizer` object\nThe *tokenizer* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), allowing _reading_ or _peeking_ from the stream.\nIt can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http);\n\n#### Key Features:\n\n- Supports seeking within the stream using `tokenizer.ignore()`.\n- Offers `peek` methods to preview data without advancing the read pointer.\n- Maintains the read position via `tokenizer.position`.\n- Supports random access for buffer, blob, and file tokenizers.\n\n#### Tokenizer functions\n\n_Read_ methods advance the stream pointer, while _peek_ methods do not.\n\nThere are two kinds of functions:\n1. *read* methods: used to read a *token* or bytes into a buffer from the [*tokenizer*](#tokenizer-object). The position of the *tokenizer-stream* will advance with the number of bytes read.\n2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead.\n\n#### `readBuffer` function\n\nRead data from the _tokenizer_ into provided \"buffer\" (`Uint8Array`).\n`readBuffer(buffer, options?)`\n\n```ts\nreadBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;\n```\n\n| Parameter  | Type                                                           | Description                                                                                                                                                                                                                            |\n|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| buffer     | [Buffer](https://nodejs.org/api/buffer.html) &#124; Uint8Array | Target buffer to write the data read to                                                                                                                                                                                                |\n| options    | [IReadChunkOptions](#ireadchunkoptions-interface)                        | Optional settings for the length, position, and handling of partial reads |\n\nReturn promise with number of bytes read.\nThe number of bytes read may be less than requested if the `mayBeLess` flag is set.\n\n#### `peekBuffer` function\n\nPeek (read ahead), from [*tokenizer*](#tokenizer-object), into the buffer without advancing the stream pointer.\n\n```ts\npeekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;\n```\n\n| Parameter  | Type                                    | Description                                         |\n|------------|-----------------------------------------|-----------------------------------------------------|\n| buffer     | Buffer &#124; Uint8Array                | Target buffer to write the data read (peeked) to.   |\n| options    | [IReadChunkOptions](#ireadchunkoptions-interface) | Optional settings for the length, position, and handling of partial reads |\n\nReturn value `Promise<number>` Promise with number of bytes read. The number of bytes read may be less if the `mayBeLess` flag was set.\n\n#### `readToken` function\n\nRead a *token* from the tokenizer-stream.\n\n```ts\nreadToken<Value>(token: IGetToken<Value>, position: number = this.position): Promise<Value>\n```  \n\n| Parameter  | Type                    | Description                                                                                                           |\n|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- |\n| token      | [IGetToken](#token-object) | Token to read from the tokenizer-stream. |\n| position?  | number | Offset where to begin reading. Defaults to `tokenizer.position` when omitted. |\n\nReturns a `Promise<Value>` resolving to the decoded token value. Rejects with `EndOfStreamError` if fewer than `token.len` bytes are available.\n\n#### `peekToken` function\n\nPeek a *token* from the [*tokenizer*](#tokenizer-object).\n\n```ts\npeekToken<Value>(token: IGetToken<Value>, position: number | null = this.position): Promise<Value>\n```\n\n| Parameter  | Type                       | Description                                                                                                             |\n|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|\n| token      | [IGetToken](#token-object) | Token to peek from the tokenizer-stream. |\n| position?  | number &#124; null | Offset where to begin peeking. Defaults to `tokenizer.position` when omitted or `null`. |\n\nReturn a promise with the token value peeked from the [*tokenizer*](#tokenizer-object).\n\n#### `readNumber` function\n\nRead a numeric [*token*](#token-object) from the [*tokenizer*](#tokenizer-object).\n\n```ts\nreadNumber(token: IToken<number>): Promise<number>\n```\n\n| Parameter  | Type                            | Description                                        |\n|------------|---------------------------------|----------------------------------------------------|\n| token      | [IToken<number>](#token-object) | Numeric token to read from the tokenizer-stream.   |\n\nA promise resolving to a numeric value read and decoded from the *tokenizer-stream*.\n\n#### `peekNumber` function\n\nPeek a numeric [*token*](#token-object) without advancing `tokenizer.position`.\n\n```ts\npeekNumber(token: IToken<number>): Promise<number>\n```\n\nReturns a promise resolving to the decoded numeric value.\nLike `readNumber`, rejects with `EndOfStreamError` if the token cannot be read in full.\n\n#### `ignore` function\n\nAdvance the offset pointer with the token number of bytes provided.\n\n```ts\nignore(length: number): Promise<number>\n```\n\n| Parameter  | Type   | Description                                                      |\n|------------|--------|------------------------------------------------------------------|\n| length     | number | Non-negative number of bytes to ignore. Advances `tokenizer.position`. |\n\nReturns a promise resolving to the number of bytes ignored.\nBuffer, blob, and file tokenizers stop at the known file size. Stream tokenizers reject with `EndOfStreamError` if the requested bytes are unavailable.\n\n#### `close` function\nClean up resources, such as closing a file pointer if applicable.\n\n```ts\nclose(): Promise<void>\n```\n\nAwait this method when finished with a tokenizer. For Node.js streams, it does not destroy the underlying stream; the caller remains responsible for its lifecycle.\n\nFor Web streams, `close()` releases the reader lock. A BYOB reader leaves the source uncancelled, allowing another reader to continue reading it. A default reader cancels the source before releasing the lock, discarding remaining data. Bytes already read into tokenizer buffers, including peeked bytes, are not returned to the source.\n\n#### `abort` function\n\nAbort pending asynchronous stream operations.\n\n```ts\nabort(): Promise<void>\n```\n\nThis is a no-op for buffer, blob, and file tokenizers.\n\nFor Web streams, `abort()` releases a BYOB reader's lock without cancelling the source. A default reader cancels the source but keeps its lock until `close()` is called. An `AbortSignal` invokes the same abort behavior.\n\n#### `supportsRandomAccess` function\n\n```ts\nsupportsRandomAccess(): boolean\n```\n\nReturns `true` for buffer, blob, and file tokenizers, and `false` for stream tokenizers.\nWhen random access is supported, read and peek methods can use positions before `tokenizer.position`.\n\n#### `setPosition` function\n\nAvailable on buffer, blob, and file tokenizers (`IRandomAccessTokenizer`).\n\n```ts\nsetPosition(position: number): void\n```\n\nSets the current byte offset without reading data.\n\n#### `Tokenizer` attributes\n\n- `fileInfo`\n\n  Object containing optional file information, see [IFileInfo](#ifileinfo-interface).\n\n- `position`\n\n  Pointer to the current position in the [*tokenizer*](#tokenizer-object) stream.\n  For stream tokenizers, a *position* provided to a _read_ or _peek_ method must be at least this value.\n  Buffer, blob, and file tokenizers also support earlier positions.\n\n### `ITokenizerOptions` interface\n\nSet these options once when creating a tokenizer. The configured limit applies to subsequent\nreads and peeks for that tokenizer; no per-read limit is needed. Each attribute is optional:\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| maxBufferSize | number | Maximum bytes in a dynamically sized tokenizer buffer or stream lookahead span. Disabled by default (`Infinity`). Must be a positive safe integer or `Infinity`. |\n| fileInfo | [IFileInfo](#ifileinfo-interface) | Additional metadata about the input |\n| onClose | `() => Promise<void>` | Asynchronous callback invoked when a buffer, blob, or file tokenizer is closed |\n| abortSignal | [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) | Signal used to abort asynchronous stream operations |\n\nCreating a tokenizer with an already-aborted `abortSignal` throws or rejects with `AbortError`\nbefore acquiring file handles or stream readers. Signal listeners are removed when the signal\nfires or the tokenizer is closed, so closed tokenizers can be collected even when a signal is reused.\n\nWhen `maxBufferSize` is configured, `readToken()` and `peekToken()` reject oversized buffers with `BufferSizeError`\nbefore allocating or consuming input. The error exposes `requestedSize` and `maxBufferSize`.\nToken lengths and positions must be non-negative safe integers. When the input size is known,\na token extending beyond the input rejects with `EndOfStreamError` before allocation.\n\nFor streams, the lookahead limit includes bytes between the current position and the requested\npeek position. `mayBeLess: true` does not bypass this limit. With a finite cap, reads into\ncaller-provided buffers, Blob reads and `ignore()` use bounded chunks where internal buffers\nare needed, so their total requested length may exceed `maxBufferSize`.\n\nThis limit does not cap total process memory, caller-owned input/output buffers, or allocations\ninside a token's `get()` method. Stream sources may also supply chunks larger than this limit.\nThe cap is opt-in to preserve existing buffer sizes. Applications parsing untrusted input should\nset a finite limit, for example 64 MiB. Omit the option or set it to `Infinity` to disable the cap.\n\n```js\nimport { BufferSizeError, fromFile } from 'strtok3';\n\nconst tokenizer = await fromFile('somefile.bin', { maxBufferSize: 64 * 1024 * 1024 });\ntry {\n  // Read or peek tokens here.\n} catch (error) {\n  if (error instanceof BufferSizeError) {\n    console.error(`Requested ${error.requestedSize} bytes; limit is ${error.maxBufferSize}`);\n  } else {\n    throw error;\n  }\n} finally {\n  await tokenizer.close();\n}\n```\n\n### `IFromFileOptions` interface\n\nExtends [ITokenizerOptions](#itokenizeroptions-interface) for `fromFile()`.\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| regularFileOnly | `boolean` | When `true`, opens with `O_RDONLY \\| O_NONBLOCK` and checks that the opened handle refers to a regular file. Defaults to `false`, preserving existing behavior. |\n\nUse this option when non-regular inputs, such as FIFOs, should be rejected without waiting for a writer. Validation uses the opened handle, so replacing the pathname before opening does not bypass the check. Symbolic links to regular files are accepted.\n\nIf an opened handle is not a regular file, `fromFile()` closes it and rejects with the exported `NotRegularFileError`. Its `path` property identifies the requested path. Opening errors, stat errors, and abort errors continue to propagate; any handle acquired by the factory is closed if setup fails. After success, the caller must close the tokenizer.\n\n```js\nimport { fromFile, NotRegularFileError } from 'strtok3';\n\ntry {\n  const tokenizer = await fromFile('somefile.bin', { regularFileOnly: true });\n  try {\n    // Parse the regular file.\n  } finally {\n    await tokenizer.close();\n  }\n} catch (error) {\n  if (!(error instanceof NotRegularFileError)) {\n    throw error;\n  }\n  // Handle an input that is not a regular file.\n}\n```\n\n### `IReadChunkOptions` interface\n\nEach attribute is optional:\n\n| Attribute | Type    | Description                                                                                                                                                                                                                   |\n|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| length    | number  | Requested number of bytes to read or peek. Defaults to the target buffer length. |\n| position  | number  | Byte offset to read or peek from. Defaults to [tokenizer.position](#tokenizer-attributes) when omitted. Earlier positions require random access. |\n| mayBeLess | boolean | If `true`, allows fewer than the requested number of bytes to be read or peeked instead of throwing `EndOfStreamError`. Defaults to `false`. |\n\nExample usage:\n```js\n  const bytesPeeked = await tokenizer.peekBuffer(buffer, {mayBeLess: true});\n```\n\n### `IFileInfo` interface\n\nProvides optional metadata about the file being tokenized.\n\n| Attribute | Type    | Description                                                                                       |\n|-----------|---------|---------------------------------------------------------------------------------------------------|\n| size      | number  | File size in bytes                                                                                |\n| mimeType  | string  | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. |\n| path      | string  | File path                                                                                         |\n| url       | string  | File URL                                                                                          |\n\n### `Token` object\n\nThe *token* is basically a description of what to read from the [*tokenizer-stream*](#tokenizer-object).\nA basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types).\n\nA token is something which implements the following interface:\n```ts\nexport interface IGetToken<T> {\n\n  /**\n   * Length in bytes of encoded value\n   */\n  len: number;\n\n  /**\n   * Decode value from buffer at offset\n   * @param buf Buffer to read the decoded value from\n   * @param off Decode offset\n   */\n  get(buf: Uint8Array, off: number): T;\n}\n```\nThe *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer.\nThe `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type.\n\n### Working with a fetch response\n\nPass the response's [WHATWG readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) directly to `fromWebStream`.\n\n```js\nimport { fromWebStream } from 'strtok3';\nimport * as Token from 'token-types';\n\n(async () => {\n\n  const response = await fetch(url);\n  if (!response.ok || !response.body) {\n    throw new Error(`Cannot read response: ${response.status}`);\n  }\n\n  const tokenizer = fromWebStream(response.body);\n  try {\n    const myNumber = await tokenizer.readToken(Token.UINT8);\n    console.log(`My number: ${myNumber}`);\n  } finally {\n    await tokenizer.close();\n  }\n})();\n```\n\n## Dependencies\n\nDependencies:\n- [@tokenizer/token](https://github.com/Borewit/tokenizer-token): Provides token definitions and utilities used by `strtok3` for interpreting binary data.\n\n## Contributing\n\nSee [the contribution guide](CONTRIBUTING.md) for code style and development commands.\n\n## Licence\n\nThis project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed.\n","publish_time":1791907086535,"_cnpm_publish_time":1791907086535,"dist-tags":{"beta":"10.1.0-beta.5","esm":"7.0.0-alpha.9","latest":"10.7.0"}}