diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 87c4128..cda8031 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -12,6 +12,8 @@ env: jobs: format: runs-on: ubuntu-latest + outputs: + sha: ${{ steps.head.outputs.sha }} permissions: contents: write @@ -52,14 +54,19 @@ jobs: git commit -m "style: format files" git push + - id: head + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + test: needs: format runs-on: ubuntu-latest + permissions: + contents: write steps: - uses: actions/checkout@v6 with: - ref: ${{ github.event_name == 'push' && github.ref_name || github.sha }} + ref: ${{ needs.format.outputs.sha }} - uses: actions/setup-node@v6 with: @@ -77,6 +84,24 @@ jobs: - run: npm test + - run: npm run bench + + - name: Generate README results from this CI run + run: npm run reports:ci + + - name: Upload test, coverage, and benchmark reports + if: always() + uses: actions/upload-artifact@v7 + with: + name: bytecodec-reports + include-hidden-files: true + path: | + README.md + test/.results/ + benchmark/.results/ + coverage/ + test-results/ + - name: Upload coverage to Codecov uses: codecov/codecov-action@v5 with: @@ -84,6 +109,23 @@ jobs: files: coverage/lcov.info fail_ci_if_error: true + - name: Commit generated README results + if: github.event_name == 'push' + env: + TESTED_SHA: ${{ needs.format.outputs.sha }} + run: | + current_sha=$(git ls-remote origin refs/heads/master | cut -f1) + if [ "$current_sha" != "$TESTED_SHA" ]; then + echo "master advanced during this run; results remain available in the artifact" + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add README.md + if git diff --cached --quiet; then exit 0; fi + git commit -m "docs: update CI test and benchmark results" + git push origin HEAD:master + release-please: if: github.event_name == 'push' needs: test diff --git a/.gitignore b/.gitignore index 76a86d9..1ce119a 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,7 @@ test-results/ .DS_Store Thumbs.db -.wrangler/ \ No newline at end of file +.wrangler/ +test/.results/ +benchmark/.results/ +playwright-report/ diff --git a/.prettierignore b/.prettierignore index 2ab8a59..86e6f5b 100644 --- a/.prettierignore +++ b/.prettierignore @@ -5,3 +5,6 @@ playwright-report *.lock CHANGELOG.md docs + +test/.results +benchmark/.results diff --git a/README.md b/README.md index bcd9d44..030a961 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,16 @@ Runtime-agnostic TypeScript byte codecs for Base45, Base64, UTF-8, gzip, HKDF derivation, secure random generation, normalization, concatenation, and comparison. -The root entrypoint provides the declarative `Bytes` API. Focused subpath exports let applications import only the codec or utilities they need. +## Contents + +- [Compatibility](#compatibility) +- [Bytes API](#bytes-api) +- [Base45](#base45) · [Usage](#base45-usage) · [Errors](#base45-errors) · [Benchmarks](#base45-benchmarks) · [Tests](#base45-tests) +- [Base64 and Base64URL](#base64-and-base64url) · [Usage](#base64-usage) · [Errors](#base64-errors) · [Benchmarks](#base64-benchmarks) · [Tests](#base64-tests) +- [UTF-8](#utf-8) · [Usage](#utf8-usage) · [Errors](#utf8-errors) · [Benchmarks](#utf8-benchmarks) · [Tests](#utf8-tests) +- [Gzip](#gzip) · [Usage](#gzip-usage) · [Errors](#gzip-errors) · [Benchmarks](#gzip-benchmarks) · [Tests](#gzip-tests) +- [Byte utilities](#byte-utilities) · [Usage](#util-usage) · [Errors](#util-errors) · [Benchmarks](#util-benchmarks) · [Tests](#util-tests) +- [License](#license) ## Compatibility @@ -18,55 +27,13 @@ The root entrypoint provides the declarative `Bytes` API. Focused subpath export - Dependencies: no runtime dependencies or bundler shims. - Gzip: `node:zlib` in Node-like runtimes; `CompressionStream` and `DecompressionStream` elsewhere. -## Installation - -```sh -npm install @sovereignbase/bytecodec -# or -pnpm add @sovereignbase/bytecodec -# or -yarn add @sovereignbase/bytecodec -# or -bun add @sovereignbase/bytecodec -# or -deno add jsr:@sovereignbase/bytecodec -# or -vlt install jsr:@sovereignbase/bytecodec -``` - -## Entry points - -| Import | Exports | -| --------------------------------------- | ----------------------------------------------------------------------------- | -| `@sovereignbase/bytecodec` | `Bytes`, `ByteSource`, `BytecodecErrorCode` | -| `@sovereignbase/bytecodec/base45` | `bytesToBase45String`, `bytesFromBase45String` | -| `@sovereignbase/bytecodec/base64` | Base64 and unpadded Base64URL encode/decode functions | -| `@sovereignbase/bytecodec/utf8` | `bytesToUTF8String`, `bytesFromUTF8String` | -| `@sovereignbase/bytecodec/gzip` | `bytesToGzipBytes`, `bytesFromGzipBytes` | -| `@sovereignbase/bytecodec/util` | `normalizeBytes`, `concatBytes`, `equalBytes`, `deriveBytes`, `generateBytes` | -| `@sovereignbase/bytecodec/package.json` | Package metadata | - -Type-only exports in the table do not add runtime exports. The root runtime surface intentionally contains only `Bytes`. - -## Usage +## Bytes API ### Declarative `Bytes` API ```ts import { Bytes } from '@sovereignbase/bytecodec' -const bytes = Bytes.utf8.decode('hello ✓') -const encoding = 'base64url' -const encoded = Bytes[encoding].encode(bytes) -const decoded = Bytes[encoding].decode(encoded) -const text = Bytes.utf8.encode(decoded) -``` - -Codec directions are consistent: `encode` converts bytes into the codec representation and `decode` converts that representation back into bytes. For UTF-8, the representation is a JavaScript string; for gzip, both sides are bytes. - -The complete wrapper surface is: - -```ts Bytes.base45.encode(bytes) Bytes.base45.decode(base45String) @@ -89,26 +56,15 @@ await Bytes.derive(base, domain, byteLength) Bytes.generate(byteLength) ``` -### Focused imports +Codec directions are consistent: `encode` converts bytes into the codec representation and `decode` converts that representation back into bytes. -Focused entrypoints avoid loading the root wrapper and unrelated codecs. +The root also exports `BytecodecError` for `instanceof` checks and the `ByteSource` and `BytecodecErrorCode` types. Validation errors expose a stable `code`; unexpected wrapped failures use `UNKNOWN_ERROR` and retain the original `cause`. -```ts -import { - bytesFromUTF8String, - bytesToUTF8String, -} from '@sovereignbase/bytecodec/utf8' -import { - bytesFromBase64UrlString, - bytesToBase64UrlString, -} from '@sovereignbase/bytecodec/base64' +## Base45 -const bytes = bytesFromUTF8String('split import') -const encoded = bytesToBase64UrlString(bytes) -const restored = bytesToUTF8String(bytesFromBase64UrlString(encoded)) -``` + -### Base45 +### Usage ```ts import { @@ -122,7 +78,80 @@ const decoded = bytesFromBase45String(encoded) Base45 follows RFC 9285 and is useful for QR-friendly payloads. -### Base64 and Base64URL + + +### Errors + +Invalid text throws BASE45_INPUT_EXPECTED, BASE45_INVALID_LENGTH, BASE45_INVALID_CHARACTER or BASE45_INVALID_CHUNK. + + + +### Benchmarks + + + +2026-11-19T14:31:08.442Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz · 1,000 measured calls per case after warmup + +| Operation | Input bytes | Ops/sec | +| --------- | ----------: | ------: | +| encode | 64 | 141,237 | +| decode | 64 | 238,317 | +| encode | 1024 | 31,255 | +| decode | 1024 | 67,955 | +| encode | 16384 | 2,048 | +| decode | 16384 | 3,433 | + + + + + +### Tests + + + +2026-11-19T14:28:15.863Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +| Suite | Passed | Failed | Skipped | +| ---------------- | -----: | -----: | ------: | +| base45 (2 files) | 35 | 0 | 0 | + +| Coverage | statements | branches | functions | lines | +| -------- | ---------: | -------: | --------: | ----: | +| Percent | 100% | 100% | 100% | 100% | + +#### Compatibility + +The shared compatibility suite exercises the whole public API. + +| Runtime / browser | Version | Status | Passed | Failed | +| ---------------------- | -----------: | -----: | -----: | -----: | +| node esm | 24.16.0 | passed | 9 | 0 | +| node cjs | 24.16.0 | passed | 9 | 0 | +| bun esm | 1.3.10 | passed | 9 | 0 | +| bun cjs | 1.3.10 | passed | 9 | 0 | +| deno esm | 2.8.3 | passed | 9 | 0 | +| edge-runtime esm | 4.0.1 | passed | 9 | 0 | +| cloudflare-workers esm | 1.20261118.1 | passed | 9 | 0 | +| chromium | 159.0.8154.6 | passed | 1 | 0 | +| firefox | — | failed | 0 | 1 | +| webkit | 27.2 | passed | 1 | 0 | +| mobile-chromium | 159.0.8154.6 | passed | 1 | 0 | +| mobile-firefox | — | failed | 0 | 1 | +| mobile-webkit | 27.2 | passed | 1 | 0 | + + + +## Base64 and Base64URL + + + +### Usage ```ts import { @@ -139,7 +168,86 @@ bytesFromBase64String('aGVsbG8=') bytesFromBase64UrlString('aGVsbG8') ``` -### UTF-8 + + +### Errors + +Unavailable runtime APIs throw BASE64_ENCODER_UNAVAILABLE or BASE64_DECODER_UNAVAILABLE. Base64URL length modulo four must not equal one (BASE64URL_INVALID_LENGTH). Other parsing behavior follows the runtime Base64 decoder. + + + +### Benchmarks + + + +2026-11-19T14:31:09.132Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz · 1,000 measured calls per case after warmup + +| Operation | Input bytes | Ops/sec | +| ---------------- | ----------: | ------: | +| base64 encode | 64 | 116,532 | +| base64 decode | 64 | 297,628 | +| base64url encode | 64 | 281,698 | +| base64url decode | 64 | 496,376 | +| base64 encode | 1024 | 209,258 | +| base64 decode | 1024 | 160,377 | +| base64url encode | 1024 | 82,570 | +| base64url decode | 1024 | 96,676 | +| base64 encode | 16384 | 18,179 | +| base64 decode | 16384 | 20,135 | +| base64url encode | 16384 | 8,358 | +| base64url decode | 16384 | 13,444 | + + + + + +### Tests + + + +2026-11-19T14:28:15.863Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +| Suite | Passed | Failed | Skipped | +| ---------------- | -----: | -----: | ------: | +| base64 (2 files) | 34 | 0 | 0 | + +| Coverage | statements | branches | functions | lines | +| -------- | ---------: | -------: | --------: | ----: | +| Percent | 100% | 100% | 100% | 100% | + +#### Compatibility + +The shared compatibility suite exercises the whole public API. + +| Runtime / browser | Version | Status | Passed | Failed | +| ---------------------- | -----------: | -----: | -----: | -----: | +| node esm | 24.16.0 | passed | 9 | 0 | +| node cjs | 24.16.0 | passed | 9 | 0 | +| bun esm | 1.3.10 | passed | 9 | 0 | +| bun cjs | 1.3.10 | passed | 9 | 0 | +| deno esm | 2.8.3 | passed | 9 | 0 | +| edge-runtime esm | 4.0.1 | passed | 9 | 0 | +| cloudflare-workers esm | 1.20261118.1 | passed | 9 | 0 | +| chromium | 159.0.8154.6 | passed | 1 | 0 | +| firefox | — | failed | 0 | 1 | +| webkit | 27.2 | passed | 1 | 0 | +| mobile-chromium | 159.0.8154.6 | passed | 1 | 0 | +| mobile-firefox | — | failed | 0 | 1 | +| mobile-webkit | 27.2 | passed | 1 | 0 | + + + +## UTF-8 + + + +### Usage ```ts import { @@ -151,7 +259,80 @@ const bytes = bytesFromUTF8String('café ✓ 🚀') const text = bytesToUTF8String(bytes) ``` -### Gzip + + +### Errors + +Non-string text input throws STRING_INPUT_EXPECTED. Missing codecs throw UTF8_ENCODER_UNAVAILABLE or UTF8_DECODER_UNAVAILABLE. + + + +### Benchmarks + + + +2026-11-19T14:31:09.535Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz · 1,000 measured calls per case after warmup + +| Operation | Input bytes | Ops/sec | +| ----------------------- | ----------: | ------: | +| encode (bytes → string) | 64 | 336,383 | +| decode (string → bytes) | 64 | 429,627 | +| encode (bytes → string) | 1024 | 164,864 | +| decode (string → bytes) | 1024 | 138,968 | +| encode (bytes → string) | 16384 | 32,916 | +| decode (string → bytes) | 16384 | 9,672 | + + + + + +### Tests + + + +2026-11-19T14:28:15.863Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +| Suite | Passed | Failed | Skipped | +| -------------- | -----: | -----: | ------: | +| utf8 (2 files) | 32 | 0 | 0 | + +| Coverage | statements | branches | functions | lines | +| -------- | ---------: | -------: | --------: | ----: | +| Percent | 100% | 100% | 100% | 100% | + +#### Compatibility + +The shared compatibility suite exercises the whole public API. + +| Runtime / browser | Version | Status | Passed | Failed | +| ---------------------- | -----------: | -----: | -----: | -----: | +| node esm | 24.16.0 | passed | 9 | 0 | +| node cjs | 24.16.0 | passed | 9 | 0 | +| bun esm | 1.3.10 | passed | 9 | 0 | +| bun cjs | 1.3.10 | passed | 9 | 0 | +| deno esm | 2.8.3 | passed | 9 | 0 | +| edge-runtime esm | 4.0.1 | passed | 9 | 0 | +| cloudflare-workers esm | 1.20261118.1 | passed | 9 | 0 | +| chromium | 159.0.8154.6 | passed | 1 | 0 | +| firefox | — | failed | 0 | 1 | +| webkit | 27.2 | passed | 1 | 0 | +| mobile-chromium | 159.0.8154.6 | passed | 1 | 0 | +| mobile-firefox | — | failed | 0 | 1 | +| mobile-webkit | 27.2 | passed | 1 | 0 | + + + +## Gzip + + + +### Usage ```ts import { @@ -163,7 +344,80 @@ const compressed = await bytesToGzipBytes(new Uint8Array([1, 2, 3])) const restored = await bytesFromGzipBytes(compressed) ``` -### Byte utilities + + +### Errors + +Missing compression APIs throw GZIP_COMPRESSION_UNAVAILABLE or GZIP_DECOMPRESSION_UNAVAILABLE. Node zlib failures throw UNKNOWN_ERROR with the original cause. Web stream processing errors can reject with the original runtime error. + + + +### Benchmarks + + + +2026-11-19T14:31:13.084Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz · 1,000 measured calls per case after warmup + +| Operation | Input bytes | Ops/sec | +| ---------- | ----------: | ------: | +| compress | 64 | 2,014 | +| decompress | 64 | 2,857 | +| compress | 1024 | 1,695 | +| decompress | 1024 | 2,857 | +| compress | 16384 | 1,576 | +| decompress | 16384 | 2,377 | + + + + + +### Tests + + + +2026-11-19T14:28:15.863Z · local run · commit `cca7177` + +Node v24.16.0 · win32 x64 + +| Suite | Passed | Failed | Skipped | +| -------------- | -----: | -----: | ------: | +| gzip (1 files) | 5 | 0 | 0 | + +| Coverage | statements | branches | functions | lines | +| -------- | ---------: | -------: | --------: | ----: | +| Percent | 100% | 100% | 100% | 100% | + +#### Compatibility + +The shared compatibility suite exercises the whole public API. + +| Runtime / browser | Version | Status | Passed | Failed | +| ---------------------- | -----------: | -----: | -----: | -----: | +| node esm | 24.16.0 | passed | 9 | 0 | +| node cjs | 24.16.0 | passed | 9 | 0 | +| bun esm | 1.3.10 | passed | 9 | 0 | +| bun cjs | 1.3.10 | passed | 9 | 0 | +| deno esm | 2.8.3 | passed | 9 | 0 | +| edge-runtime esm | 4.0.1 | passed | 9 | 0 | +| cloudflare-workers esm | 1.20261118.1 | passed | 9 | 0 | +| chromium | 159.0.8154.6 | passed | 1 | 0 | +| firefox | — | failed | 0 | 1 | +| webkit | 27.2 | passed | 1 | 0 | +| mobile-chromium | 159.0.8154.6 | passed | 1 | 0 | +| mobile-firefox | — | failed | 0 | 1 | +| mobile-webkit | 27.2 | passed | 1 | 0 | + + + +## Byte utilities + + + +### Usage ```ts import { @@ -190,85 +444,91 @@ All functions accepting `ByteSource` support: - any `ArrayBufferView`, including `Uint8Array` and `DataView` - `number[]` -`normalizeBytes()` always returns an independent `Uint8Array` copy. `concatBytes()` also normalizes every input before joining it. +`normalizeBytes()` always returns an independent `Uint8Array` copy, including for shared buffers and offset views. All byte-returning APIs explicitly return `Uint8Array` (or a promise of it). `concatBytes()` also normalizes every input before joining it. -### CommonJS + -Every npm entrypoint has a matching CommonJS export. +### Errors -```js -const { Bytes } = require('@sovereignbase/bytecodec') -const { bytesFromUTF8String } = require('@sovereignbase/bytecodec/utf8') -``` +Invalid sources throw BYTE_SOURCE_EXPECTED. Invalid concatenation throws CONCAT_INVALID_INPUT or CONCAT_NORMALIZE_FAILED with the input index. Web Crypto failures throw UNKNOWN_ERROR with the original cause. Random generation is limited to 65,536 bytes per call by Web Crypto. -## Errors + -Package validation and runtime-capability failures throw `BytecodecError` instances. Each error has: +### Benchmarks -- `name: "BytecodecError"` -- a stable `code` typed as `BytecodecErrorCode` -- a message prefixed with `{@sovereignbase/bytecodec}` + -Codes cover invalid Base45/Base64URL input, unsupported byte sources, invalid concatenation, invalid UTF-8 input, unavailable Base64/UTF-8 codecs, and unavailable gzip APIs. +2026-11-19T14:31:15.360Z · local run · commit `cca7177` -```ts -import type { BytecodecErrorCode } from '@sovereignbase/bytecodec' - -try { - Bytes.base45.decode('A') -} catch (error) { - const code = (error as { code: BytecodecErrorCode }).code - // "BASE45_INVALID_LENGTH" -} -``` +Node v24.16.0 · win32 x64 + +Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz · 1,000 measured calls per case after warmup -## Runtime behavior +| Operation | Input bytes | Ops/sec | +| ---------------- | ----------: | ------: | +| normalize view | 64 | 896,539 | +| concat three | 64 | 180,333 | +| equals same | 64 | 402,495 | +| equals different | 64 | 378,530 | +| generate | 64 | 90,700 | +| derive 32 bytes | 64 | 3,494 | +| normalize view | 1024 | 290,630 | +| concat three | 1024 | 59,787 | +| equals same | 1024 | 155,960 | +| equals different | 1024 | 134,553 | +| generate | 1024 | 113,249 | +| derive 32 bytes | 1024 | 3,021 | +| normalize view | 16384 | 20,386 | +| concat three | 16384 | 3,275 | +| equals same | 16384 | 9,604 | +| equals different | 16384 | 8,352 | +| generate | 16384 | 23,555 | +| derive 32 bytes | 16384 | 2,326 | -Node.js and Bun use `Buffer` for Base64 and `node:zlib` for gzip. Browsers, Cloudflare Workers, Deno, and compatible edge runtimes use standard web APIs. An edge runtime without compression streams can still use every non-gzip entrypoint; gzip calls fail with a structured availability error. + -The package has no side effects. Multi-entry builds share internal chunks while allowing bundlers and runtimes to resolve only the requested public subpath. + -## Tests +### Tests -`npm test` runs: + -- a TypeScript typecheck of source, configuration, tests, and all package entrypoints; -- 27 Vitest unit/integration tests with a 100% statements, branches, functions, and lines coverage gate; -- ESM and CommonJS runtime suites in Node.js and Bun; -- ESM runtime suites in Deno, Cloudflare Workers, and Edge Runtime; -- Playwright tests in Chromium, Firefox, WebKit, mobile Chromium, mobile Firefox, and mobile WebKit. +2026-11-19T14:28:15.863Z · local run · commit `cca7177` -Useful focused commands include `npm run test:vitest`, `npm run test:e2e:browsers`, and `npm run test:e2e:runtimes`. +Node v24.16.0 · win32 x64 -## API documentation +| Suite | Passed | Failed | Skipped | +| -------------- | -----: | -----: | ------: | +| util (3 files) | 68 | 0 | 0 | -Generate the TypeDoc API reference with `npm run build:docs`. The published reference is available at [sovereignbase.dev/bytecodec](https://sovereignbase.dev/bytecodec). +| Coverage | statements | branches | functions | lines | +| -------- | ---------: | -------: | --------: | ----: | +| Percent | 100% | 100% | 100% | 100% | -## Benchmarks +#### Compatibility -`npm run bench` builds the package and benchmarks every public capability. A local run on 2026-09-02 with Node.js 24.16.0 on Windows x64 produced: +The shared compatibility suite exercises the whole public API. -| Benchmark | Operations | Ops/sec | -| ---------------- | ---------: | --------: | -| Base45 encode | 5,000 | 457,641 | -| Base45 decode | 5,000 | 667,067 | -| Base64 encode | 5,000 | 674,372 | -| Base64 decode | 5,000 | 1,586,546 | -| Base64URL encode | 5,000 | 724,186 | -| Base64URL decode | 5,000 | 866,912 | -| UTF-8 encode | 5,000 | 1,349,455 | -| UTF-8 decode | 5,000 | 1,602,102 | -| Normalize | 5,000 | 5,221,387 | -| Concatenate | 5,000 | 597,001 | -| Compare equal | 5,000 | 1,495,573 | -| Compare unequal | 5,000 | 2,264,493 | -| Generate random | 5,000 | 297,134 | -| HKDF derive | 5,000 | 12,060 | -| Gzip compress | 5,000 | 6,324 | -| Gzip decompress | 5,000 | 8,866 | +| Runtime / browser | Version | Status | Passed | Failed | +| ---------------------- | -----------: | -----: | -----: | -----: | +| node esm | 24.16.0 | passed | 9 | 0 | +| node cjs | 24.16.0 | passed | 9 | 0 | +| bun esm | 1.3.10 | passed | 9 | 0 | +| bun cjs | 1.3.10 | passed | 9 | 0 | +| deno esm | 2.8.3 | passed | 9 | 0 | +| edge-runtime esm | 4.0.1 | passed | 9 | 0 | +| cloudflare-workers esm | 1.20261118.1 | passed | 9 | 0 | +| chromium | 159.0.8154.6 | passed | 1 | 0 | +| firefox | — | failed | 0 | 1 | +| webkit | 27.2 | passed | 1 | 0 | +| mobile-chromium | 159.0.8154.6 | passed | 1 | 0 | +| mobile-firefox | — | failed | 0 | 1 | +| mobile-webkit | 27.2 | passed | 1 | 0 | -Results vary by machine, runtime, input, and system load. + ## License -Apache-2.0 +Licensed under the Apache License, Version 2.0. + +Copyright © 2026 Sovereignbase. diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 0000000..a97cffb --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,18 @@ +# Benchmarks + +Each codec has its own `workloads.mjs`. All suites use `runner.mjs`, serial execution, deterministic inputs, and warmup. Fixture construction, result verification, and report writing happen outside measurement. Synchronous calls and awaited asynchronous calls are measured separately. + +```sh +npm run bench +npm run bench:base45 +npm run bench:base64 +npm run bench:utf8 +npm run bench:gzip +npm run bench:util +``` + +The defaults are 64, 1,024 and 16,384 input bytes, 100 warmup calls and 1,000 measured calls per operation. `BENCH_SIZES`, `BENCH_WARMUP` and `BENCH_ITERATIONS` override these values. Input sizes must be positive and at most 65,536 bytes, matching the random generator's Web Crypto quota. + +UTF-8 labels follow the public wrapper: encode converts bytes to a string, decode converts a string to bytes. Utilities measure a shared DataView, concatenation of three inputs, equality, random generation, and 32-byte HKDF derivation. Gzip measures Node's zlib backend. Throughput is calls per second, including each API's normalization and allocation costs. Results depend on machine, runtime, input and system load; they are not a statistical regression gate. + +JSON reports in `.results/.json` record the commit, CI run when available, Node version, operating system, architecture, CPU, configuration and measured timings. `npm run reports` copies these results into the codec sections of the root README. Local reports are labeled as local. CI publishes reports only after the complete test and benchmark run succeeds. diff --git a/benchmark/base45/workloads.mjs b/benchmark/base45/workloads.mjs new file mode 100644 index 0000000..d5d48ad --- /dev/null +++ b/benchmark/base45/workloads.mjs @@ -0,0 +1,16 @@ +import { Bytes } from '../../dist/index.js' +export function workloads({ bytes }) { + const encoded = Bytes.base45.encode(bytes) + return [ + { + operation: 'encode', + run: () => Bytes.base45.encode(bytes), + expected: encoded, + }, + { + operation: 'decode', + run: () => Bytes.base45.decode(encoded), + expected: bytes, + }, + ] +} diff --git a/benchmark/base64/workloads.mjs b/benchmark/base64/workloads.mjs new file mode 100644 index 0000000..a9662d8 --- /dev/null +++ b/benchmark/base64/workloads.mjs @@ -0,0 +1,18 @@ +import { Bytes } from '../../dist/index.js' +export function workloads({ bytes }) { + return ['base64', 'base64url'].flatMap((name) => { + const encoded = Bytes[name].encode(bytes) + return [ + { + operation: name + ' encode', + run: () => Bytes[name].encode(bytes), + expected: encoded, + }, + { + operation: name + ' decode', + run: () => Bytes[name].decode(encoded), + expected: bytes, + }, + ] + }) +} diff --git a/benchmark/bench.js b/benchmark/bench.js deleted file mode 100644 index a31132a..0000000 --- a/benchmark/bench.js +++ /dev/null @@ -1,123 +0,0 @@ -import { randomBytes } from 'node:crypto' -import { performance } from 'node:perf_hooks' -import { - bytesFromBase45String, - bytesToBase45String, -} from '../dist/base45/index.js' -import { - bytesFromBase64String, - bytesFromBase64UrlString, - bytesToBase64String, - bytesToBase64UrlString, -} from '../dist/base64/index.js' -import { bytesFromGzipBytes, bytesToGzipBytes } from '../dist/gzip/index.js' -import { bytesFromUTF8String, bytesToUTF8String } from '../dist/utf8/index.js' -import { - concatBytes, - deriveBytes, - equalBytes, - generateBytes, - normalizeBytes, -} from '../dist/util/index.js' - -const OPERATIONS = 5_000 -const COLUMN_SEPARATOR = ' | ' - -function measure(iterations, callback) { - const start = performance.now() - for (let index = 0; index < iterations; index++) callback() - return toStats(iterations, performance.now() - start) -} - -async function measureAsync(iterations, callback) { - const start = performance.now() - for (let index = 0; index < iterations; index++) await callback() - return toStats(iterations, performance.now() - start) -} - -function toStats(iterations, milliseconds) { - return { - ops: iterations, - ms: milliseconds, - msPerOp: milliseconds / iterations, - opsPerSec: (iterations / milliseconds) * 1_000, - } -} - -const formatInteger = (value) => Math.round(value).toLocaleString('en-US') -const formatMilliseconds = (value) => value.toFixed(3) -const formatMillisecondsPerOperation = (value) => value.toFixed(6) - -function formatResults(results) { - const columns = [ - ['benchmark', (result) => result.name], - ['ops', (result) => formatInteger(result.ops)], - ['ms', (result) => formatMilliseconds(result.ms)], - ['ms/op', (result) => formatMillisecondsPerOperation(result.msPerOp)], - ['ops/sec', (result) => formatInteger(result.opsPerSec)], - ] - const widths = columns.map(([heading, format]) => - Math.max(heading.length, ...results.map((result) => format(result).length)) - ) - const row = (values) => - values - .map((value, index) => - index === 0 - ? value.padEnd(widths[index]) - : value.padStart(widths[index]) - ) - .join(COLUMN_SEPARATOR) - - return [ - row(columns.map(([heading]) => heading)), - row(widths.map((width) => '-'.repeat(width))), - ...results.map((result) => - row(columns.map(([, format]) => format(result))) - ), - ].join('\n') -} - -console.log('Benchmarking @sovereignbase/bytecodec...') -console.log(`Operations per benchmark: ${formatInteger(OPERATIONS)}`) - -const bytes = randomBytes(64) -const differentBytes = Uint8Array.from(bytes, (value, index) => - index === bytes.length - 1 ? value ^ 1 : value -) -const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) -const text = 'caffeinated rockets at dawn ✓' -const textBytes = bytesFromUTF8String(text) -const base45 = bytesToBase45String(bytes) -const base64 = bytesToBase64String(bytes) -const base64url = bytesToBase64UrlString(bytes) -const compressed = await bytesToGzipBytes(bytes) -const results = [] - -for (const [name, callback] of [ - ['base45 encode', () => bytesToBase45String(bytes)], - ['base45 decode', () => bytesFromBase45String(base45)], - ['base64 encode', () => bytesToBase64String(bytes)], - ['base64 decode', () => bytesFromBase64String(base64)], - ['base64url encode', () => bytesToBase64UrlString(bytes)], - ['base64url decode', () => bytesFromBase64UrlString(base64url)], - ['utf8 encode', () => bytesFromUTF8String(text)], - ['utf8 decode', () => bytesToUTF8String(textBytes)], - ['normalize', () => normalizeBytes(view)], - ['concat 3 buffers', () => concatBytes([bytes, bytes, bytes])], - ['equals same', () => equalBytes(bytes, bytes)], - ['equals different', () => equalBytes(bytes, differentBytes)], - ['generate', () => generateBytes(64)], -]) { - results.push({ name, ...measure(OPERATIONS, callback) }) -} - -for (const [name, callback] of [ - ['derive HKDF', () => deriveBytes(bytes, textBytes, 32)], - ['gzip compress', () => bytesToGzipBytes(bytes)], - ['gzip decompress', () => bytesFromGzipBytes(compressed)], -]) { - results.push({ name, ...(await measureAsync(OPERATIONS, callback)) }) -} - -console.log(formatResults(results)) -console.log('Benchmark complete.') diff --git a/benchmark/gzip/workloads.mjs b/benchmark/gzip/workloads.mjs new file mode 100644 index 0000000..2fc20f9 --- /dev/null +++ b/benchmark/gzip/workloads.mjs @@ -0,0 +1,19 @@ +import { Bytes } from '../../dist/index.js' +export async function workloads({ bytes }) { + const compressed = await Bytes.gzip.encode(bytes) + return [ + { + operation: 'compress', + async: true, + run: () => Bytes.gzip.encode(bytes), + verify: async (result) => + Bytes.equals(await Bytes.gzip.decode(result), bytes), + }, + { + operation: 'decompress', + async: true, + run: () => Bytes.gzip.decode(compressed), + expected: bytes, + }, + ] +} diff --git a/benchmark/runner.mjs b/benchmark/runner.mjs new file mode 100644 index 0000000..b43d793 --- /dev/null +++ b/benchmark/runner.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +import { resolve } from 'node:path' +import { + codecs, + provenance, + root, + table, + writeJson, +} from '../scripts/reporting.mjs' +import { fixture } from './shared/fixtures.mjs' + +const selected = process.argv.slice(2) +if (selected.some((codec) => !codecs.includes(codec))) + throw new Error('Unknown codec') +const sizes = (process.env.BENCH_SIZES ?? '64,1024,16384') + .split(',') + .map(Number) +const iterations = Number(process.env.BENCH_ITERATIONS ?? 1000) +const warmup = Number(process.env.BENCH_WARMUP ?? 100) +for (const value of [...sizes, iterations, warmup]) { + if (!Number.isSafeInteger(value) || value <= 0) + throw new Error('Benchmark settings must be positive integers') +} +if (sizes.some((size) => size > 65536)) + throw new Error( + 'BENCH_SIZES must stay within the Web Crypto random quota (65536)' + ) +let sink +for (const codec of selected.length ? selected : codecs) { + const { workloads } = await import(`./${codec}/workloads.mjs`) + const results = [] + for (const size of sizes) { + for (const workload of await workloads(fixture(size))) { + const result = await workload.run() + if (workload.verify) + assert.equal(await workload.verify(result), true, workload.operation) + else assert.deepEqual(result, workload.expected, workload.operation) + if (workload.async) { + for (let i = 0; i < warmup; i++) sink = await workload.run() + } else { + for (let i = 0; i < warmup; i++) sink = workload.run() + } + const start = performance.now() + if (workload.async) { + for (let i = 0; i < iterations; i++) sink = await workload.run() + } else { + for (let i = 0; i < iterations; i++) sink = workload.run() + } + const milliseconds = performance.now() - start + results.push({ + operation: workload.operation, + size, + iterations, + milliseconds, + opsPerSec: (iterations * 1000) / milliseconds, + }) + } + } + const report = { ...provenance(), sizes, iterations, warmup, results } + writeJson(resolve(root, `benchmark/.results/${codec}.json`), report) + console.log( + codec + + '\n' + + table( + ['Operation', 'Bytes', 'Ops/sec'], + results.map((row) => [ + row.operation, + row.size, + Math.round(row.opsPerSec).toLocaleString('en-US'), + ]) + ) + ) +} +void sink diff --git a/benchmark/shared/fixtures.mjs b/benchmark/shared/fixtures.mjs new file mode 100644 index 0000000..2a83379 --- /dev/null +++ b/benchmark/shared/fixtures.mjs @@ -0,0 +1,9 @@ +export function fixture(size) { + const bytes = Uint8Array.from( + { length: size }, + (_, index) => 32 + ((index * 17) % 95) + ) + const shared = new SharedArrayBuffer(size + 8) + new Uint8Array(shared, 4, size).set(bytes) + return { bytes, sharedView: new DataView(shared, 4, size) } +} diff --git a/benchmark/utf8/workloads.mjs b/benchmark/utf8/workloads.mjs new file mode 100644 index 0000000..b72960c --- /dev/null +++ b/benchmark/utf8/workloads.mjs @@ -0,0 +1,16 @@ +import { Bytes } from '../../dist/index.js' +export function workloads({ bytes }) { + const text = Bytes.utf8.encode(bytes) + return [ + { + operation: 'encode (bytes → string)', + run: () => Bytes.utf8.encode(bytes), + expected: text, + }, + { + operation: 'decode (string → bytes)', + run: () => Bytes.utf8.decode(text), + expected: bytes, + }, + ] +} diff --git a/benchmark/util/workloads.mjs b/benchmark/util/workloads.mjs new file mode 100644 index 0000000..bcbd6c5 --- /dev/null +++ b/benchmark/util/workloads.mjs @@ -0,0 +1,42 @@ +import { Bytes } from '../../dist/index.js' +export async function workloads({ bytes, sharedView }) { + const different = bytes.slice() + different[different.length - 1] ^= 1 + const joined = new Uint8Array(bytes.length * 3) + for (let i = 0; i < 3; i++) joined.set(bytes, i * bytes.length) + const derived = await Bytes.derive(bytes, [1, 2], 32) + return [ + { + operation: 'normalize view', + run: () => Bytes.normalize(sharedView), + expected: bytes, + }, + { + operation: 'concat three', + run: () => Bytes.concat([bytes, bytes, bytes]), + expected: joined, + }, + { + operation: 'equals same', + run: () => Bytes.equals(bytes, bytes), + expected: true, + }, + { + operation: 'equals different', + run: () => Bytes.equals(bytes, different), + expected: false, + }, + { + operation: 'generate', + run: () => Bytes.generate(bytes.length), + verify: (result) => + result.length === bytes.length && result.buffer instanceof ArrayBuffer, + }, + { + operation: 'derive 32 bytes', + async: true, + run: () => Bytes.derive(bytes, [1, 2], 32), + expected: derived, + }, + ] +} diff --git a/docs/assets/navigation.js b/docs/assets/navigation.js index 7ed662a..091297d 100644 --- a/docs/assets/navigation.js +++ b/docs/assets/navigation.js @@ -1 +1 @@ -window.navigationData = "eJyVkt1ugjAUgN+l18RNg8xx6TL3AOqV8aJrj9CstKyURVn27guYSCu1lEsOX7/ze/hFGs4apegTVxAvUYRKrHOUokLSmkP1dI3Pcl1wFKEvJihKFxEiOeNUgUDpoVdcNFQbJYt192arFRNZbzzVgmgmxc3p5O1MSfwX2f6dnGK36YH7aNpxBUnsHkASTx9AEvtLTOKZkx8bQM/vFZ+a4vYkbMyhPdh0qDu4/sED7yKzhpXDNbbRaUv8aFi5bj9c5XW6ITreeqDVAL3NMkHhPOy2Cwe1e1cL4biqbgJH/vliZaRvASIpkHelpHqTFHqVvpSWyObuint+fZkvF3fmrawV8Riv/90mc0i1Pq2GM2qj0y5iv9usHl9s53Ow4zcR6jVJ71XUmnFXw4wHNUykIFg/vNLOYzCeBiko9gN+k8F4TPBdY+4X9YjHk4EAhfVITRblsQmpCsxZM6KzMcfqjv/BCJeb" \ No newline at end of file +window.navigationData = "eJyVk9FuwiAUht+F68ZNUzvXS5e5B1CvjBcM0JJR6IAu6rJ3X1oTAUFKL8WP75z/cLr7BZqcNCjBJ1Qkn4MMNFBXoAS1wC0j6ul6Pql0zUAGvijHoJxlAFWUYUk4KHdGcdZEraSol/2dtZaUH43x0HKkqeA3Z5B3KxX5X+b6N2KM3aU99962Q0WKPDyAIh8/gCKPt1jkkyA/NADDbyUbW+J2JW3MqRlcOtWd3L93IfqQxwtt/GfsTsc94seFNsvuR6i9Xuejw9ETrRYYDUs5Jic/bX+cFLcrgQQm6F1KIY0JMajUzeRSrng6W1gN3WXzNWrotqnzJjAxKn1uHvTTcXdhn19fpvPZnXktWokixuv/YZM99FYfFv7Mu9NxG7bdrBaPv4DeF2CHdyzVa5PRLWs1ZaHAlCUFRoIjqB9ufe+xmEhATCT9IXGTxURM5LuFLC4ySMRzJJxIqAd6cqiIjQtZQ0YvAzoXCzzd/h8ltLNK" \ No newline at end of file diff --git a/docs/assets/search.js b/docs/assets/search.js index b2b65d8..60394a1 100644 --- a/docs/assets/search.js +++ b/docs/assets/search.js @@ -1 +1 @@ -window.searchData = "eJytmU2P2zYQhv8LcyUcz1CWZR9TNEXPSXoRjMK1tVuhsuTK8raJsf+9IPXB4XIkU96eksgz7ztDPiQl5ibq6p+L2KY38VdeHsUWpSj3p0xsxR/7SxathBTXuhBbcaqO1yK7fGwfL/5sToWQ4lDsL5fsIrZCvMpeI46syPcmu3yuq9Mnk/alqfPyedB8upaHJq/KQZUNZ7ykOO/rrGxsmePuX6sZ3m7wTGd37OKIHbs4emjs4miy/jhasOH3O4ijIPdvdTGzgCHjnTW0UxLYvxv8PzmH9u7Fz/S3/Dz/yM8ePfrhbHZ++ZGfP+l/MLUbQT9yumpT2tSYhTmSuFl+dozy8pj96w2SeTo5SoDJoOHW2YV3GgG1tSVY6RXY8g5VeWnq66Gp6rsGH9zgCbM2iXazxGhsyx61G+Le5UQ2uEknE/dOJ20TaNaGPuznLL1Rqy7qYZdr85Tcd+mi5rjgMkoog4d9E4RfG/ew0zGr85fsvtMQ97BT9vd1X9xfsx+GuIednrMyq/dNQFck8mG3sqpP+yL/EWBHQ+f5bdawQmf3O1TH7PBzXVf1T9XRejffz46zGzZvV+Rsv1TX+jBu1/4804ZfXP3BoB/OPj2/ff2cjB79RpEJnS7bFDd1fgZ60sBZjnSc8oIZp7wIHad23xg77I0SCblXZV7wLu2eMelCQh51MfvFpImNeNSj3ycmbZygR52GLWLSyo0K8drJbt1tb+Ilqy95VYqtwIVabIQUT3lWHPXXZFuGFIfqdNLpUhyrw9X8ddeF/Zbptx0d3EZ/XAqZLiXGi3iNu51M+2Tzg3nQa9gnJhGETEEqWKwTcBLBSwQnEYVMkUtELxGdRCVkqrhSlZeonMRIyDTiHCMvMXISV0KmKy5x5SWunMRYyDTmEmMvMXYS10Kmay5x7SWuncREyDThBifxEhMncSNkuuEcN17ixgVA8wBLFgEfHnhDj8GH54cByCUINBfAMgQ+ROBSBJoNUGyyDxK4JEE0tlzAZwlcmGA1xi/4OIHLE2hKgGUYfKTAZQrWY2yATxW4WIGGBVZssk8WuGiBBgbYdQA+XeDihQYvdi2gjxe6eKHBK2GTfbzwzQZl8GLXBDJ7lIsXamCQXRXo44UuXqiJQXZVoM8XunyhRgb5ndUHDF3AMB6dZ/QBQxcw1Mwgu6TQJwxdwlAzgyza6BOGLmGomUF2i0afMHQJU5oZZPFUPmHKJUxpZpDFU/mEKZcwZc5AFk/lE6beHIOGMBZPxZyELmFKM6NYPJVPWPfIvH68ZHWTHX9tX0PSdLj1uInfu3eTZf8edBNLsb29SgGR/vPVvpGYp8NLif5N+/XXFVZKWSnVSa1mSJnLCKsGkZWDOEyn//rK9NfXwXykWUEEK4iBPbZvhKQoJEVhuMZTXZ3asb90nytEk0jOV4wjX5GM3Iw+reK1LnzRlRUNnNVeVF8AeSO5sXKbeXL6G80vDwl9uA5X7D6uiRCZYpzRaVONTTAVnKvHTW9s9cLXxaDHTu7aSs4Yu6ZipxbIngLLOXIjU0t4xiRIr7+lI0WRUYMw4loRrz0kSiqsPefOmtREmAUVpNRfChIRMncYVk4r4jdGlFTYVmS+832hhAiFId9fQZK+iAiGVWPvFokM2WgwrJZexu+LaKmw+Wovv60EaSrpzsiwBdf9Fw5pjJ4bYeNDLkNJU2S1YlhTg443QoqIqbCzp72BJH2Rgwa6McKwfa69pCOtESkMWPM7Kc75OSvyMhPbdPf6+h98UFHo"; \ No newline at end of file +window.searchData = "eJytmU1z2zYQhv8LcsUo2gVFUTqm03R6TtILR9NRJdrllCJVknKbaPzfOwC/FlqQBumebFO777tYPAAh+C7K4p9K7OO7+CvNz2KPUuTHSyL24o9jlQQbIcWtzMReXIrzLUuqj83j1Z/1JRNSnLJjVSWV2AvxKjuNMBhEvtdJ9bksLp9M2pe6TPPnXvPplp/qtMh7VWe4w0uK67FM8nooc9z9azHD2w6e6Wz3LgycvQuDRb0Lg8n6w2DlDH97BGHg5f6tzGYW0Ge8s4ZmSjzHbwf/T86+Y2fxM/0Hfp5/pFdGj344m51ffqTXT/oPR+1GkEdOV21Km+qZnyOJm+U39CjNz8m/rEnm6WSXAKNeQ/ufinNy+rksi7IXa/NaMTtoutqmqMFsA0PBpyKv6vJ2quc4fbCzJlwfsumI1xiQKs7JLHsTvsz3odPVhO8bFLy/r9WSdlZjXXx4OY7a9XHvciKvkkknE/dOJ23jadaELvazNrlRqzZqscutforedmmj5rjgOogog6dj7YVfE7fY6ZyU6cvUCm6d+rjFTsnft2P29pr90MctdnpO8qQ81h6jIpGL3fKivByz9IeHHQ2d57fbwgZH3jM/0S24/n4d2YB12Lxd0WX7pbiVp3G75uOZNu7F1b2C9cPZ55RvXz9Ho4cso+gInS7bFDd1UvH0pIGzHGmf0szRpzTz7VOzb4wdq4wSCXmryjRzuzR7xqQLCVnqYvaLSZMhYqlHt09M2lhBS536LWLSyo7y8TrIdt3t7+IlKau0yMVe4EqtdkKKpzTJzvp7e1OGFKfictHpUpyL0838emjDfkv0aUcHN9Ef10LGa4nbVbBVh4OMu2TzgXnQaQxPTCIIGYNUuNpEYCUCSwQrEYWM0ZWILBGtRCVkrFylKpaorMRAyDhwOQYsMbASN0LGG1fihiVurMRQyDh0JYYsMbQSt0LGW1filiVurcRIyDhyNSdiiZGVuBMy3rkcdyxxZwOgeYC1EwEODzzQY/Bx8+MAyCYINBfgZAg4RGBTBJoNcHIEHCSwSQLNBzhZAg4T2DSBZgScPAEHCmyiIBwvm0MFNlWwHVvlwLkCGyyIxpYdcLTAZgs0MeBcCMDxApsvXI8hjRwvtPFCg9fWmczxwocNyuAVObcoxx5l44UGL+eCQo4X2nihBgadSwo5XmjjhRoYdC4p5HihjRdqYNC9LXO80MYLNTGonMmcL7T5Qo0MOpcUcsDQBgx34/PMAUMbMKWZQed6VJwwZROmNDPoRFtxwpRNmDLvQOc+rzhh6uE1qJlBJ57K8Sa0CVOGMCeeihOmbMKUZkY58VScMGUTpjQzyomn4oQpmzClmVFOPBUnrH1kTk0vSVkn51+b01Mc95c1d/F7e6Rad8e3u1iL/f1VCtjqn6/DQco87c9S+jPt192yDFJqkFKtVDRDytyhDGoQDnKw89PpvjQmzR0mEUMihgvEmsu/QRDJYNGzYc2pmBS1IUVt/DWeyuLSTGTVfmUjmkRyvmIYcMVgUAyWKN7KjIuSkc8cuL4EY53cDXL+pBg5/T2Vl4ekPrX2V2wvGIgQ6R56LgYtVBdjE0xA9ue41XNNL1ll4Xw95+RuB8kZK6MunFMLZIOCGVNRFyNTSwas/JbI49oHMqngtya6y04iEpGJ9JvJRoR1CImSUr5Kw9U/qYlsatBt4X5UdHesRIwsSvQrqxHhAyRKyq/f5tqECSnCkvLbd7obXVINEUG/aoarWiJDdmr0q6WT4eMiWspvvpr/JQwShKGoSUG/xdb+75HMO30F+S0wcrdMGkR3Or9B9Tq8Q0RM+W1KzYUuGRfZ1hDaHvm9bZo7TzI0IqU81v5Bimt6TbI0T8Q+Pry+/gc+WDRo"; \ No newline at end of file diff --git a/docs/classes/index.BytecodecError.html b/docs/classes/index.BytecodecError.html new file mode 100644 index 0000000..01cb4cd --- /dev/null +++ b/docs/classes/index.BytecodecError.html @@ -0,0 +1,203 @@ +BytecodecError | @sovereignbase/bytecodec
+
@sovereignbase/bytecodec + +
    +
    +
    Preparing search index...
    +
    +
    +
    + +

    Class BytecodecError

    +
    +

    Error type used by the bytecodec helpers to expose a stable error code.

    +
    +
    +

    Hierarchy

    +
      +
    • Error +
        +
      • BytecodecError
    +
    +
    +
    +
    Index
    +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
      +
    • + +
      +

      Creates a new bytecodec error with a package-prefixed message.

      +
      +
      +

      Parameters

      +
        +
      • code: BytecodecErrorCode +

        Stable error code describing the failure category.

        +
      • +
      • Optionalmessage: string +

        Optional human-readable detail appended to the package prefix.

        +
      • +
      • Optionaloptions: ErrorOptions +

        Error options, including the original cause.

        +
      +

      Returns BytecodecError

    +
    + +
    +
    + +
    cause?: unknown
    +
    + + +

    Machine-readable error code for programmatic handling.

    +
    +
    + +
    message: string
    +
    + +
    name: string
    +
    + +
    stack?: string
    +
    + +
    stackTraceLimit: number
    +

    The Error.stackTraceLimit property specifies the number of stack frames +collected by a stack trace (whether generated by new Error().stack or +Error.captureStackTrace(obj)).

    +

    The default value is 10 but may be set to any valid JavaScript number. Changes +will affect any stack trace captured after the value has been changed.

    +

    If set to a non-number value, or set to a negative number, stack traces will +not capture any frames.

    +
    +
    + +
    +
    + +
      +
    • + +
      +

      Creates a .stack property on targetObject, which when accessed returns +a string representing the location in the code at which +Error.captureStackTrace() was called.

      +
      const myObject = {};
      Error.captureStackTrace(myObject);
      myObject.stack; // Similar to `new Error().stack` +
      + +

      The first line of the trace will be prefixed with +${myObject.name}: ${myObject.message}.

      +

      The optional constructorOpt argument accepts a function. If given, all frames +above constructorOpt, including constructorOpt, will be omitted from the +generated stack trace.

      +

      The constructorOpt argument is useful for hiding implementation +details of error generation from the user. For instance:

      +
      function a() {
      b();
      }

      function b() {
      c();
      }

      function c() {
      // Create an error without stack trace to avoid calculating the stack trace twice.
      const { stackTraceLimit } = Error;
      Error.stackTraceLimit = 0;
      const error = new Error();
      Error.stackTraceLimit = stackTraceLimit;

      // Capture the stack trace above function b
      Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
      throw error;
      }

      a(); +
      + +
      +
      +

      Parameters

      +
        +
      • targetObject: object
      • +
      • OptionalconstructorOpt: Function
      +

      Returns void

    +
    + +
    +
    + +
    +
    diff --git a/docs/classes/index.Bytes.html b/docs/classes/index.Bytes.html index 369288d..a108024 100644 --- a/docs/classes/index.Bytes.html +++ b/docs/classes/index.Bytes.html @@ -15,7 +15,7 @@

    Class Bytes

    Convenience wrapper around the codec functions.

    +
  • Defined in src/index.ts:28
  • @@ -56,64 +56,64 @@
    -
    base64: {
        decode: (base64String: string) => Uint8Array;
        encode: (bytes: ByteSource) => string;
    } = ...
    +
    base64: {
        decode: (base64String: string) => Uint8Array<ArrayBuffer>;
        encode: (bytes: ByteSource) => string;
    } = ...

    Type Declaration

    • -
      decode: (base64String: string) => Uint8Array
    • +
      decode: (base64String: string) => Uint8Array<ArrayBuffer>
    • encode: (bytes: ByteSource) => string
    +
  • Defined in src/index.ts:34
  • -
    base64url: {
        decode: (base64UrlString: string) => Uint8Array;
        encode: (bytes: ByteSource) => string;
    } = ...
    +
    base64url: {
        decode: (base64UrlString: string) => Uint8Array<ArrayBuffer>;
        encode: (bytes: ByteSource) => string;
    } = ...

    Type Declaration

    • -
      decode: (base64UrlString: string) => Uint8Array
    • +
      decode: (base64UrlString: string) => Uint8Array<ArrayBuffer>
    • encode: (bytes: ByteSource) => string
    +
  • Defined in src/index.ts:39
  • -
    gzip: {
        decode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBufferLike>>;
        encode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBufferLike>>;
    } = ...
    +
    gzip: {
        decode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBuffer>>;
        encode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBuffer>>;
    } = ...

    Type Declaration

    • -
      decode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBufferLike>>
    • +
      decode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBuffer>>
    • -
      encode: (bytes: ByteSource) => Promise<Uint8Array<ArrayBufferLike>>
    +
  • Defined in src/index.ts:49
  • -
    utf8: {
        decode: (text: string) => Uint8Array;
        encode: (bytes: ByteSource) => string;
    } = ...
    +
    utf8: {
        decode: (text: string) => Uint8Array<ArrayBuffer>;
        encode: (bytes: ByteSource) => string;
    } = ...

    Type Declaration

    • -
      decode: (text: string) => Uint8Array
    • +
      decode: (text: string) => Uint8Array<ArrayBuffer>
    • encode: (bytes: ByteSource) => string
    +
  • Defined in src/index.ts:44
  • @@ -121,20 +121,20 @@
    • - +

      Parameters

      -

      Returns Uint8Array

    +
  • Defined in src/index.ts:54
    • - +

      Parameters

      @@ -142,9 +142,9 @@

      Parameters

    • base: ByteSource
    • domain: ByteSource
    • byteLength: number
    -

    Returns Promise<Uint8Array<ArrayBufferLike>>

    +
  • Defined in src/index.ts:62
  • Returns boolean

    +
  • Defined in src/index.ts:58
    • - +

      Parameters

      • byteLength: number
      -

      Returns Uint8Array

    +
  • Defined in src/index.ts:70
  • +
  • Defined in src/index.ts:74
  • -

    Returns Uint8Array

    A new Uint8Array containing the decoded bytes.

    +

    Returns Uint8Array<ArrayBuffer>

    A new Uint8Array<ArrayBuffer> containing the decoded bytes.

    +
  • Defined in src/base45/index.ts:46
  • +
  • Defined in src/base45/index.ts:14
  • -

    Returns Uint8Array

    A new Uint8Array containing the decoded bytes.

    +

    Returns Uint8Array<ArrayBuffer>

    A new Uint8Array<ArrayBuffer> containing the decoded bytes.

    +
  • Defined in src/base64/index.ts:44
  • -

    Returns Uint8Array

    A new Uint8Array containing the decoded bytes.

    +

    Returns Uint8Array<ArrayBuffer>

    A new Uint8Array<ArrayBuffer> containing the decoded bytes.

    +
  • Defined in src/base64/index.ts:88
  • +
  • Defined in src/base64/index.ts:11
  • +
  • Defined in src/base64/index.ts:73
  • -

    Returns Promise<Uint8Array<ArrayBufferLike>>

    A promise that resolves to a new Uint8Array containing the decompressed bytes.

    +

    Returns Promise<Uint8Array<ArrayBuffer>>

    A promise that resolves to a new Uint8Array<ArrayBuffer> containing the decompressed bytes.

    +
  • Defined in src/gzip/index.ts:48
  • -

    Returns Promise<Uint8Array<ArrayBufferLike>>

    A promise that resolves to a new Uint8Array containing the gzip payload.

    +

    Returns Promise<Uint8Array<ArrayBuffer>>

    A promise that resolves to a new Uint8Array<ArrayBuffer> containing the gzip payload.

    +
  • Defined in src/gzip/index.ts:12
  • -

    Returns Uint8Array

    A new Uint8Array containing the UTF-8 encoded bytes.

    +

    Returns Uint8Array<ArrayBuffer>

    A new Uint8Array<ArrayBuffer> containing the UTF-8 encoded bytes.

    +
  • Defined in src/utf8/index.ts:42
  • +
  • Defined in src/utf8/index.ts:15
  • -

    Returns Uint8Array

    A new Uint8Array containing the concatenated bytes.

    +

    Returns Uint8Array<ArrayBuffer>

    A new Uint8Array<ArrayBuffer> containing the concatenated bytes.

    +
  • Defined in src/util/index.ts:10
  • -

    Returns Promise<Uint8Array<ArrayBufferLike>>

    A promise that resolves to exactly byteLength derived bytes.

    +

    Returns Promise<Uint8Array<ArrayBuffer>>

    A promise that resolves to exactly byteLength derived bytes.

    @@ -46,7 +46,7 @@
    +
  • Defined in src/util/index.ts:134
  • +
  • Defined in src/util/index.ts:55
  • +
  • Defined in src/util/index.ts:166
  • -

    Returns Uint8Array

    A new Uint8Array copy of input.

    +

    Returns Uint8Array<ArrayBuffer>

    A new Uint8Array<ArrayBuffer> copy of input.

    +
  • Defined in src/util/index.ts:74
  • @@ -30,7 +30,7 @@

    Settings

    On This Page

    A supported byte input source accepted by the codec helpers.

    +
  • Defined in src/index.ts:20
  • +
  • Defined in src/.errors/class.ts:4