npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ecson/bson

v0.2.0

Published

ECSON reference implementation: BSON type set (MongoDB Extended JSON v2 canonical forms)

Readme

@ecson/bson

The official BSON type set of ECSON (spec section 4.1): ObjectId, Binary, Decimal128, Timestamp, MinKey and MaxKey, serialized in the canonical forms of MongoDB Extended JSON v2. ECSON values with these tags can be exchanged with MongoDB tools.

The package is standard ECMAScript only. It depends on @ecson/core and does not depend on the bson or mongodb packages: it ships its own small value classes.

Install

npm install @ecson/core @ecson/bson

ESM only, Node >= 24.

Conformance

Used together with @ecson/core, an implementation conforms to Core + BSON (CONFORMANCE_DECLARE). @ecson/core has the References and Error sets on by default, so the level of a codec with BSON is Core + BSON + References + Error:

import { createCodec } from '@ecson/core';
import { bson } from '@ecson/bson';

const codec = createCodec({ types: [bson] });
codec.conformance.level; // 'Core + BSON + References + Error'

createCodec({ types: [bson], typeSets: { references: false, error: false } }).conformance.level; // 'Core + BSON'

The set is supported in whole: the six tags $oid, $binary, $numberDecimal, $timestamp, $minKey and $maxKey, plus the optional reading of the canonical MongoDB date form (BSON_READ_CANONICAL_DATE). Without the set, these tags are unknown tags and are preserved (spec section 7); applications cannot define them (TAG_RESERVED).

Usage

import { createCodec } from '@ecson/core';
import { Binary, Decimal128, MaxKey, MinKey, ObjectId, Timestamp, bson } from '@ecson/bson';

const codec = createCodec({ types: [bson] });

const text = codec.stringify({
  _id: new ObjectId('507f1f77bcf86cd799439011'),
  data: new Binary(new TextEncoder().encode('sure.'), 0),
  price: new Decimal128('9.99'),
  at: new Timestamp({ t: 1678886400, i: 1 }),
  from: new MinKey(),
  to: new MaxKey(),
});
// {"_id":{"$oid":"507f1f77bcf86cd799439011"},"data":{"$binary":{"base64":"c3VyZS4=","subType":"00"}},
//  "price":{"$numberDecimal":"9.99"},"at":{"$timestamp":{"t":1678886400,"i":1}},
//  "from":{"$minKey":1},"to":{"$maxKey":1}}

const back = codec.parse(text) as { _id: ObjectId };
back._id.toHexString(); // '507f1f77bcf86cd799439011'

codec.stringifyPlain({ _id: back._id, data: new Binary(new Uint8Array([1])) });
// {"_id":"507f1f77bcf86cd799439011","data":"AQ=="}

API

  • bson: the type set (TypeSet named bson), to pass in createCodec({ types: [bson] }).
  • ObjectId: new ObjectId(input) with 24 hexadecimal characters (any case) or 12 bytes, else TypeError. Members: bytes (12 bytes, big-endian), toHexString() (lowercase), toString(), equals(other), and ObjectId.isValid(input).
  • Binary: new Binary(bytes, subType = 0), with subType an integer from 0 to 255. Members: bytes (a copy), subType.
  • Decimal128: new Decimal128(value). Members: value (the canonical string) and toString().
  • Timestamp: new Timestamp({ t, i }), both integers from 0 to 4294967295. Members: t, i.
  • MinKey, MaxKey: classes without members; any instance is the value.

Forms

  • $oid: 24 hexadecimal characters. Written in lowercase, read in any case (BSON_HEX_CASE).
  • $binary: { "base64": "<padded Base64>", "subType": "<1 or 2 hexadecimal digits>" }. Written with two lowercase digits and the keys in this order; read with one or two digits in any case and the keys in any order. Base64 must be padded RFC 4648, with no whitespace and no non-zero padding bits.
  • $numberDecimal: the canonical Decimal128 string.
  • $timestamp: { "t": <uint32>, "i": <uint32> }.
  • $minKey, $maxKey: the number 1.
  • $date, canonical form: the reader also accepts { "$date": { "$numberLong": "<ms>" } }, an integer string within the range of an ECMAScript Date (plus or minus 8.64e15), and returns a Date. Writers never emit it: dates are always written in the core $date form (BSON_READ_CANONICAL_DATE).

Every violation of these forms fails with EcsonError code TYPEDEF_VALIDATE and rule BSON_FORMS (or BSON_READ_CANONICAL_DATE).

Plain JSON form (spec section 5.3)

  • $binary: the Base64 string.
  • $minKey, $maxKey: null.
  • Others use the default, the serialized form without the tag: $oid is the hexadecimal string, $numberDecimal the decimal string, $timestamp the object { "t", "i" }.

Decimal128 strings

Decimal128 implements the string conversions of the BSON Decimal128 specification, without rounding. The constructor accepts the "From String" syntax: an optional sign, digits with an optional fraction and an optional exponent (E or e), or NaN, Inf and Infinity in any case. value is the "To String" form of the result, which writers emit (BSON_DECIMAL_CANONICAL): 1e3 becomes 1E+3, 1000 stays 1000, -NaN becomes NaN, inf becomes Infinity.

Decimal128 holds at most 34 significant digits and exponents from -6176 to 6111. Text that would need rounding to fit is rejected with TypeError (and TYPEDEF_VALIDATE with rule BSON_DECIMAL_EXACT when read), because a lossy conversion would break the lossless round trip of ECSON. Exact adjustments are allowed: leading zeros are dropped, zero values clamp their exponent, and a coefficient with trailing zeros is padded or trimmed to bring the exponent into range, as in the specification.

Converting to and from the MongoDB driver

The classes here are not the driver classes. Convert at the boundary:

import * as mongodb from 'mongodb';
import { Binary, Decimal128, MaxKey, MinKey, ObjectId, Timestamp } from '@ecson/bson';

// ECSON to driver
new mongodb.ObjectId(oid.toHexString());
new mongodb.Binary(bin.bytes, bin.subType);
mongodb.Decimal128.fromString(d.value);
new mongodb.Timestamp({ t: ts.t, i: ts.i });
new mongodb.MinKey();
new mongodb.MaxKey();

// driver to ECSON
new ObjectId(driverOid.toHexString());
new Binary(driverBinary.buffer.subarray(0, driverBinary.position), driverBinary.sub_type);
new Decimal128(driverDecimal.toString());
new Timestamp({ t: driverTimestamp.high >>> 0, i: driverTimestamp.low >>> 0 });
new MinKey();
new MaxKey();

The canonical Extended JSON output of these tags equals EJSON.stringify(x, { relaxed: false }) of the matching driver type, apart from key order and whitespace: the $oid, $binary, $numberDecimal, $timestamp, $minKey and $maxKey forms are the same. Dates differ on purpose: ECSON writes $date in the core form (an RFC 3339 string), while canonical Extended JSON writes { "$date": { "$numberLong": "..." } }; this package reads the latter.

In a driver Timestamp, high holds the seconds (t) and low the increment (i), as signed 32-bit integers, hence >>> 0. In a driver Binary, the bytes are buffer up to position, and sub_type is the subtype. Check these members against the version of the driver you use.

Conformance vectors

conformance/vectors/bson.json holds the language independent vectors of this type set, checked by bun run conformance. The unit tests port the BSON corpus cases of the MongoDB specifications (oid, binary, decimal128-1 to 7, timestamp, minkey, maxkey, datetime).

License

Apache 2.0. Copyright 2026 Gustavo Gondim. See LICENSE.