Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ itself — for the latter see
- Apply 0.9 source diagnostics and the pinned 412-case conformance corpus, including 72 diagnostic fixtures with raw UTF-8 byte locations and EOF opener spans.
- Native uses the immutable preparing-0.9 core and C ABI 2; pure remains independent of native binaries. Package versions are unchanged; this functionality is not published in 0.8.1.

### Documentation

- Expand README examples for dotted and literal-key paths, mixed arrays, String/Integer identity, multiline unfolding, byte-identical no-op and BOM/CRLF/EOF preservation. Clarify 0.9 byte diagnostics, safe refusal, ABI 2 and standalone pure usage; these additions are not part of published 0.8.1.

## Unreleased

### 0.8.1
Expand Down
155 changes: 153 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ separator, `\.` for a literal dot and `\\` for a literal backslash;
segments are already-decoded literal names. Errors are distinct
envelope codes: `EditInvalidPath` (body = UTF-8 byte offset in the
path), `EditNotFound` (missing key, out-of-bounds index, scalar
descent, empty path) and `EditUnsupported` (noncontiguous
descent, empty segments list) and `EditUnsupported` (noncontiguous
dotted/reopen targets, structural replacement of a comment-carrying
container, a replacement String containing CR or a line `))`). A
container, or a replacement without a lossless representation in its target context). A
source that does not parse raises the ordinary parser envelope. On the
native side these methods require a `ktav_cabi` exporting the
source-edit ABI (version 2); an older binary fails with a clear
Expand All @@ -177,6 +177,157 @@ is exact digit-string equality and Float identity is exact f64 equality
Object equality IGNORES key order (Rust IndexMap PartialEq), arrays
stay ordered.

### Source-edit cookbook

These examples describe the unreleased 0.9 API, not the published 0.8.1 package. They replace existing values only: keys are not renamed, missing paths are not created, and entries are not removed. Each snippet is independent; Rust `?` assumes an enclosing `Result`-returning function. Go examples panic only for these fixed, known-valid inputs; applications should handle the returned error.

