{"name":"@peculiar/utils","version":"4.0.1","keywords":["typescript","utils","buffer","bytes","convert","encoding","base64","base64url","hex","utf8","utf16","pem","pki","peculiar"],"author":{"name":"PeculiarVentures"},"license":"MIT","_id":"@peculiar/utils@4.0.1","maintainers":[{"name":"rmhrisk","email":"ryan_hurst@hotmail.com"},{"name":"microshine","email":"microshine@mail.ru"},{"name":"yury.strozhevsky","email":"yury@strozhevsky.com"},{"name":"peculiarventures","email":"info@peculiarventures.com"},{"name":"apilguk","email":"apilguk@gmail.com"},{"name":"donskov","email":"donskovdmitriyv@gmail.com"},{"name":"worldthirteen","email":"mihailzachepilo@gmail.com"}],"contributors":[{"name":"Miroshin Stepan","email":"microshine@mail.ru"}],"homepage":"https://github.com/PeculiarVentures/pvtsutils#readme","bugs":{"url":"https://github.com/PeculiarVentures/pvtsutils/issues"},"dist":{"shasum":"6c71235d8889283535b38c2b634f9c885a9b54e6","tarball":"http://registry-npm.ywwl.com/@peculiar/utils/download/@peculiar/utils-4.0.1.tgz","fileCount":53,"integrity":"sha512-3WDWwZNyg+XsrHpJpF5qnp5EheREVezxIc/2QsOe5TjXyqPJbfwtxIyDfmGKZKQirIPIOcD+yVzci+nfAhVAdQ==","signatures":[{"sig":"MEUCIQDYJkbzTz50vhk6X7hnAxEe5oAyIYp5yChXQmfUpnQgdAIgSWNiinOtH4Rk7CzLkRp912tTMYa/heJ7hcoRVv2Yo3M=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"sig":"MEUCIQDi35fXFnuAo0eXU5Dzx4Eohr5qH1enXtcPdL632pDaBgIgIGr47v0zvEzGIdB6eSkA73dccBtRsfgsMni3r9n7pPA=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@peculiar%2futils@4.0.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":102072,"size":23511,"noattachment":false,"key":"/@peculiar/utils/-/@peculiar/utils-4.0.1.tgz"},"main":"./build/index.js","type":"module","types":"./build/index.d.ts","module":"./build/index.js","engines":{"node":"^20.19.0 || >=22.12.0"},"exports":{".":"./build/index.js","./pem":"./build/pem.js","./bytes":"./build/bytes.js","./legacy":"./build/legacy.js","./encoding":"./build/encoding.js","./converters":"./build/converters.js","./package.json":"./package.json"},"gitHead":"d51d08cba66601b7a96e7eaba797a71229d0c1e6","scripts":{"lint":"oxlint","test":"vitest run","build":"tsdown","format":"oxfmt","prepack":"npm run build","coverage":"vitest run --coverage","lint:fix":"oxlint --fix","typecheck":"tsc --noEmit","format:check":"oxfmt --check"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"479db2c2-8d82-4a22-b1eb-03495f7f23fc"}},"repository":{"url":"git+https://github.com/PeculiarVentures/pvtsutils.git","type":"git"},"_npmVersion":"11.19.0","description":"Modern byte, encoding, converter registry, and PEM utilities for TypeScript projects.","directories":{},"sideEffects":false,"_nodeVersion":"24.21.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"oxfmt":"^0.72.0","oxlint":"^1.86.0","tsdown":"^0.23.0","vitest":"^4.1.5","typescript":"^6.0.3","@vitest/coverage-v8":"^4.1.5","@arethetypeswrong/core":"^0.18.5"},"_npmOperationalInternal":{"tmp":"tmp/utils_4.0.1_1792406341657_0.3206776031139644","host":"s3://npm-registry-packages-npm-production"},"readme":"<h1 align=\"center\">\n  @peculiar/utils\n</h1>\n\n<div align=\"center\">\n\n![NPM License](https://img.shields.io/npm/l/@peculiar/utils)\n![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/PeculiarVentures/pvtsutils/publish.yml?branch=master&label=publish)\n[![npm version](https://img.shields.io/npm/v/@peculiar/utils.svg)](https://www.npmjs.com/package/@peculiar/utils)\n![Coveralls](https://img.shields.io/coverallsCoverage/github/PeculiarVentures/pvtsutils)\n[![npm downloads](https://img.shields.io/npm/dm/@peculiar/utils.svg)](https://www.npmjs.com/package/@peculiar/utils)\n\n</div>\n\nModern byte, text, converter registry, and PEM utilities for TypeScript projects.\n\nThe package is designed around a modular v2 API:\n\n- multi-entry exports for tree-shake-friendly imports;\n- `encode` and `decode` terminology;\n- an extensible runtime converter registry;\n- generic PEM helpers without PKI-specific parsing;\n- a legacy compatibility layer for historical `pvtsutils` consumers.\n\n## Install\n\n```bash\nnpm install @peculiar/utils\n```\n\n## Breaking Changes In v4\n\nv4 ships ESM only. The CommonJS build (`*.cjs` files and `require` export conditions) has been removed.\n\n- **Node.js `^20.19.0 || >=22.12.0` is required** (previously `>=16`). These versions support `require()` of ES modules, so CommonJS code can keep using `require(\"@peculiar/utils\")` without changes.\n- **TypeScript projects that compile to CommonJS** need `\"module\": \"node20\"` or `\"nodenext\"` (TypeScript 5.9+). With `\"module\": \"node16\"` the compiler reports TS1479.\n- **ESM and bundler setups** (`\"module\": \"preserve\"`, `\"moduleResolution\": \"bundler\"`) work without changes.\n- **Legacy `\"moduleResolution\": \"node\"` (node10)** resolves only the root entry through `types`. Subpath imports such as `@peculiar/utils/encoding` need one of the settings above.\n\nThe public API is unchanged; only packaging and runtime requirements changed.\n\n## Entry Points\n\n```ts\nimport { bytes } from \"@peculiar/utils\";\nimport { hex, base64, base64url } from \"@peculiar/utils/encoding\";\nimport { int, uint } from \"@peculiar/utils/integer\";\nimport { pem } from \"@peculiar/utils/pem\";\nimport { convert, createConverterRegistry, defaultConverters } from \"@peculiar/utils/converters\";\nimport { Convert } from \"@peculiar/utils/legacy\";\n```\n\n## Bytes Helpers\n\n`@peculiar/utils/bytes` stays focused on stateless byte sequence utilities. It does not include stateful readers, writers, ASN.1 parsing, PDF parsing, or other structured binary readers. For structured binary parsing, use a dedicated binary reader package.\n\n```ts\nimport { bytes } from \"@peculiar/utils\";\n\nconst offset = bytes.indexOf(new Uint8Array([0x25, 0x25, 0x45, 0x4f, 0x46]), \"%%EOF\", {\n  encoding: \"ascii\",\n});\n\nconst suffix = bytes.endsWith(new Uint8Array([0x25, 0x25, 0x45, 0x4f, 0x46]), \"%%EOF\", {\n  encoding: \"ascii\",\n});\n```\n\n### Find `startxref` In A PDF Tail\n\n```ts\nimport { lastIndexOf } from \"@peculiar/utils/bytes\";\n\nconst tailStart = Math.max(0, pdf.byteLength - 4096);\n\nconst offset = lastIndexOf(pdf, \"startxref\", {\n  encoding: \"ascii\",\n  start: pdf.byteLength,\n  end: tailStart,\n});\n\nif (offset === -1) {\n  throw new Error(\"PDF startxref marker not found\");\n}\n```\n\n### Find `startxref` Via `tail`\n\n```ts\nimport { lastIndexOf, tail } from \"@peculiar/utils/bytes\";\n\nconst pdfTail = tail(pdf, 4096);\n\nconst localOffset = lastIndexOf(pdfTail, \"startxref\", {\n  encoding: \"ascii\",\n});\n\nconst offset = localOffset === -1 ? -1 : pdf.byteLength - pdfTail.byteLength + localOffset;\n```\n\n### Check Prefixes And Suffixes\n\n```ts\nimport { bytes } from \"@peculiar/utils\";\n\nbytes.startsWith(data, \"-----BEGIN\", { encoding: \"ascii\" });\nbytes.endsWith(data, \"%%EOF\", { encoding: \"ascii\" });\n```\n\n### Compare Byte Sequences\n\n```ts\nimport { bytes } from \"@peculiar/utils\";\n\nconst result = bytes.compare(a, b);\n\nif (result === 0) {\n  console.log(\"equal\");\n}\n```\n\n## Convert API\n\nThe default `convert` facade is a convenience singleton backed by the built-in registry.\n\n```ts\nimport { convert } from \"@peculiar/utils/converters\";\n\nconst bytes = convert.decode(\"base64\", \"AQID\");\nconst text = convert.encode(\"hex\", bytes, { case: \"upper\" });\n```\n\nDeprecated `convert.to(...)` and `convert.from(...)` aliases are still available for temporary migration, but the primary v2 API is `encode` and `decode`.\n\n## Transcode\n\nDirect text-to-text transcoding goes through the registry without a manual intermediate step.\n\n```ts\nimport { convert } from \"@peculiar/utils/converters\";\nimport { hex } from \"@peculiar/utils/encoding\";\n\nconst pemText = convert.transcode(\"AQID\", {\n  from: \"base64\",\n  to: \"pem\",\n  toOptions: {\n    label: \"CERTIFICATE\",\n  },\n});\n\nconst hexText = convert.transcode(pemText, {\n  from: \"pem\",\n  fromOptions: { label: \"CERTIFICATE\" },\n  to: \"hex\",\n  toOptions: hex.formats.colonUpper,\n});\n```\n\nThere is intentionally no chain API.\n\n## Integer Codecs\n\n`@peculiar/utils/integer` converts integers to and from big-endian bytes. Both codecs accept `number` or `bigint`; `decode` returns a `number` and throws a `RangeError` outside the safe integer range, while `decodeBigInt` has no limit.\n\n```ts\nimport { int, uint } from \"@peculiar/utils/integer\";\n\nuint.encode(0x010203); // Uint8Array [1, 2, 3]\nuint.encode(0x41, { length: 4 }); // Uint8Array [0, 0, 0, 65]\nuint.encode(113549, { bitsPerByte: 7 }); // base-128 digits: Uint8Array [6, 119, 13]\nuint.decode(new Uint8Array([6, 119, 13]), { bitsPerByte: 7 }); // 113549\nuint.decodeBigInt(new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 1])); // 18446744073709551617n\n\nint.encode(128); // two's complement: Uint8Array [0, 128]\nint.encode(-129); // Uint8Array [255, 127]\nint.encode(-2, { length: 3 }); // sign-extended: Uint8Array [255, 255, 254]\nint.decode(new Uint8Array([255, 127])); // -129\nint.isMinimal(new Uint8Array([0, 127])); // false: redundant leading 0x00\n```\n\n`bitsPerByte: 7` produces the raw base-128 digits only. Set the continuation bits yourself when you need an ASN.1 OID arc or tag number.\n\n## Hex Formatting\n\nThe `hex` codec accepts common input styles and can format output explicitly.\n\n```ts\nimport { hex } from \"@peculiar/utils/encoding\";\n\nhex.decode(\"0102030405060708090a0b0c\");\nhex.decode(\"01020304 05060708 090a0b0c\");\nhex.decode(\"01:02:03:04:05:06:07:08:09:0A:0B:0C\");\nhex.decode(\"0x0102030405060708090a0b0c\");\n\nhex.encode(new Uint8Array([1, 2, 3, 4]), hex.formats.colonUpper);\nhex.encode(new Uint8Array([1, 2, 3, 4]), {\n  prefix: \"0x\",\n  group: {\n    size: 2,\n    separator: \" \",\n  },\n});\n```\n\nAvailable presets:\n\n- `hex.formats.compact`\n- `hex.formats.upper`\n- `hex.formats.colon`\n- `hex.formats.colonUpper`\n- `hex.formats.groupsOf4`\n- `hex.formats.prefixed`\n\n## Preserve Formatting\n\nUse `parse` and `format` when you want to keep the original visual style of a hex string.\n\n```ts\nimport { hex } from \"@peculiar/utils/encoding\";\n\nconst parsed = hex.parse(\"01:02:03:04:05:06\");\n\nparsed.bytes;\nparsed.format;\nparsed.normalized;\n\nconst updated = hex.format(new Uint8Array([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]), parsed.format);\n```\n\nThe same capabilities are available through the registry facade:\n\n```ts\nimport { convert } from \"@peculiar/utils/converters\";\n\nconst parsed = convert.parse(\"hex\", \"01:02:03:04\");\nconst formatted = convert.format(\"hex\", new Uint8Array([0xaa, 0xbb, 0xcc, 0xdd]), parsed.format);\n```\n\n## PEM Helpers\n\nPEM support stays generic. The package does not parse ASN.1, validate PKI semantics, or handle encrypted PEM containers.\n\n```ts\nimport { pem } from \"@peculiar/utils/pem\";\n\nconst text = pem.encode(\"CERTIFICATE\", new Uint8Array([1, 2, 3]));\nconst blocks = pem.decode(text);\nconst block = pem.find(text, \"CERTIFICATE\");\nconst matches = pem.findAll(text, \"CERTIFICATE\");\n\nconst bundle = pem.encodeMany([\n  { label: \"CERTIFICATE\", data: new Uint8Array([1, 2, 3]) },\n  { label: \"PRIVATE KEY\", data: new Uint8Array([4, 5, 6]) },\n]);\n```\n\n## Safe Decode And Detection\n\n```ts\nimport { convert } from \"@peculiar/utils/converters\";\n\nconst result = convert.tryDecode(\"hex\", \"01:02:03\");\n\nif (result.ok) {\n  console.log(result.bytes);\n} else {\n  console.error(result.error);\n}\n\nconst candidates = convert.detect(\"-----BEGIN DATA-----\\nAQID\\n-----END DATA-----\\n\", {\n  formats: [\"pem\", \"base64\", \"hex\"],\n});\n```\n\n## Custom Registries\n\nApplications can create isolated registries instead of mutating global state.\n\n```ts\nimport { createConverterRegistry, defaultConverters } from \"@peculiar/utils/converters\";\n\nconst registry = createConverterRegistry(defaultConverters);\n\nregistry.register({\n  name: \"base58btc\",\n  aliases: [\"b58\"],\n  encode(data) {\n    return base58btcEncode(data);\n  },\n  decode(text) {\n    return base58btcDecode(text);\n  },\n});\n```\n\nName and alias conflicts throw by default. Use `{ override: true }` only when replacement is intentional.\n\n## Typed Converter Options\n\nBuilt-in converters expose typed options through the registry facade.\n\n```ts\nimport { convert } from \"@peculiar/utils/converters\";\n\nconvert.encode(\"hex\", new Uint8Array([1, 2, 3]), {\n  case: \"upper\",\n});\n```\n\nWrong options are rejected by TypeScript:\n\n```ts\nconvert.encode(\"hex\", new Uint8Array([1, 2, 3]), {\n  label: \"CERTIFICATE\",\n});\n```\n\nCustom converters can extend the options map via module augmentation:\n\n```ts\ndeclare module \"@peculiar/utils/converters\" {\n  interface ConverterOptionsMap {\n    base58btc: {\n      encode: Base58EncodeOptions;\n      decode: Base58DecodeOptions;\n    };\n  }\n}\n```\n\n## Legacy Compatibility\n\nThe old `pvtsutils`-style surface is preserved under the legacy entry point.\n\n```ts\nimport { BufferSourceConverter, Convert, assign, combine, isEqual } from \"@peculiar/utils/legacy\";\n```\n\nUnlike the lenient `utf8` codec, the legacy UTF-8 helpers (`ToUtf8String`, `FromUtf8String`, and `ToString`/`FromString` with `\"utf8\"`) are strict, as in `pvtsutils` 1.x: malformed bytes and lone surrogates throw instead of being replaced with U+FFFD, and a leading BOM is preserved. The error is a `TypeError` (`pvtsutils` threw `URIError`).\n\n## Migrating From `pvutils`\n\n`pvutils` is superseded by this package. It has no compatibility layer; use the replacements below.\n\n| `pvutils`                                        | Replacement                                                                        |\n| ------------------------------------------------ | ---------------------------------------------------------------------------------- |\n| `utilToBase(value, base, reserved)`              | `uint.encode(value, { bitsPerByte: base, length: reserved })`                      |\n| `utilFromBase(data, base)`                       | `uint.decode(data, { bitsPerByte: base })` or `uint.decodeBigInt(...)`             |\n| `utilEncodeTC(value)`                            | `int.encode(value)`                                                                |\n| `utilDecodeTC.call(block)`                       | `int.decode(block.valueHex)`; `int.isMinimal(...)` for the \"Needlessly long\" check |\n| `isEqualBuffer(a, b)`                            | `bytes.equal(a, b)`                                                                |\n| `utilConcatBuf(...)` / `utilConcatView(...)`     | `bytes.concat(...)` / `bytes.concatToUint8Array([...])`                            |\n| `bufferToHexCodes(data)`                         | `hex.encode(data, { case: \"upper\" })`                                              |\n| `toBase64(arrayBufferToString(data), url, ...)`  | `base64.encode(data)` / `base64url.encode(data)`                                   |\n| `stringToArrayBuffer(fromBase64(text, url))`     | `base64.decode(text)` / `base64url.decode(text)`                                   |\n| `arrayBufferToString` / `stringToArrayBuffer`    | `binary.encode` / `binary.decode`                                                  |\n| `padNumber(value, length)`                       | `String(value).padStart(length, \"0\")`                                              |\n| `getParametersValue(params, name, defaultValue)` | `params[name] ?? defaultValue`                                                     |\n| `clearProps(object, names)`                      | `delete object[name]`                                                              |\n\nBehavior differences:\n\n- The integer codecs throw a `RangeError` for values they cannot represent. `pvutils` returned an empty buffer, and it lost precision above 2^53 (above 2^47 for negative two's complement values).\n- `base64.decode` and `base64url.decode` reject invalid text. `pvutils` decoded garbage silently and added zero bytes to unpadded input, so code that trimmed its output (for example to a power-of-two length) no longer needs to.\n- `base64url.decode` rejects `=` padding by default, which `pvutils` accepted. Pass `{ allowPadding: true }` to accept correctly padded input such as JWK values produced by tools that pad.\n- `padNumber` returned `\"\"` when the number had more digits than `length` (`padNumber(123, 2) === \"\"`), while `padStart` returns the full text (`\"123\"`). Check the length explicitly if you relied on that width check.\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, required checks, and release process.\n","publish_time":1792406341749,"_cnpm_publish_time":1792406341749,"dist-tags":{"latest":"4.1.1"}}