# pcn.ex

[![Hex.pm](https://img.shields.io/hexpm/v/sashite_pcn.svg)](https://hex.pm/packages/sashite_pcn)
[![Docs](https://img.shields.io/badge/hex-docs-blue.svg)](https://hexdocs.pm/sashite_pcn)
[![CI](https://github.com/sashite/pcn.ex/actions/workflows/elixir.yml/badge.svg?branch=main)](https://github.com/sashite/pcn.ex/actions)
[![License](https://img.shields.io/hexpm/l/sashite_pcn.svg)](https://github.com/sashite/pcn.ex/blob/main/LICENSE)

> **PCN** (Portable Chess Notation) implementation for Elixir.

## Overview

This library implements the [PCN Specification v1.0.0](https://sashite.dev/specs/pcn/1.0.0/).

PCN records a complete Match of an abstract strategy board game built on the [Sashité Game Protocol](https://sashite.dev/game-protocol/): metadata, links, Players, time control, the initial Position in [FEEN](https://sashite.dev/specs/feen/1.0.0/), the Plies in [PMN](https://sashite.dev/specs/pmn/1.0.0/) with their annotations and variations, and the result. A document is serialized in JSON or in TOML.

The library validates PCN documents and keeps them as they are decoded: maps with string keys, custom properties included. It reads and writes the JSON serialization with Elixir's built-in `JSON` module. For TOML, decode the document with a TOML library of your choice and pass the map to `Sashite.Pcn.validate/1`.

### Implementation Constraints

| Constraint | Value | Rationale |
|------------|-------|-----------|
| Max JSON document size | 1 MiB | Bounds decoding time and memory |
| Max integer literal | 20 characters | Every 64-bit integer; longer literals cost more than linear time to convert |
| Max variation depth | 64 | Bounds recursion on analysis trees |

The specification asks implementations to bound document size, string lengths and the nesting of variations (§17). Positions and moves are validated by [`sashite_feen`](https://github.com/sashite/feen.ex) and [`sashite_pmn`](https://github.com/sashite/pmn.ex), with their own limits.

## Installation

```elixir
# In your mix.exs
def deps do
  [
    {:sashite_pcn, "~> 1.0"}
  ]
end
```

The library requires Elixir 1.18 or later, for its built-in `JSON` module.

## Dependencies

```elixir
{:sashite_feen, "~> 2.1"}  # Field Expression Encoding Notation
{:sashite_pmn, "~> 1.3"}   # Portable Move Notation
```

## Usage

### Parsing JSON

```elixir
{:ok, match} =
  Sashite.Pcn.parse("""
  {
    "meta": {"event": "Example", "started_at": "2025-06-17T14:00:00Z"},
    "sides": {
      "first": {"variant": "Chess", "style": "Western", "name": "Alice", "rating": 1500},
      "second": {"variant": "Chess", "name": "Bob", "rating": 1450}
    },
    "setup": {"feen": "-rnbqk^bn-r/pppppppp/8/8/8/8/PPPPPPPP/-RNBQK^BN-R / W/w"},
    "plies": [
      {"pmn": "e2-e4", "elapsed_ms": 4200},
      {"pmn": "e7-e5"},
      {"pmn": "f1-c4"},
      {"pmn": "b8-c6"},
      {"pmn": "d1-h5"},
      {"pmn": "g8-f6", "assessment": "blunder", "comment": "Overlooks the mate threat"},
      {"pmn": "h5+f7", "check": true, "mate": true}
    ],
    "outcome": {"result": "1-0"}
  }
  """)

match["sides"]["first"]["name"]  # => "Alice"
length(match["plies"])           # => 7
match["outcome"]["result"]       # => "1-0"

# Invalid input returns an error tuple
{:error, :invalid_pmn} =
  Sashite.Pcn.parse(~s({"setup": {"feen": "1 / W/w"}, "plies": [{"pmn": "e7-e8/Q"}]}))

# Bang version (raises ArgumentError on invalid input)
match = Sashite.Pcn.parse!(json)
```

### Validating a TOML document

```elixir
# With any TOML decoder that returns maps with string keys, e.g. {:toml, "~> 0.7"}
{:ok, decoded} = Toml.decode(toml)
{:ok, match} = Sashite.Pcn.validate(decoded)
```

A TOML native datetime for `meta.started_at` may be decoded as a `DateTime` or a `NaiveDateTime`; both are accepted.

### Writing JSON

```elixir
Sashite.Pcn.dump(%{
  "setup" => %{"feen" => "1 / W/w"},
  "meta" => %{"started_at" => ~U[2025-06-17 14:00:00Z]}
})
# => ~s({"meta":{"started_at":"2025-06-17T14:00:00Z"},"setup":{"feen":"1 / W/w"}})
```

The encoded document is read back with `parse/1` before it is returned, so the output is always a document that `parse/1` accepts: valid PCN, within the 1 MiB limit. The output is compact JSON; the order of the properties of an object carries no meaning and is not specified.

### Validation

```elixir
Sashite.Pcn.valid?(json)     # => true or false, never raises
Sashite.Pcn.valid?(decoded)  # decoded documents too
```

### Working with Positions and Moves

The document keeps FEEN and PMN strings as they are. Decode them with their libraries when needed:

```elixir
position = Sashite.Feen.parse!(match["setup"]["feen"])
moves = Enum.map(match["plies"], &Sashite.Pmn.parse!(&1["pmn"]))
```

## API Reference

```elixir
@spec Sashite.Pcn.parse(String.t()) :: {:ok, map()} | {:error, atom()}
@spec Sashite.Pcn.parse!(String.t()) :: map()
@spec Sashite.Pcn.validate(term()) :: {:ok, map()} | {:error, atom()}
@spec Sashite.Pcn.valid?(term()) :: boolean()
@spec Sashite.Pcn.dump(map()) :: String.t()
@spec Sashite.Pcn.max_string_length() :: pos_integer()    # 1_048_576
@spec Sashite.Pcn.max_variation_depth() :: pos_integer()  # 64
```

### Errors

Reasons are atoms naming the first check that failed. The sections are checked in this order: `setup`, `meta`, `links`, `periods`, `sides`, `plies`, `outcome`.

JSON text (`parse/1` only):

| Atom | Cause |
|------|-------|
| `:not_a_string` | The input is not a binary |
| `:input_too_long` | The input exceeds 1 MiB |
| `:invalid_json` | The input is not a JSON text (RFC 8259), or holds a number beyond the range of a float |
| `:duplicate_key` | An object has two members with the same name |
| `:integer_too_large` | An integer literal has more than 20 characters |

Document:

| Atom | Cause |
|------|-------|
| `:not_an_object` | The document is not a map |
| `:missing_setup` | `setup` is absent |
| `:invalid_setup` | `setup` is not an object of at least one property, all strings |
| `:invalid_feen` | `setup.feen` or a Ply's `feen` is not a valid FEEN string |
| `:invalid_meta` | `meta` is not an object, or one of its string properties is not a string |
| `:invalid_started_at` | `meta.started_at` is not an ISO 8601 datetime |
| `:invalid_links` | `links` is not an array of objects with non-empty `rel` and `url` strings |
| `:invalid_periods` | `periods` is not an array of Periods (`duration_ms` ≥ 0, `increment_ms` ≥ 0, `plies` ≥ 1, all integers) |
| `:invalid_sides` | `sides` or a Side is not an object, or a `name` is not a string |
| `:invalid_variant` | A `variant` does not match `^[A-Z][A-Za-z]*[0-9]*$` |
| `:invalid_style` | A `style` does not match `^[A-Z][A-Za-z]*$` |
| `:invalid_rating` | A `rating` is not an integer ≥ 0 |
| `:invalid_plies` | `plies` or `variations` is not an array, a Ply or a variation is not an object, a variation has no `plies` array, or a `comment`, `name`, `check`, `mate` or `draw_offer` has the wrong type |
| `:invalid_pmn` | A `pmn` is not a valid PMN string |
| `:invalid_elapsed_ms` | An `elapsed_ms` is not an integer ≥ 0 |
| `:invalid_assessment` | An `assessment` is not one of the six values |
| `:variations_too_deep` | Variations are nested more than 64 levels |
| `:invalid_outcome` | `outcome` is not an object with a `result` |
| `:invalid_result` | `outcome.result` is not one of the five values |

## Semantics

- **Integers** must be written as JSON integers: `1000`, not `1000.0` or `1e3`.
- **`started_at`** is an ISO 8601 datetime, with `T` between the date and the time, with or without offset; a date alone is rejected.
- **`style`** is checked for its syntax only. Whether it is consistent with the SIN letters of the FEEN Style–Turn field depends on the mapping between Style names and SIN letters, which is a convention of the Rule System (§9.2): an application that knows the mapping checks it itself, and the FEEN string prevails.
- **Keys** are strings, as JSON and TOML decoders return them. In a decoded document passed to `validate/1`, a property under any other key, such as an atom, is not recognized.
- **Custom properties** (§14.1) are kept and not inspected. Properties that PCN defines are checked wherever they appear, so a custom property cannot reuse a semantic name.
- **Rule System checks** (§15.3: legality, accuracy of `check` and `mate`, consistency of `style` with the FEEN Style–Turn field, Turn alternation against the Position) need a Rule System and are left to the application.

## Security

This library is designed for documents that come from untrusted clients.

- **Size first**: JSON inputs over 1 MiB are rejected in O(1), before decoding.
- **Linear decoding**: integer literals are limited to 20 characters, so no number costs more than linear time to convert.
- **No ambiguity**: duplicate member names are rejected rather than resolved, so that every consumer reads a document the same way.
- **Bounded recursion**: variations deeper than 64 levels are rejected.
- **No atoms from input**: error reasons are compile-time atoms, and decoded keys stay strings.

## Related Specifications

- [Game Protocol](https://sashite.dev/game-protocol/) — Conceptual foundation
- [PCN Specification](https://sashite.dev/specs/pcn/1.0.0/) — Official specification
- [PCN Examples](https://sashite.dev/specs/pcn/1.0.0/examples/) — Usage examples
- [FEEN Specification](https://sashite.dev/specs/feen/1.0.0/) — Position encoding
- [PMN Specification](https://sashite.dev/specs/pmn/1.0.0/) — Move encoding

## License

Available as open source under the [Apache License 2.0](https://opensource.org/licenses/Apache-2.0).