The binding examples use the standalone pure backend, without a native binary. Native entry points accept the same paths and values: `ktav.EditValue` (Go), `Ktav.editValue` (Java), `KtavApi.EditValue(..., KtavBackend.Native)` (C#), `Ktav::editValue` (PHP), the package's native/FFI exports (JS), and `ktav.edit_value` (Python). C-ABI backends require ABI 2; PyO3/N-API/WASM require the matching preparing-0.9 core. Bun/Deno FFI calls return promises: use `await`; pure/Node/WASM examples shown here are synchronous.

```php
use Ktav\PureBackend;
```

#### 1. Dotted deployment settings

Only the address changes; the comment, dotted form and neighbouring user entry remain byte-for-byte unchanged.

```php
$source = "## deployment\ntargets.storagehost.address: old\ntargets.storagehost.user: mcp-agent\n";
$updated = PureBackend::editValue($source, "targets.storagehost.address", "192.168.0.88:22");
```

Result:

```ktav
## deployment
targets.storagehost.address: 192.168.0.88:22
targets.storagehost.user: mcp-agent
```

#### 2. Literal dots: textual path or segments

The quoted source key is literally `a.b`. The textual path escapes its dot; the segments call passes the decoded key directly. Both calls return the same result.

```php
$source = "\"a.b\": {port: 80}\n";
$updated = PureBackend::editValue($source, "a\\.b.port", 90);
$same = PureBackend::editValueSegments($source, ["a.b", "port"], 90);
```

Result:

```ktav
"a.b": {port: 90}
```

#### 3. A leaf inside a mixed-form array

`0` is an array index here. Inside an Object, the same segment would address the key named `0`; untouched containers remain inline.

```php
$source = "servers: [{host: old, keep: yes}, standby]\n";
$updated = PureBackend::editValueSegments($source, ["servers", "0", "host"], "new");
```

Result:

```ktav
servers: [{host: new, keep: yes}, standby]
```

#### 4. A numeric-looking String stays a String

The replacement is a String, not an Integer. The raw marker preserves that distinction. Supply a typed Integer when a numeric value is intended.

```php
$source = "port: 8080\n";
$updated = PureBackend::editValue($source, "port", "9090");
```

Result:

```ktav
port:: 9090
```

#### 5. Multiline replacement: expand only what is necessary

The changed array expands with four-space indentation. The untouched object stays inline, and verbatim string contents are not reindented.

```php
$source = "a: [old, {keep: yes}]\n";
$updated = PureBackend::editValue($source, "a.0", "x\ny");
```

Result:

```ktav
a: [
((
x
y
))
{keep: yes}
]
```

#### 6. No-op preserves noncanonical spelling

The Integer value is already 1. Equality returns the original bytes, including `+1` and the original separator spacing; readability thresholds are bypassed.

```php
$source = "n : +1\n";
$updated = PureBackend::editValue($source, "n", 1);
assert($updated === $source);
```

Result:

```ktav
n : +1
```

#### 7. BOM, CRLF and an unterminated final line

The returned string keeps the BOM and CRLF, and does not gain a final newline. Its escaped representation is shown to make the bytes visible.

```php
$source = "\u{FEFF}port: 8080\r\nhost: db";
$updated = PureBackend::editValue($source, "port", 9090);
```

Result:

```text
"\uFEFFport: 9090\r\nhost: db"
```

Expansion is deterministic: a multiline replacement, growth beyond `max(100, original line length)`, or at least four escapes with at least 25% encoding overhead for an individual replacement string. Width counts Unicode scalar values, not UTF-8 bytes or terminal columns. An already-long line without growth is kept. New levels use four spaces and the source EOL. If CR or a `))` data line prevents lossless standalone encoding, a valid inline candidate is retained; these characters do not automatically make every inline edit unsupported.

#### 8. Exact Integer replacement

The source Integer domain is signed 64-bit. This value exceeds JavaScript's safe-Number range but fits i64; use an exact host representation, not a rounded floating-point value. A typed Integer outside i64 cannot be preserved as an Integer in source and is refused instead of truncated. Use a String when a large identifier is text. Float identity distinguishes negative and positive zero; Object no-op equality ignores key order, while Array order remains significant.

```php
$updated = PureBackend::editValue("n: 1\n", "n", ['$i' => '9007199254740993']);
```

```ktav
n: 9007199254740993
```

### Diagnostics and safe failures in 0.9

Source coordinates are UTF-8 byte offsets, including a BOM; spans are half-open `[start, end)`, and lines are 1-based. LF, lone CR and CRLF are handled, with CRLF counted as one terminator. A Unicode character may occupy several bytes.

An unfinished `a: [\n` reports `UnclosedCompound`, line 1 and span `3..5`: the span begins at the innermost unmatched opener, not the start of its key or line. For raw bytes `61 3A 20 FF` (`a: ` followed by invalid UTF-8), validation reports `InvalidUtf8`, line 1 and a covering span `3..4`; `line_text` is null rather than fabricated by lossy decoding. UTF-8 validation precedes grammar processing.

A malformed textual path, including an empty textual path or empty textual segment, is `EditInvalidPath`; its offset is measured in the path's UTF-8 bytes. An empty segments list, missing key, out-of-range index or scalar descent is `EditNotFound`. Object numeric segments remain keys; array indexes use ASCII digits, allow leading zeros and reject signs.

Whole dotted/reopened intermediate objects may occupy several physical ranges and are `EditUnsupported`; their existing leaves can still be edited. Replacing a container must not discard interior comments. No failed call returns a partial patch or changes the supplied source. The returned text is re-parsed and semantically checked: the target must equal the replacement and the rest of the value tree must remain equal.

For bindings, invalid source is reported with the ordinary parser envelope before path validation. Malformed wire payloads are `Message` errors without invented source coordinates. The wire envelope has `error`, `reason`, `line`, `line_text`, `span`, `path`, `body`, `canonical`, `spec_section` and `message`; host accessor names are documented in the errors section. `body` carries the decimal path-byte offset for `EditInvalidPath`, null for `EditNotFound`, and the refusal reason for `EditUnsupported`.

### Formatting

`Ktav::format()` takes Ktav **source text** and returns Ktav source
Expand Down
4 changes: 4 additions & 0 deletions docs/ru/CHANGELOG.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ MINOR — ломающий.
- Применена диагностика исходника 0.9 и закреплён corpus из 412 фикстур, включая 72 диагностические фикстуры с позициями сырых байтов UTF-8 и EOF spans от opener.
- Native использует immutable ядро подготовки 0.9 и C ABI 2; pure не требует native-бинарников. Версии пакетов не менялись; функционал не опубликован в 0.8.1.

### Документация

- Дополнены примеры README: dotted-пути и буквальные ключи, смешанные массивы, различие String/Integer, раскрытие многострочной замены, побайтовый no-op и сохранение BOM/CRLF/EOF. Уточнены байтовая диагностика 0.9, безопасные отказы, ABI 2 и самостоятельный pure-бэкенд; дополнения не относятся к опубликованному 0.8.1.

## Unreleased

### 0.8.1
Expand Down
Loading
Loading