# ECSON: ECMAScript Object Notation

Version: 0.2.0 · Status: draft · License: Apache-2.0

Source: lingodata/ecson@fe27835

## 0. Introduction

ECSON (ECMAScript Object Notation) is a JSON-based format that preserves the JavaScript (ECMAScript) types JSON cannot express, such as [dates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), [big integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), [special numbers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), [sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), [maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [binary data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). It is part of the **LingoData** family of specifications for data interoperability.

### 0.1 Motivation

JSON has 6 types. JavaScript has dozens. Every attempt to bridge this gap makes a different trade-off:

- **[MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/)**: inline `$`-prefixed types, but closed to extension and tied to BSON.
- **[Meteor EJSON](https://docs.meteor.com/api/ejson.html)**: extensible, but diverges from MongoDB Extended JSON and is incomplete for native JavaScript types.
- **[Superjson](https://github.com/ravionhq/superjson)**: covers native JavaScript types and is extensible, but stores type metadata in a separate envelope.

ECSON combines their strengths:

- inline `$`-prefixed typed values, without a separate envelope;
- full coverage of native JavaScript types, including special numbers (`$number`) and Temporal;
- formal extension through type sets and namespaced application tags;
- exact compatibility with MongoDB Extended JSON through the BSON type set;
- an encoding that does not depend on which types each side knows, so data can pass through any intermediary unchanged;
- output that is always valid JSON, with [JSON5](https://spec.json5.org/) accepted as input.

### 0.2 Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.

Normative rules are identified by a code (for example [`ESCAPE_SERIALIZE`](#ESCAPE_SERIALIZE)). Notes, examples and rationales are informative.

### 0.3 Terminology

- **Typed value**: a JSON object with a single key starting with a single `$` ([section 1](#1-typed-values)).
- **Tag**: the key of a typed value, such as `$date`.
- **Plain object**: any JSON object that is not a typed value. On the host side, the object that serializes to it: in ECMAScript, an object whose prototype is `Object.prototype` or `null` ([section 5.5](#55-values-outside-the-model)).
- **Type set**: a named group of tags and their serialized forms (sections 3 and 4).
- **Writer** and **reader**: an implementation when serializing and when deserializing, respectively.

## 1. Typed values

ECSON represents values that JSON cannot express natively (dates, big integers, sets, maps, binary data and others) as **typed values**: small JSON objects whose single key names the type.

### 1.1 Output format

<a id="OUTPUT_JSON"></a>**Rule `OUTPUT_JSON`**: MUST

Every ECSON serialization MUST be a valid JSON text as defined in [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259).

### 1.2 Definition

<a id="TYPED_VALUE"></a>**Rule `TYPED_VALUE`**: MUST

A JSON object with exactly one key, where that key starts with a single `$` (and not with `$$`), MUST be interpreted as a typed value. The key is the **tag** and its value is the serialized form of the type.

<a id="TYPED_PLAIN_OTHERWISE"></a>**Rule `TYPED_PLAIN_OTHERWISE`**: MUST

Any other JSON object (with zero or more than one key, or whose single key does not start with a single `$`) MUST be interpreted as a plain object, never as a typed value.

> **Tip (non-normative): Example**
>
> | JSON | Interpretation |
> |---|---|
> | `{ "$date": "2024-01-15T00:00:00.000Z" }` | typed value, tag `$date` |
> | `{ "$date": "2024-01-15T00:00:00.000Z", "x": 1 }` | plain object with keys `$date` (escaped on output, see [section 2](#2-escape-convention)) and `x` |
> | `{ "$$date": "text" }` | escaped plain object with key `$date` (see [section 2](#2-escape-convention)) |
> | `{ "date": "2024-01-15" }` | plain object |

### 1.3 Recursion

<a id="RECURSION"></a>**Rule `RECURSION`**: MUST

Serialization and deserialization MUST be recursive: typed values MAY contain other typed values and plain objects, and the escape convention ([section 2](#2-escape-convention)) MUST be applied to every plain object at any depth, including plain objects inside typed values.

> **Tip (non-normative): Example**
>
> ```json
> {
>   "$map": [
>     ["createdAt", { "$date": "2024-01-15T00:00:00.000Z" }],
>     ["tags",      { "$set": ["a", "b"] }],
>     ["meta",      { "$$source": "import" }]
>   ]
> }
> ```

### 1.4 Key order and canonical form

<a id="KEY_ORDER_PRESERVE"></a>**Rule `KEY_ORDER_PRESERVE`**: MUST

When serializing a plain object, an implementation MUST emit its keys in the enumeration order of the source object in the host language.

<a id="CANONICAL_JCS"></a>**Rule `CANONICAL_JCS`**: MAY

An implementation MAY offer a canonical serialization mode. In canonical mode, the output MUST follow the JSON Canonicalization Scheme (JCS) defined in [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785), applied after ECSON serialization, and MUST fail for strings, including object keys, with lone UTF-16 surrogates, which RFC 8785 does not allow.

## 2. Escape convention

Plain objects in user data may contain keys starting with `$`. To keep them distinguishable from typed values, ECSON escapes every such key, regardless of which tags are registered.

<a id="ESCAPE_SERIALIZE"></a>**Rule `ESCAPE_SERIALIZE`**: MUST

When serializing a plain object, every key starting with `$` MUST be prefixed with an additional `$`.

<a id="ESCAPE_DESERIALIZE"></a>**Rule `ESCAPE_DESERIALIZE`**: MUST

When deserializing a plain object, every key starting with `$$` MUST have one leading `$` removed.

<a id="ESCAPE_NOT_TYPED"></a>**Rule `ESCAPE_NOT_TYPED`**: MUST

An object whose single key starts with `$$` MUST be treated as an escaped plain object, never as a typed value.

<a id="DUPLICATE_KEYS"></a>**Rule `DUPLICATE_KEYS`**: MUST

When a JSON object has the same key more than once, the last one MUST be used, as ECMAScript `JSON.parse` does. This happens before [`TYPED_VALUE`](#TYPED_VALUE) and [`TYPED_PLAIN_OTHERWISE`](#TYPED_PLAIN_OTHERWISE) count the keys, so `{ "$date": 0, "$date": 1 }` is a typed value with the form `1`.

<a id="ESCAPE_COLLISION"></a>**Rule `ESCAPE_COLLISION`**: MUST

When two keys of a plain object become equal after removing the escape (such as `$$a` and `$a`), deserialization MUST fail.

<a id="PROTO_OWN_PROPERTY"></a>**Rule `PROTO_OWN_PROPERTY`**: MUST

In hosts where the key `__proto__` sets the prototype of an object, such as ECMAScript, a deserialized key `__proto__` MUST become an own property, never the prototype.

> **Tip (non-normative): Example**
>
> | Value | Serialized |
> |---|---|
> | `{ "$price": 10 }` (plain object) | `{ "$$price": 10 }` |
> | `{ "$$price": 10 }` (plain object) | `{ "$$$price": 10 }` |
> | `{ "$price": 10, "name": "x" }` (plain object) | `{ "$$price": 10, "name": "x" }` |
> | `new Date(0)` (typed value) | `{ "$date": "1970-01-01T00:00:00.000Z" }` |

## 3. Built-in types

Built-in types are the native JavaScript types that every full ECSON implementation supports. They form the **core type set**. Other types are added through extension type sets ([section 4](#4-extension-type-sets)).

Each built-in type has a single serialized form, except where a type explicitly defines alternatives (such as `$date`). There are no global serialization modes.

### 3.1 `$date`

Represents a `Date` object.

<a id="TYPE_DATE_STRING"></a>**Rule `TYPE_DATE_STRING`**: SHOULD

A valid date SHOULD be serialized as a string in the [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339) format, in UTC, with millisecond precision and the `Z` suffix (`YYYY-MM-DDTHH:mm:ss.sssZ`).

<a id="TYPE_DATE_EPOCH"></a>**Rule `TYPE_DATE_EPOCH`**: MAY

A valid date MAY be serialized as an integer number of milliseconds since the [Unix epoch](https://tc39.es/ecma262/#sec-time-values-and-time-range).

<a id="TYPE_DATE_EPOCH_RANGE"></a>**Rule `TYPE_DATE_EPOCH_RANGE`**: MUST

A valid date whose year is outside the range 0000 to 9999 MUST be serialized as an integer number of milliseconds since the Unix epoch, because RFC 3339 cannot represent it.

<a id="TYPE_DATE_READ"></a>**Rule `TYPE_DATE_READ`**: MUST

When deserializing `$date`, an implementation MUST accept both the RFC 3339 string form and the integer epoch form.

<a id="TYPE_DATE_READ_STRICT"></a>**Rule `TYPE_DATE_READ_STRICT`**: MUST

When deserializing `$date`, the string form MUST follow the `date-time` production of RFC 3339, section 5.6, with these differences: a leap second (`:60`) MUST fail, and fractions longer than milliseconds MUST be truncated, not rounded. Any UTC offset is accepted, and `t` and `z` are accepted in lowercase. A space instead of `T`, an epoch that is not an integer, and an epoch outside plus or minus 8.64e15 milliseconds (the ECMAScript time range) MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).

<a id="TYPE_DATE_INVALID"></a>**Rule `TYPE_DATE_INVALID`**: MUST

An invalid date (a `Date` whose time value is `NaN`) MUST be serialized as `{ "$date": null }`, and `{ "$date": null }` MUST be deserialized as an invalid date.

> **Tip (non-normative): Example**
>
> ```json
> { "$date": "2024-01-15T00:00:00.000Z" }
> { "$date": 1705276800000 }
> { "$date": 8640000000000000 }
> { "$date": null }
> ```
> The third value is the largest JavaScript date (year 275760), which only the epoch form can represent.

### 3.2 `$bigint`

Represents a `BigInt` value.

<a id="TYPE_BIGINT"></a>**Rule `TYPE_BIGINT`**: MUST

A `BigInt` MUST be serialized as a string of decimal digits, with an optional leading `-`, no leading `+` and no leading zeros (the value zero is `"0"`).

> **Tip (non-normative): Example**
>
> `{ "$bigint": "9007199254740993" }`, `{ "$bigint": "-42" }`, `{ "$bigint": "0" }`

> **Note (non-normative): Rationale**
>
> A string is used instead of a JSON number because JSON parsers commonly convert numbers to IEEE 754 doubles, which lose precision beyond 2^53: only integers in the range [-(2^53)+1, (2^53)-1] are interoperable ([RFC 8259, section 6](https://www.rfc-editor.org/rfc/rfc8259#section-6)), and I-JSON recommends encoding larger integers as JSON strings ([RFC 7493, section 2.2](https://www.rfc-editor.org/rfc/rfc7493#section-2.2)).

### 3.3 `$number`

Represents the IEEE 754 values that JSON cannot express.

<a id="TYPE_NUMBER_SPECIAL"></a>**Rule `TYPE_NUMBER_SPECIAL`**: MUST

The number values `NaN`, `Infinity`, `-Infinity` and negative zero MUST be serialized as `{ "$number": "NaN" }`, `{ "$number": "Infinity" }`, `{ "$number": "-Infinity" }` and `{ "$number": "-0" }`, respectively.

<a id="TYPE_NUMBER_PLAIN"></a>**Rule `TYPE_NUMBER_PLAIN`**: MUST

All other number values MUST be serialized as plain JSON numbers, never as `$number`.

<a id="TYPE_NUMBER_ZERO_READ"></a>**Rule `TYPE_NUMBER_ZERO_READ`**: MUST

When deserializing ECSON or reading the plain JSON form, a JSON or JSON5 number that converts to an IEEE 754 double equal to zero MUST be read as positive zero, including `-0`, `-0.0`, `-1e-400` and, in JSON5, `-0x0`. Negative zero is only read from `{ "$number": "-0" }`.

> **Note (non-normative)**
>
> [`TYPE_NUMBER_ZERO_READ`](#TYPE_NUMBER_ZERO_READ) deliberately differs from ECMAScript `JSON.parse`, which returns negative zero for `-0` and for negative numbers that round to zero, such as `-1e-400`. ECSON writers never emit these numbers: negative zero is written as `{ "$number": "-0" }` ([`TYPE_NUMBER_SPECIAL`](#TYPE_NUMBER_SPECIAL)).

> **Note (non-normative)**
>
> Scientific notation (for example `1e300` or `1.5E-7`) is already part of the JSON number grammar (RFC 8259, section 6) and needs no typed value.

> **Note (non-normative): Rationale**
>
> `JSON.stringify` turns `NaN` and `Infinity` into `null` and `-0` into `0`, silently changing the data. MongoDB Extended JSON solves the same problem with `$numberDouble`.

### 3.4 `$undefined`

Represents `undefined`, including inside objects and arrays, where `JSON.stringify` would drop the property or replace the element with `null`.

<a id="TYPE_UNDEFINED"></a>**Rule `TYPE_UNDEFINED`**: MUST

`undefined` MUST be serialized as `{ "$undefined": true }`.

> **Tip (non-normative): Example**
>
> `{ "a": undefined, "list": [1, undefined] }` serializes as `{ "a": { "$undefined": true }, "list": [1, { "$undefined": true }] }`.

### 3.5 `$regexp`

Represents a `RegExp` object.

<a id="TYPE_REGEXP"></a>**Rule `TYPE_REGEXP`**: MUST

A `RegExp` MUST be serialized as an object with a `source` string, using the ECMAScript regular expression syntax, and a `flags` string containing only the characters `d`, `g`, `i`, `m`, `s`, `u`, `v` and `y`.

<a id="TYPE_REGEXP_VALID"></a>**Rule `TYPE_REGEXP_VALID`**: MUST

When deserializing, a `$regexp` value whose `flags` repeat a character, or whose `source` and `flags` are rejected by ECMAScript (for example both `u` and `v`, or a `source` with an unbalanced `(`), MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)), also under [`TYPE_REGEXP_OPAQUE`](#TYPE_REGEXP_OPAQUE).

<a id="TYPE_REGEXP_OPAQUE"></a>**Rule `TYPE_REGEXP_OPAQUE`**: MAY

An implementation whose host language cannot represent ECMAScript regular expressions MAY keep `$regexp` values as opaque values, without compiling `source`. It still validates `source` and `flags` against the ECMAScript syntax ([`TYPE_REGEXP_VALID`](#TYPE_REGEXP_VALID)), so that every reader accepts the same values.

> **Tip (non-normative): Example**
>
> `{ "$regexp": { "source": "^foo", "flags": "i" } }`

### 3.6 `$symbol`

Represents a `Symbol`.

<a id="TYPE_SYMBOL_UNIQUE"></a>**Rule `TYPE_SYMBOL_UNIQUE`**: MUST

A symbol that is not in the global symbol registry MUST be serialized as a string with its description (`""` when it has none), and MUST be deserialized as a new symbol with that description.

<a id="TYPE_SYMBOL_REGISTERED"></a>**Rule `TYPE_SYMBOL_REGISTERED`**: MUST

A symbol in the global symbol registry MUST be serialized as an object `{ "for": key }`, where `key` is its registry key, and MUST be deserialized as the registered symbol for that key (`Symbol.for(key)`).

<a id="TYPE_SYMBOL_WELL_KNOWN"></a>**Rule `TYPE_SYMBOL_WELL_KNOWN`**: MUST

Serializing a well-known symbol (such as `Symbol.iterator`) MUST fail.

> **Tip (non-normative): Example**
>
> | Value | Serialized |
> |---|---|
> | `Symbol("id")` | `{ "$symbol": "id" }` |
> | `Symbol()` | `{ "$symbol": "" }` |
> | `Symbol.for("app.key")` | `{ "$symbol": { "for": "app.key" } }` |

### 3.7 `$set`

Represents a `Set`.

<a id="TYPE_SET"></a>**Rule `TYPE_SET`**: MUST

A `Set` MUST be serialized as an array of its values, serialized recursively, in iteration order. Deserialization MUST preserve that order.

> **Tip (non-normative): Example**
>
> `{ "$set": ["a", "b", { "$date": "2024-01-15T00:00:00.000Z" }] }`

### 3.8 `$map`

Represents a `Map`.

<a id="TYPE_MAP"></a>**Rule `TYPE_MAP`**: MUST

A `Map` MUST be serialized as an array of `[key, value]` pairs, both serialized recursively, in iteration order. Keys MAY be any ECSON value. Deserialization MUST preserve that order.

<a id="TYPE_SET_MAP_DUPLICATES"></a>**Rule `TYPE_SET_MAP_DUPLICATES`**: MUST

When deserializing, a `$set` with two equal values, or a `$map` with two equal keys, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). Equality is ECMAScript `SameValueZero` on the deserialized values: primitives compare by value (`$bigint`, `$undefined`, numbers, where `NaN` equals `NaN` and `-0` equals `0`, strings, booleans, `null`, and registered symbols with the same key), while objects (plain objects, arrays and every other typed value, such as `$date`, `$regexp`, `$set` and Temporal types) and unique symbols are never equal to each other.

> **Tip (non-normative): Example**
>
> `{ "$map": [["key", 42], [{ "$date": "2024-01-15T00:00:00.000Z" }, "a date key"], [{ "id": 1 }, "an object key"]] }`
>
> `{ "$set": [{ "$date": 0 }, { "$date": 0 }] }` is valid: the two dates are distinct objects. `{ "$set": [1, 1] }`, `{ "$set": [0, { "$number": "-0" }] }` and `{ "$set": [{ "$bigint": "1" }, { "$bigint": "1" }] }` fail.

> **Note (non-normative)**
>
> An implementation that keeps Temporal values as opaque strings ([`TYPE_TEMPORAL_OPAQUE`](#TYPE_TEMPORAL_OPAQUE)) still treats them as distinct objects, so that its result does not depend on the host.

### 3.9 `$bytes`

Represents binary data: `ArrayBuffer`, Node.js `Buffer` and the typed array family.

<a id="TYPE_BYTES"></a>**Rule `TYPE_BYTES`**: MUST

Binary data MUST be serialized as an object with a `type` string and a `data` string containing the bytes in Base64, as defined in [RFC 4648, section 4](https://www.rfc-editor.org/rfc/rfc4648#section-4), with padding.

<a id="TYPE_BYTES_VALID"></a>**Rule `TYPE_BYTES_VALID`**: MUST

A `$bytes` value whose `data` is not Base64 with padding (without spaces, and with zero padding bits), or whose number of bytes is not a multiple of the element size of its `type`, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).

<a id="TYPE_BYTES_TYPES"></a>**Rule `TYPE_BYTES_TYPES`**: MUST

`type` MUST be one of `ArrayBuffer`, `Buffer`, `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `Float16Array`, `Float32Array`, `Float64Array`, `BigInt64Array` or `BigUint64Array`.

<a id="TYPE_BYTES_LITTLE_ENDIAN"></a>**Rule `TYPE_BYTES_LITTLE_ENDIAN`**: MUST

Typed arrays with elements larger than one byte MUST be serialized with each element in little-endian byte order, regardless of the host platform.

<a id="TYPE_BYTES_FALLBACK"></a>**Rule `TYPE_BYTES_FALLBACK`**: MAY

An implementation that cannot represent the given `type` MAY deserialize the value as a plain byte sequence (for example, `Buffer` as `Uint8Array` outside Node.js).

> **Tip (non-normative): Example**
>
> ```json
> { "$bytes": { "type": "Uint8Array",   "data": "c3VyZS4=" } }
> { "$bytes": { "type": "Float32Array", "data": "AACAPw==" } }
> ```
> The second value is `new Float32Array([1])`, whose bytes are `00 00 80 3F` in little-endian order.

> **Note (non-normative): Rationale**
>
> Typed arrays use the byte order of the host platform. Without a fixed byte order, the same `Float32Array` would serialize to different bytes on different machines.
>
> `$binary` is intentionally not used as a tag here, to avoid collision with the MongoDB Extended JSON `$binary`, which carries BSON subtype semantics. BSON binary data is covered by the BSON type set ([section 4](#4-extension-type-sets)).

### 3.10 Temporal types

Represent the [ECMAScript Temporal](https://tc39.es/proposal-temporal/) types, part of ECMAScript since ES2026.

<a id="TYPE_TEMPORAL"></a>**Rule `TYPE_TEMPORAL`**: MUST

Temporal values MUST be serialized as strings, using the tag for their type from the table below and the string format that ECMAScript Temporal's `toString()` produces with default options, which follows [RFC 9557](https://www.rfc-editor.org/rfc/rfc9557).

| Temporal type | Tag | Example |
|---|---|---|
| `Temporal.Instant` | `$instant` | `{ "$instant": "2024-01-15T00:00:00Z" }` |
| `Temporal.ZonedDateTime` | `$zoneddatetime` | `{ "$zoneddatetime": "2024-01-15T12:30:00-03:00[America/Sao_Paulo]" }` |
| `Temporal.PlainDateTime` | `$plaindatetime` | `{ "$plaindatetime": "2024-01-15T12:30:00" }` |
| `Temporal.PlainDate` | `$plaindate` | `{ "$plaindate": "2024-01-15" }` |
| `Temporal.PlainTime` | `$plaintime` | `{ "$plaintime": "12:30:00" }` |
| `Temporal.PlainYearMonth` | `$plainyearmonth` | `{ "$plainyearmonth": "2024-01" }` |
| `Temporal.PlainMonthDay` | `$plainmonthday` | `{ "$plainmonthday": "01-15" }` |
| `Temporal.Duration` | `$duration` | `{ "$duration": "P1Y2M3DT4H5M6S" }` |

> **Tip (non-normative): Example: canonical strings**
>
> | Tag | Accepted | Rejected |
> |---|---|---|
> | `$instant` | `2024-01-15T00:00:00Z`, `2024-01-15T00:00:00.5Z` | `2024-01-15T00:00:00.000Z`, `2024-01-15T00:00:00.500Z`, `2024-01-15T00:00:00+00:00` |
> | `$plaindate` | `2024-01-15`, `2024-01-15[u-ca=hebrew]` | `20240115`, `2024-01-15[u-ca=iso8601]` |
> | `$plainyearmonth` | `2024-01` | `2024-01-01`, `2024-01[u-ca=iso8601]` |
> | `$duration` | `PT0S`, `PT1.5S` | `P0D`, `PT1.50S` |

<a id="TYPE_TEMPORAL_OPAQUE"></a>**Rule `TYPE_TEMPORAL_OPAQUE`**: MAY

An implementation whose host language has no equivalent for a Temporal type MAY keep its value as an opaque string.

<a id="TYPE_TEMPORAL_SYNTAX"></a>**Rule `TYPE_TEMPORAL_SYNTAX`**: MUST

When deserializing, a Temporal string MUST be a string that `toString()` with default options can produce for its type, whether the implementation has native Temporal or keeps opaque strings. Other strings that `Temporal.*.from()` accepts, such as `20240115` for a `$plaindate` or `2024-01-15T00:00:00.000Z` for an `$instant`, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).

<a id="TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY"></a>**Rule `TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY`**: MUST

`$plainyearmonth` and `$plainmonthday` values MUST use the ISO 8601 calendar. Serialization MUST fail for values in other calendars, and deserialization MUST fail for strings with any calendar annotation, including `[u-ca=iso8601]`, which `toString()` never writes.

> **Note (non-normative): Rationale**
>
> For these two types in a non-ISO calendar, `toString()` writes a reference ISO day (`$plainyearmonth`, for example `2024-01-11[u-ca=hebrew]`) or a reference ISO year (`$plainmonthday`, for example `1972-09-22[u-ca=chinese]`) computed by the calendar, which an implementation that keeps Temporal values as opaque strings cannot compute. Restricting them to the ISO calendar keeps the round trip identical in every implementation. Other Temporal types keep any calendar.

> **Note (non-normative)**
>
> Non-ISO calendars appear as an annotation, for example `2024-01-15[u-ca=hebrew]` (except for `$plainyearmonth` and `$plainmonthday`, see [`TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY`](#TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY)). Values keep the full precision of Temporal (up to nanoseconds).

## 4. Extension type sets

A **type set** is a named group of tags with their serialized forms. The core type set ([section 3](#3-built-in-types)) contains the native JavaScript types. **Official extension type sets**, defined in this section, cover types from other ecosystems and native types that are not in the core type set, such as errors. Implementations decide how to package each set.

<a id="TYPESET_OPTIONAL"></a>**Rule `TYPESET_OPTIONAL`**: MAY

An implementation MAY support any official extension type set, in whole. Partial support of a set is not compliant with that set.

### 4.1 BSON type set

Covers the BSON types used by MongoDB that are not native JavaScript types. Its forms are identical to [MongoDB Extended JSON v2](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md), so that ECSON values can be exchanged with MongoDB tools.

<a id="BSON_FORMS"></a>**Rule `BSON_FORMS`**: MUST

The BSON type set MUST use the tags and forms in the table below, which are identical to the [canonical format](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md) of MongoDB Extended JSON v2.

| BSON type | Form |
|---|---|
| ObjectId | `{ "$oid": "507f1f77bcf86cd799439011" }`: 24 hexadecimal characters, big-endian bytes |
| Binary | `{ "$binary": { "base64": "c3VyZS4=", "subType": "00" } }`: Base64 with padding, subtype as a 1 or 2 digit hexadecimal string |
| Decimal128 | `{ "$numberDecimal": "9.99" }` |
| Timestamp | `{ "$timestamp": { "t": 1678886400, "i": 1 } }`: non-negative integers |
| MinKey | `{ "$minKey": 1 }` |
| MaxKey | `{ "$maxKey": 1 }` |

<a id="BSON_HEX_CASE"></a>**Rule `BSON_HEX_CASE`**: MUST

Writers MUST emit hexadecimal strings (`$oid`, `subType`) in lowercase, and readers MUST accept them in any case.

<a id="BSON_DECIMAL_EXACT"></a>**Rule `BSON_DECIMAL_EXACT`**: MUST

When deserializing, a `$numberDecimal` string MUST follow the string syntax of the [MongoDB Decimal128 specification](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.md) (`e` or `E` for the exponent; `Inf`, `Infinity` and `NaN` in any case) and MUST represent a Decimal128 exactly: clamping and rounding that do not change the value are allowed, and a string that needs inexact rounding, overflows or underflows MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).

<a id="BSON_DECIMAL_CANONICAL"></a>**Rule `BSON_DECIMAL_CANONICAL`**: MUST

Writers MUST emit the canonical Decimal128 string of the MongoDB Decimal128 specification (for example, `1e3` is written as `1E+3`).

<a id="BSON_READ_CANONICAL_DATE"></a>**Rule `BSON_READ_CANONICAL_DATE`**: MAY

A reader that supports the BSON type set MAY also accept the MongoDB canonical date form `{ "$date": { "$numberLong": "<milliseconds>" } }` when deserializing. Writers MUST NOT emit it: dates are always written in the core `$date` form ([section 3.1](#31-date)).

> **Note (non-normative)**
>
> Other MongoDB Extended JSON tags, such as `$numberLong`, `$numberInt` and `$numberDouble`, are not part of the BSON type set: in ECSON they are covered by plain JSON numbers, `$bigint` and `$number`. A reader without support for them preserves them as unknown tags ([section 7](#7-unknown-tags)).

### 4.2 References type set

Covers references from one value to another resource: links to anything addressable by a URI, and references to resources in the same data source.

<a id="REF_TAG"></a>**Rule `REF_TAG`**: MUST

The References type set MUST use the tag `$rel`, whose value is one of the forms in the table below, or `null` for an empty reference: a single reference that points to nothing.

| Form | Value | Example |
|---|---|---|
| URI | a string with a URI ([RFC 3986, section 3](https://www.rfc-editor.org/rfc/rfc3986#section-3)), either a URL or a URN, with an optional fragment | `{ "$rel": "urn:isbn:9780262033848" }` |
| Link header | a string with the value of an HTTP `Link` header field ([RFC 8288, section 3](https://www.rfc-editor.org/rfc/rfc8288#section-3)), with one or more links | `{ "$rel": "<https://api.example.com/users/42>; rel=\"author\", <https://api.example.com/users/7>; rel=\"editor\"" }` |
| Link object | an object with an `href` URI string and, optionally, `rel` and the target attributes of [RFC 9264, section 4.2](https://www.rfc-editor.org/rfc/rfc9264#section-4.2) (`type`, `title`, `hreflang` and others) | `{ "$rel": { "href": "https://api.example.com/users/42", "rel": "author", "type": "application/vnd.ecson+json", "title": "Ana", "hreflang": ["pt-BR"] } }` |
| Collection object | an object with a `collection` name and either an `id` or an `ids` array | `{ "$rel": { "collection": "tags", "ids": ["promo", "delivery"] } }` |
| Array | an array of URI strings, link objects and collection objects, for several references | `{ "$rel": ["https://example.com/a", { "href": "https://example.com/b", "rel": "related" }, { "collection": "products", "id": "p1" }] }` |

<a id="REF_STRING_FORMS"></a>**Rule `REF_STRING_FORMS`**: MUST

A string value starting with `<` MUST be interpreted as a Link header value; any other string MUST be interpreted as a URI ([RFC 3986, section 3](https://www.rfc-editor.org/rfc/rfc3986#section-3)). A string that is not a URI, such as a relative reference (`/users/42`) or the empty string, makes the value malformed.

<a id="REF_OBJECT_FORMS"></a>**Rule `REF_OBJECT_FORMS`**: MUST

An object value with an `href` member MUST be interpreted as a link object, and an object value with a `collection` member as a collection object. An object with both, or with neither, is malformed.

<a id="REF_ARRAY"></a>**Rule `REF_ARRAY`**: MUST

An array value MUST contain only URI strings, link objects and collection objects, in any combination; it MUST NOT contain Link header strings, which already represent several links, nor nested arrays.

<a id="REF_EMPTY"></a>**Rule `REF_EMPTY`**: MUST

An empty array value and a collection object with an empty `ids` array MUST be accepted as zero references: a list that has no references, which is not the same as `null`, the empty reference of [`REF_TAG`](#REF_TAG). With an empty `ids`, `data`, when present, is an empty array.

<a id="REF_COLLECTION_ID"></a>**Rule `REF_COLLECTION_ID`**: MUST

The `id` of a collection object, and each element of `ids`, MUST be an ECSON value other than `null`, `$undefined`, a boolean, an array or a plain object, such as a string, a number, a `$bigint` or an `$oid`. Other values make the collection object malformed.

<a id="REF_LINK_ATTRIBUTES"></a>**Rule `REF_LINK_ATTRIBUTES`**: MUST

The members of a link object MUST have the JSON types of RFC 9264, section 4.2: `href`, `rel`, `title`, `type` and `media` are strings; attributes whose name ends with `*` are arrays of objects with a `value` string, an optional `language` string and no other members; `hreflang` and the other attributes, including extension attributes, are arrays of strings. Other types make the link object malformed.

<a id="REF_COLLECTION_DATA"></a>**Rule `REF_COLLECTION_DATA`**: MAY

A collection object MAY include a `data` member with a snapshot of the referenced data: an object (or `null`, when not found) for `id`, or an array in the same order as `ids`. The `data` member is not part of the reference: writers that store references MUST ignore it.

> **Tip (non-normative): Example: several references**
>
> | Case | Value |
> |---|---|
> | several Resources of one Collection | `{ "$rel": { "collection": "tags", "ids": ["promo", "delivery"] } }` |
> | several links in one string | `{ "$rel": "<https://example.com/u/42>; rel=\"author\", <https://example.com/u/7>; rel=\"editor\"" }` |
> | several links as objects | `{ "$rel": [{ "href": "https://example.com/u/42", "rel": "author" }, { "href": "https://example.com/u/7", "rel": "editor" }] }` |
> | Resources of different Collections | `{ "$rel": [{ "collection": "products", "id": "p1" }, { "collection": "services", "id": "s9" }] }` |

<a id="REF_COLLECTION_SAME_SOURCE"></a>**Rule `REF_COLLECTION_SAME_SOURCE`**: MUST

A collection object MUST refer to Resources stored in the same data source as the value that contains it. References to anything else MUST use a URI, Link header or link object form.

> **Note (non-normative)**
>
> The link object follows the JSON link target object of RFC 9264, with one addition and two restrictions. The addition is an optional `rel` member, a registered relation type name or a URI, because a single reference has no enclosing link context object to carry the relation type. The restrictions: `href` is a URI, not a relative reference (RFC 9264 only says it SHOULD NOT be one), because a value has no base URI to resolve it against; and the objects of attributes ending with `*` have no members other than `value` and `language`.

> **Note (non-normative): Rationale**
>
> The URI and Link header forms reuse existing standards for links, including the IANA link relations registry, so references to external resources need no new vocabulary. The collection object covers the common case of references inside the same data source, which a Provider can resolve without network access.

### 4.3 Error type set

Covers ECMAScript error objects.

<a id="ERROR_FORM"></a>**Rule `ERROR_FORM`**: MUST

An error MUST be serialized under the tag `$error` as an object with a `name` string and a `message` string, and MAY include `cause` (any ECSON value), `errors` (an array of ECSON values, for `AggregateError` and for any other error whose own `errors` property is an array), `stack` (a string) and `props` (an object with the own enumerable properties of the error other than `name`, `message`, `cause`, `errors` and `stack`, such as `code`, serialized as ECSON). Other members MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).

<a id="ERROR_NATIVE"></a>**Rule `ERROR_NATIVE`**: MUST

When deserializing, an implementation MUST create the native error type named by `name` when it is one of `Error`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError` or `AggregateError`, and MUST otherwise create an `Error` whose `name` is the received `name`.

<a id="ERROR_ERRORS_READ"></a>**Rule `ERROR_ERRORS_READ`**: MUST

When deserializing, an error whose `name` is `AggregateError` and that has no `errors` MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). An `errors` in an error with another `name` MUST be restored as an own property `errors` of the created error.

<a id="ERROR_STACK_READ"></a>**Rule `ERROR_STACK_READ`**: MUST

When deserializing, a received `stack` MUST replace the `stack` of the created error.

<a id="ERROR_PROPS"></a>**Rule `ERROR_PROPS`**: MUST

When deserializing, the members of `props` MUST be restored as own properties of the error.

<a id="ERROR_PROPS_KEYS"></a>**Rule `ERROR_PROPS_KEYS`**: MUST

A `props` with the key `name`, `message`, `cause`, `errors` or `stack` MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). An empty `props` is valid.

> **Note (non-normative)**
>
> Restoring one of these keys from `props` would overwrite a member of the error.

<a id="ERROR_STACK_OPT_IN"></a>**Rule `ERROR_STACK_OPT_IN`**: SHOULD NOT

Implementations SHOULD NOT serialize `stack` unless the application asks for it.

> **Tip (non-normative): Example**
>
> `{ "$error": { "name": "TypeError", "message": "amount must be a string", "cause": { "$error": { "name": "Error", "message": "invalid input" } } } }`
>
> `{ "$error": { "name": "Error", "message": "file not found", "props": { "code": "ENOENT", "path": "/tmp/a.txt" } } }`
>
> `{ "$error": { "name": "AggregateError", "message": "2 uploads failed", "errors": [{ "$error": { "name": "Error", "message": "timeout" } }, { "$error": { "name": "RangeError", "message": "file too large" } }] } }`

> **Note (non-normative)**
>
> A missing `cause` and a `cause` of `{ "$undefined": true }` are different ([`TYPE_UNDEFINED`](#TYPE_UNDEFINED)): the first is an error without a `cause` property, the second an error whose own `cause` property is `undefined`, as `new Error("x", { cause: undefined })` creates.

> **Caution (non-normative): Security**
>
> Stack traces expose file paths and internal structure of the sender. Sending them should be opt-in.

## 5. Type definitions and processing

This section defines the abstract model that every implementation follows. It does not define a programming interface: function names and signatures are left to each implementation.

ECSON is a serialization for transport. The types defined by ECSON form a model of values; ECSON serializes them without loss, and the plain JSON form ([section 5.3](#53-plain-json-form)) serializes them with loss, for receivers that do not use ECSON. Applications and data stores keep values in their own native types, not as ECSON.

Sections 5.4 and 5.5 name ECMAScript mechanisms: the `toJSON` method, the static `fromJSON` method and the behavior of `JSON.stringify`. Implementations in other host languages use the equivalent mechanism of their language and state which one ([`CONFORMANCE_DECLARE`](#CONFORMANCE_DECLARE)). The serialized forms are the same in every language, such as `$class` with `ctor` and `value`.

### 5.1 Type definitions

A **type definition** describes one tag. It consists of:

- the **tag**, a string starting with a single `$`;
- the **serialized form**: the JSON value that represents an instance of the type;
- the **validation** of the serialized form, which states when a value under that tag is malformed;
- the **plain JSON form**: the JSON value used when the value is sent without ECSON ([section 5.3](#53-plain-json-form)).

Each type in sections 3 and 4 is a type definition. The `$class` form ([section 5.4](#54-application-classes)) is also a type definition, defined by this section and outside any type set. Applications MAY add their own type definitions, following the namespace rules in [section 6](#6-tag-ownership-and-namespaces).

<a id="TYPEDEF_VALIDATE"></a>**Rule `TYPEDEF_VALIDATE`**: MUST

When deserializing a typed value whose tag is known, an implementation MUST fail if the serialized form does not match the type definition.

> **Tip (non-normative): Example**
>
> `{ "$bigint": "12.5" }` is malformed ([`TYPE_BIGINT`](#TYPE_BIGINT) allows only decimal digits) and deserialization fails. `{ "$acme.unknown": 1 }`, with an unknown tag, does not fail and is preserved ([section 7](#7-unknown-tags)).

### 5.2 Processing limits

<a id="CIRCULAR_FAIL"></a>**Rule `CIRCULAR_FAIL`**: MUST

Serialization MUST fail when the value contains a circular reference, including one reached through the result of a `toJSON` method.

<a id="DEPTH_LIMIT"></a>**Rule `DEPTH_LIMIT`**: MAY

An implementation MAY limit the nesting depth it serializes or deserializes. The depth is counted in the JSON text of the ECSON form, where each array and object, including the root, is one level, so `{ "$set": [] }` has two levels. When the limit is exceeded, the implementation MUST fail, rather than truncate.

<a id="TAG_ALLOWLIST"></a>**Rule `TAG_ALLOWLIST`**: MAY

An implementation MAY let users restrict processing to a list of tags. Typed values with tags outside the list MUST then be handled as unknown tags ([section 7](#7-unknown-tags)) when deserializing, and serializing a native value whose tag would be outside the list MUST fail. Unknown typed values preserved under [`UNKNOWN_PRESERVE`](#UNKNOWN_PRESERVE) are written back unchanged.

### 5.3 Plain JSON form

The plain JSON form lets a value be sent to a receiver that reads only JSON. It keeps the data that JSON can carry and drops the type information.

<a id="PLAIN_FORM_DEFAULT"></a>**Rule `PLAIN_FORM_DEFAULT`**: MUST

The plain JSON form of a typed value MUST be its serialized form, itself in plain JSON form, without the tag, except for the types in the table below.

| Tag | Plain JSON form |
|---|---|
| `$date` | the RFC 3339 string of [`TYPE_DATE_STRING`](#TYPE_DATE_STRING); for years outside 0000 to 9999, the expanded year string of ECMAScript `Date.prototype.toISOString` (for example `+275760-09-13T00:00:00.000Z`); `null` for an invalid date |
| `$bigint` | a JSON number |
| `$number` | `null`, and `0` for negative zero |
| `$undefined` | omitted as a member of an object; `null` elsewhere, including at the root and inside `$set` and `$map` |
| `$class` | for a registered class, the plain JSON form of `value`; for an unregistered identifier, the raw object with `ctor` and `value`, as for any unknown tag ([`CLASS_REGISTERED_ONLY`](#CLASS_REGISTERED_ONLY), [`PLAIN_FORM_UNKNOWN`](#PLAIN_FORM_UNKNOWN)) |
| `$regexp` | the string `/source/flags` |
| `$symbol` | the description string, or the registry key for a registered symbol |
| `$bytes` | the Base64 string of `data` |
| `$binary` (BSON) | the Base64 string of `base64` |
| `$minKey`, `$maxKey` (BSON) | `null` |

> **Tip (non-normative): Example**
>
> | ECSON | Plain JSON form |
> |---|---|
> | `{ "$date": "2026-11-06T12:00:00.000Z" }` | `"2026-11-06T12:00:00.000Z"` |
> | `{ "$set": [1, 2] }` | `[1, 2]` |
> | `{ "$map": [[{ "$date": "2026-11-06T12:00:00.000Z" }, "a"]] }` | `[["2026-11-06T12:00:00.000Z", "a"]]` |
> | `{ "$bigint": "42" }` | `42` |
> | `{ "$acme.money": { "amount": "9.90", "currency": "BRL" } }` | `{ "amount": "9.90", "currency": "BRL" }` |
> | `{ "$error": { "name": "TypeError", "message": "bad amount", "props": { "code": "E1" } } }` | `{ "name": "TypeError", "message": "bad amount", "props": { "code": "E1" } }` |

<a id="PLAIN_FORM_CUSTOM"></a>**Rule `PLAIN_FORM_CUSTOM`**: MAY

A type definition outside this specification MAY declare another plain JSON form.

<a id="PLAIN_FORM_UNKNOWN"></a>**Rule `PLAIN_FORM_UNKNOWN`**: MUST

The plain JSON form of an unknown tag ([section 7](#7-unknown-tags)) MUST be its raw serialized value, without the tag: keys inside it are not unescaped and typed values inside it are not converted ([`UNKNOWN_RAW`](#UNKNOWN_RAW)).

<a id="PLAIN_FORM_NO_ESCAPE"></a>**Rule `PLAIN_FORM_NO_ESCAPE`**: MUST

In the plain JSON form, keys of plain objects MUST NOT be escaped ([section 2](#2-escape-convention)): a key `$ref` is written as `$ref`.

<a id="PLAIN_FORM_READ"></a>**Rule `PLAIN_FORM_READ`**: MUST

A JSON text received in the plain JSON form MUST be read as plain JSON: keys starting with `$` are plain keys, and no object is interpreted as a typed value.

> **Note (non-normative)**
>
> Reading the plain JSON form does not recover the types: a date arrives as a string. Recovering them needs information outside ECSON, such as a schema. JavaScript parsers round integers above 2^53 − 1, so a large `$bigint` can lose precision in its plain JSON form, although JSON allows integers of any size ([RFC 8259, section 6](https://www.rfc-editor.org/rfc/rfc8259#section-6)). Senders that must keep every value exact use ECSON.

### 5.4 Application classes

Applications that own a type define it with a namespaced tag (sections 5.1 and 6), such as `$acme.money`, and register it in the implementation. For instances of application classes that have no registered tag, ECSON defines a generic form based on `toJSON` and `fromJSON`.

<a id="CLASS_FORM"></a>**Rule `CLASS_FORM`**: MUST

An instance of a registered class MUST be serialized under the tag `$class` as an object with two members: `ctor`, the class identifier, and `value`, the result of `toJSON()` serialized as ECSON. A registered class is a class without a registered tag, with a `toJSON` method and a static `fromJSON` method, that the application registered under a class identifier.

<a id="CLASS_IDENTIFIER"></a>**Rule `CLASS_IDENTIFIER`**: MUST

The class identifier MUST be declared by the application when it registers the class, and MUST NOT be taken from the runtime name of the class. It MUST follow [`TAG_GRAMMAR`](#TAG_GRAMMAR) without the leading `$`: a namespace, a `.` and a class name (for example `acme.Money`).

<a id="CLASS_EXACT"></a>**Rule `CLASS_EXACT`**: MUST

The `$class` form MUST apply only to instances of the registered class itself, not of its subclasses. An instance of a subclass that is not registered itself goes on to the next steps of [`SERIALIZE_ORDER`](#SERIALIZE_ORDER): the type sets, when it is an instance of one of their types, or else the `toJSON` step, through the inherited `toJSON`. Either way it loses its class.

<a id="CLASS_READ_FORM"></a>**Rule `CLASS_READ_FORM`**: MUST

When deserializing, a `$class` value whose `ctor` does not follow the grammar of [`CLASS_IDENTIFIER`](#CLASS_IDENTIFIER), without `value`, or with members other than `ctor` and `value`, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).

> **Note (non-normative): Rationale**
>
> Minifiers rename classes: in a minified build, `Money.name` may become `"o"`, so data written by one build could not be read by another. Namespaces avoid collisions between libraries that use the same class name.

<a id="CLASS_REGISTERED_ONLY"></a>**Rule `CLASS_REGISTERED_ONLY`**: MUST

When deserializing a `$class` value, an implementation MUST call the static `fromJSON` method with the deserialized `value` only for classes registered by the application under that identifier, and MUST NOT look up classes by name in any other way. A `$class` value with an unregistered identifier MUST be handled as an unknown tag ([section 7](#7-unknown-tags)).

> **Caution (non-normative): Security**
>
> Creating instances from a class name received in the data would let a sender run code of any class the receiver can reach. Only registered classes are instantiated.

> **Tip (non-normative): Example**
>
> An application registers the class `Money` as `acme.Money`. An instance whose `toJSON()` returns `{ amount: "9.90", currency: "BRL" }` is written as `{ "$class": { "ctor": "acme.Money", "value": { "amount": "9.90", "currency": "BRL" } } }`, and that value is read as `Money.fromJSON({ amount: "9.90", currency: "BRL" })`. A reader that did not register `acme.Money` keeps the value as an unknown tag ([`CLASS_REGISTERED_ONLY`](#CLASS_REGISTERED_ONLY)).

### 5.5 Values outside the model

A value that is not JSON, not a known type and not a plain object (an object whose prototype is `Object.prototype` or `null`) is outside the model: for example a function, a `WeakMap` or an instance of an application class that has no registered tag and is not a registered class ([section 5.4](#54-application-classes)). [`SERIALIZE_ORDER`](#SERIALIZE_ORDER) decides how each one is written.

<a id="SERIALIZE_ORDER"></a>**Rule `SERIALIZE_ORDER`**: MUST

Serialization MUST try, in order: (1) the registered application types; (2) the `$class` form ([section 5.4](#54-application-classes)); (3) the core type set and the extension type sets the implementation supports; (4) for a value that does not meet [`CLASS_FORM`](#CLASS_FORM), the result of its `toJSON` method, except for functions ([`FUNCTION_NOT_SERIALIZED`](#FUNCTION_NOT_SERIALIZED)); and (5), for any other value, the behavior of ECMAScript `JSON.stringify` ([`OUT_OF_MODEL_JSON`](#OUT_OF_MODEL_JSON)).

<a id="CLASS_OVER_ERROR"></a>**Rule `CLASS_OVER_ERROR`**: MUST

An instance of a registered class ([`CLASS_FORM`](#CLASS_FORM)) MUST be serialized in the `$class` form, even when it is also an array or an instance of a type of the core type set or of an extension type set, such as a subclass of `Array`, `Map`, `Date` or `Error`. An instance of such a type that is not a registered class keeps the form of its type set.

<a id="SERIALIZE_ORDER_SCOPE"></a>**Rule `SERIALIZE_ORDER_SCOPE`**: MUST

The `toJSON` step MUST NOT apply to plain objects and arrays, which are in the model.

<a id="TOJSON_CALL"></a>**Rule `TOJSON_CALL`**: MUST

Every call to `toJSON`, in the `$class` form and in the `toJSON` step, MUST pass the key as `JSON.stringify` does: the member name, the array index as a string, and the empty string at the root. Inside `$set` and `$map`, which `JSON.stringify` does not serialize, the key MUST be the empty string.

<a id="TOJSON_RESULT"></a>**Rule `TOJSON_RESULT`**: MUST

The result of `toJSON` MUST be serialized as ECSON, so that a `Date` inside it becomes `$date`, but it MUST NOT go through the `$class` and `toJSON` steps again: its own `toJSON` is never called. Its members go through the whole order.

<a id="OUT_OF_MODEL_JSON"></a>**Rule `OUT_OF_MODEL_JSON`**: MUST

Values that reach the last step of [`SERIALIZE_ORDER`](#SERIALIZE_ORDER) MUST be serialized as `JSON.stringify` does. A `Number`, `String`, `Boolean` or `BigInt` object is unboxed, and the primitive is serialized as ECSON (so `Object(1n)` becomes `$bigint`). Any other object becomes a plain object with its own enumerable string-keyed properties, whose values are serialized as ECSON, so that a `Date` inside it becomes `$date`. A function, or a symbol or `undefined` in an implementation that does not support `$symbol` or `$undefined`, is omitted as a member of an object and becomes `null` elsewhere, including at the root and inside `$set` and `$map`.

<a id="OUT_OF_MODEL_REPORT"></a>**Rule `OUT_OF_MODEL_REPORT`**: MAY

An implementation MAY report the values handled by [`OUT_OF_MODEL_JSON`](#OUT_OF_MODEL_JSON), with their path and reason, without failing.

<a id="FUNCTION_NOT_SERIALIZED"></a>**Rule `FUNCTION_NOT_SERIALIZED`**: MUST NOT

The source code of a function MUST NOT be serialized, and a `toJSON` method of a function MUST NOT be called.

<a id="CODE_NOT_EVALUATED"></a>**Rule `CODE_NOT_EVALUATED`**: MUST NOT

When deserializing, an implementation MUST NOT evaluate code received in the data.

> **Note (non-normative): Rationale**
>
> Serializing a function means writing its source code and evaluating it on the receiving side, which is remote code execution, and it would still lose the variables the function captures. `WeakMap`, `WeakSet`, `WeakRef` and `Promise` cannot be inspected, so there is nothing to serialize.

## 6. Tag ownership and namespaces

Every tag must mean the same thing to every reader. This section defines who may define a tag.

<a id="TAG_RESERVED"></a>**Rule `TAG_RESERVED`**: MUST NOT

A tag defined by the core type set, by an official extension type set or by [section 5](#5-type-definitions-and-processing) (`$class`) MUST NOT be redefined, overridden or given another form by any other type set or application.

<a id="TAG_UNNAMESPACED_RESERVED"></a>**Rule `TAG_UNNAMESPACED_RESERVED`**: MUST NOT

Applications MUST NOT define tags without a `.` (such as `$money`): those tags are reserved for this specification.

<a id="TAG_NAMESPACE"></a>**Rule `TAG_NAMESPACE`**: SHOULD

Application-defined tags SHOULD use a namespace followed by `.` and the type name, such as `$acme.money`, where the namespace identifies the application or organization.

<a id="TAG_GRAMMAR"></a>**Rule `TAG_GRAMMAR`**: MUST

A tag that contains a `.` MUST be `$` followed by two or more non-empty segments separated by `.`, and its first segment MUST NOT start with `$` (a key starting with `$$` is never a tag, [`ESCAPE_NOT_TYPED`](#ESCAPE_NOT_TYPED)). Segments MUST NOT contain white space (Unicode property `White_Space`), control or invisible format characters (general categories `Cc` and `Cf`, such as U+200B and U+202E) or lone surrogates; any other character, including non-ASCII letters, is allowed. The last segment is the type name, and the segments before it form the **namespace**: in `$acme.billing.money`, the namespace is `acme.billing`. Tags such as `$acme.`, `$.money`, `$a..b` and `$acme. money` are malformed.

<a id="TAG_MALFORMED_READ"></a>**Rule `TAG_MALFORMED_READ`**: MUST

When deserializing, a typed value whose tag is malformed MUST be handled as an unknown tag ([section 7](#7-unknown-tags)).

<a id="TAG_DOLLAR_ONLY"></a>**Rule `TAG_DOLLAR_ONLY`**: MUST

The tag `$`, made only of `$`, is not defined by this specification and MUST NOT be defined by applications ([`TAG_UNNAMESPACED_RESERVED`](#TAG_UNNAMESPACED_RESERVED)). When deserializing, it MUST be handled as an unknown tag ([section 7](#7-unknown-tags)).

> **Tip (non-normative): Example: redefining a core tag**
>
> MongoDB writes dates in its canonical format as `{ "$date": { "$numberLong": "1705276800000" } }`. If a type set redefined `$date` to emit that form, a reader with only the core type set would find a known tag with an unexpected value and would fail or misread it. Under [`TAG_RESERVED`](#TAG_RESERVED), writers always emit the core `$date` form; the BSON type set may only accept the MongoDB form when reading ([`BSON_READ_CANONICAL_DATE`](#BSON_READ_CANONICAL_DATE)).

> **Tip (non-normative): Example: application tags**
>
> An e-commerce application defines `{ "$money": { "amount": "10.50", "currency": "BRL" } }`. If a future ECSON version defines an official `$money` with another form, the stored data becomes ambiguous; if another application also defines `$money`, data from both mixes in the same store. With `$shop.money` and `$acme.money`, neither collides with the specification nor with each other.

## 7. Unknown tags

A reader may receive a typed value whose tag it does not know, for example a client without BSON support receiving `{ "$oid": "..." }`.

<a id="UNKNOWN_IGNORE_DEFAULT"></a>**Rule `UNKNOWN_IGNORE_DEFAULT`**: MUST

By default, an implementation MUST NOT fail when deserializing a typed value with an unknown tag, except as stated in [`UNKNOWN_NOT_JSON`](#UNKNOWN_NOT_JSON).

<a id="UNKNOWN_PRESERVE"></a>**Rule `UNKNOWN_PRESERVE`**: MUST

When an unknown tag is ignored, the implementation MUST preserve the tag and its serialized value, so that serializing the result again produces the same typed value.

<a id="UNKNOWN_RAW"></a>**Rule `UNKNOWN_RAW`**: MUST

The serialized value of an unknown tag MUST be preserved as it is: keys inside it MUST NOT be unescaped and typed values inside it MUST NOT be interpreted.

<a id="UNKNOWN_NOT_JSON"></a>**Rule `UNKNOWN_NOT_JSON`**: MUST

When deserializing, an unknown tag whose value contains `NaN`, `Infinity` or `-Infinity`, which JSON5 input allows and JSON cannot represent, MUST fail, because it could not be written back unchanged ([`UNKNOWN_PRESERVE`](#UNKNOWN_PRESERVE)). Other JSON5 numbers inside it, such as `+1`, `.5`, `0x10` and `-0`, keep their value and are written back in JSON syntax (`1`, `0.5`, `16` and `0`, see [`TYPE_NUMBER_ZERO_READ`](#TYPE_NUMBER_ZERO_READ)).

<a id="UNKNOWN_ERROR_MODE"></a>**Rule `UNKNOWN_ERROR_MODE`**: MAY

An implementation MAY offer a mode that fails when deserializing a typed value with an unknown tag.

> **Note (non-normative): Rationale**
>
> With unconditional escaping ([section 2](#2-escape-convention)), turning an unknown typed value into a plain object would corrupt it: on the next serialization its key would be escaped (`$oid` becomes `$$oid`) and it would stop being a typed value. Preserving unknown typed values lets intermediaries (proxies, providers, caches) pass data they do not understand without changing it.

> **Tip (non-normative): Example**
>
> A reader without BSON support receives `{ "id": { "$oid": "507f1f77bcf86cd799439011" } }`, keeps `id` as an opaque unknown typed value, and later serializes it back as `{ "id": { "$oid": "507f1f77bcf86cd799439011" } }`.

> **Note (non-normative)**
>
> Hosts whose JSON parser reads numbers as IEEE 754 doubles, such as ECMAScript `JSON.parse`, cannot preserve integers outside the range [-(2^53)+1, (2^53)-1] inside unknown tags ([RFC 8259, section 6](https://www.rfc-editor.org/rfc/rfc8259#section-6)). This is a limit of the host, not of ECSON.

## 8. Conformance and interoperability

### 8.1 Conformance levels

| Level | Requirements |
|---|---|
| **Structural** | All rules in sections 1, 2, 5, 6 and 7, with support for any subset of the core types |
| **Core** | Structural, plus every type in [section 3](#3-built-in-types) |
| **Type set** | Core, plus every type of one official extension type set ([section 4](#4-extension-type-sets)), for example "Core + BSON", "Core + References" or "Core + Error" |

> **Note (non-normative)**
>
> A structural implementation that knows no type at all still passes data through without changing it, because unknown typed values are preserved ([section 7](#7-unknown-tags)). This makes small implementations in other languages safe to use as intermediaries.

> **Note (non-normative)**
>
> The Structural level includes sections 5.4 and 5.5, which name ECMAScript mechanisms. Implementations in other languages meet them with the equivalent mechanisms of their language ([section 5](#5-type-definitions-and-processing)), and write and read the same forms, such as `$class` with `ctor` and `value`.

<a id="CONFORMANCE_DECLARE"></a>**Rule `CONFORMANCE_DECLARE`**: MUST

An implementation MUST state which conformance level it meets and, for the structural level, which core types it supports. An implementation in a host language other than ECMAScript MUST also state which mechanisms of its language stand for `toJSON`, the static `fromJSON` and the behavior of `JSON.stringify` ([section 5](#5-type-definitions-and-processing)).

### 8.2 JSON5 input

ECSON output is always standard JSON ([`OUTPUT_JSON`](#OUTPUT_JSON)). Input may also come from humans, for example in configuration files.

<a id="JSON5_INPUT"></a>**Rule `JSON5_INPUT`**: SHOULD

Deserializers SHOULD accept [JSON5](https://spec.json5.org/) input. Typed value detection and escaping MUST work identically for JSON and JSON5 input.

> **Tip (non-normative): Example**
>
> ```json5
> {
>   createdAt: { $date: "2024-01-15T00:00:00.000Z" }, // unquoted key, comment
>   tags: { $set: ["a", "b",] },                       // trailing comma
> }
> ```

### 8.3 Media type

<a id="MEDIA_TYPE"></a>**Rule `MEDIA_TYPE`**: SHOULD

ECSON content exchanged over protocols that carry media types (such as HTTP) SHOULD be labeled `application/vnd.ecson+json`.

> **Note (non-normative): Rationale**
>
> The `+json` structured syntax suffix ([RFC 6839](https://www.rfc-editor.org/rfc/rfc6839)) tells generic clients that the content is valid JSON. The vendor tree (`vnd.`) does not require standardization; if ECSON becomes an IETF specification, the media type may become `application/ecson+json`.

### 8.4 MongoDB Extended JSON

ECSON is not MongoDB Extended JSON, but they overlap:

- the core `$date` string form equals the MongoDB relaxed form for years 1970 to 9999;
- the BSON type set ([section 4.1](#41-bson-type-set)) uses the exact MongoDB canonical forms;
- MongoDB numeric wrappers (`$numberLong`, `$numberInt`, `$numberDouble`) are not ECSON tags and are preserved as unknown tags.

### 8.5 Versioning

<a id="SPEC_SEMVER"></a>**Rule `SPEC_SEMVER`**: MUST

This specification MUST be versioned independently of the other specifications of the LingoData family, following [Semantic Versioning 2.0.0](https://semver.org/).

> **Note (non-normative)**
>
> While this specification is in a `0.x` version, any release may contain incompatible changes, as allowed by Semantic Versioning. Version `1.0.0` is reserved for when the reference implementation and the conformance test suite validate the specification.

## 9. Non-goals

- **Binary encoding**: ECSON is text only. For binary efficiency, use formats such as [CBOR](https://www.rfc-editor.org/rfc/rfc8949) or [MessagePack](https://github.com/msgpack/msgpack/blob/master/spec.md).
- **References and cycles**: ECSON does not preserve shared or circular references; serializing a circular value fails ([`CIRCULAR_FAIL`](#CIRCULAR_FAIL)).
- **Schema validation**: ECSON validates only the serialized form of each type ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). Validating the shape of documents is left to schema languages applied after deserialization.
- **Streaming**: ECSON does not define incremental serialization or parsing.
- **Functions**: ECSON never serializes functions ([`FUNCTION_NOT_SERIALIZED`](#FUNCTION_NOT_SERIALIZED)), because reading them back would mean evaluating code received in the data.
- **Storage format**: ECSON is a serialization for transport. Data stores keep values in their native types; ECSON does not define how they are stored.

## 10. References

### 10.1 Normative references

- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119): Key words for use in RFCs to Indicate Requirement Levels
- [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words
- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259): The JavaScript Object Notation (JSON) Data Interchange Format
- [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339): Date and Time on the Internet: Timestamps
- [RFC 9557](https://www.rfc-editor.org/rfc/rfc9557): Date and Time on the Internet: Timestamps with Additional Information
- [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648): The Base16, Base32, and Base64 Data Encodings
- [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785): JSON Canonicalization Scheme (JCS)
- [RFC 6839](https://www.rfc-editor.org/rfc/rfc6839): Additional Media Type Structured Syntax Suffixes
- [ECMAScript Temporal](https://tc39.es/proposal-temporal/)
- [ECMAScript `Date.prototype.toISOString`](https://tc39.es/ecma262/#sec-date.prototype.toisostring) and the [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format), including expanded years
- [JSON5](https://spec.json5.org/)
- [Unicode Standard Annex #44, Unicode Character Database](https://www.unicode.org/reports/tr44/): the `White_Space` property and the `Cc` general category
- [MongoDB Extended JSON v2](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md)

### 10.2 Informative references

- [Meteor EJSON](https://docs.meteor.com/api/ejson.html)
- [Superjson](https://github.com/ravionhq/superjson)
- [devalue](https://github.com/sveltejs/devalue)
- [BSON specification](https://bsonspec.org/spec.html)
