# Changelog

All notable changes to live_slice are recorded in this file. The format is based on
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
[Semantic Versioning](https://semver.org/spec/v2.0.0.html): before 1.0, a minor version may break the API.
Releases are published on [Hex](https://hex.pm/packages/live_slice) and tagged in git (`v0.2.1`); the library is
not published on npm.

## [Unreleased]

## [0.2.1] - 2026-12-04

### Changed

- The service worker fetches the `pages` it precaches at install without following redirects. While nobody
  is signed in, a page that redirects to the sign-in page is skipped without requesting the sign-in page:
  one request less at install, and that page's answer no longer replaces the session cookie of the page that
  is open (a LiveView could reload the page once after it). A redirect that itself writes the session, such
  as one that stores the page to return to after signing in, still sets its cookie. The install report still
  lists the page, as `{url, kind: "page", essential: false, status: null, error: "redirected"}`: `status` is
  null, since a redirect that is not followed hides its status (it used to be the status of the page the
  redirect led to, usually 200). Static files and the `offlinePage` still follow redirects.

### Fixed

- A page skipped at install only because the server redirected it no longer causes the warning "the service
  worker ... installed without ... (redirected)", in the worker or in the page: on a first visit to an app that
  requires signing in, the worker installs on the sign-in page, where every listed page redirects. Any other
  skipped file still causes it, and the warning names only those.

## [0.2.0] - 2026-12-03

Deploy the Elixir and the JavaScript sides together. The guide
[Upgrading from 0.1.0 to 0.2.0](guides/upgrading.md) explains each breaking change in more detail.

### Breaking changes

#### Deploying

- New wire formats: entry operations (`ops` in `live_slice:patch`, sent by `put_entries/5` and the other entry
  functions) and binary columns of types `:int16` and `:uint16`. A tab still running the 0.1.0 bundle drops an
  `ops` patch without an error and fails a chunk with such a column (`unknown column type 8` or `9`).
  Migration: keep the `phx-track-static` attribute on the root layout's script and stylesheet tags, so an old
  tab reloads when it reconnects; without it, send the new operations and column types only once the new
  bundle is deployed.

#### Store and actions

- Failed pushes are kept by default: a server action that got no reply after `maxAttempts` pushes stays
  applied and pending as failed (`keepFailed` is `true` by default) instead of being rolled back with
  `"push_failed"`, and holds back the later calls that may concern its record until `retry(id)` or
  `discard(id)`. When the store sets no `keepFailed` and has no `onFailed` listener, this is reported once per
  store and page with `console.warn`. A tab still running 0.1.0 rejects a call another tab kept as failed when
  its queue reaches it. Migration: `keepFailed: false` restores the old behaviour exactly; otherwise offer
  retry and discard from `onFailed` and `pending()`.

#### Collaborative keys

- `LiveSlice.CRDT.delete/2` returns `{:ok, generation}` instead of `:ok`; the errors are unchanged.
  Migration: match `{:ok, _generation}` where code matched `:ok`.
- Local changes are batched: the changes made within `batchMs` (50 ms by default) go out as one push. Each
  change is still written to the local copy at once. Migration: `batchMs: 0` pushes the changes of each task
  at once, as before.
- New status `"waiting"`: connected, but the LiveView's `crdt_document/2` does not name the binding's
  document yet; the binding syncs once the LiveView names it. Migration: handle the new value where code
  switches on `status`.
- The status key (`statusKey`) holds `unsent` next to `status` and `writable`. Migration: code that compares
  the whole value sees one more field.
- Before each `sync1`, the binding pushes the store's mirrored keys whose debounce is still running, on the
  same connection, so the LiveView has applied them when the `sync1` arrives. Migration: none, unless the
  server relied on the debounce delay.
- `LiveSlice.CRDT`'s `:rate_limit` is one window per key and LiveView, whatever document the key syncs: a
  `sync1` to another document no longer starts a fresh window, and background deliveries (`deliver1`
  included) count in it. Migration: raise `:rate_limit` if keys that switch documents often reach it.

#### Persistence and tabs

- Persisted keys are shared live between tabs (`persist.share`, `true` by default): after each write, the
  other tabs show the values at once, without writing them back. Migration: `persist: { share: false }`
  restores the old behaviour; `persist: { share: ["key"] }` shares only the keys listed.
- The persisted record of a store gains `seq`, a stamp per key (`stamps`) and, once cleared, `epoch`.
  `removeStore(name, { clearPersisted: true })` replaces the record with a marker (`{cleared: id}`) instead of
  deleting it. A tab still running 0.1.0 reads the marker as an invalid record, removes it and writes its own
  state again, as after a delete. Migration: none in application code.

#### Service worker and offline

- A precache file that is not a script, stylesheet or WebAssembly (`.js`, `.mjs`, `.css`, `.wasm`) no longer
  fails the install: it is skipped and reported. Migration: `essential: ["/"]` in the worker's options makes
  every file essential again.
- The manifest of `LiveSlice.ServiceWorker` lists only the names that `Plug.Static` with the same filters
  serves: digested names that `:only` does not serve are left out and logged with `Logger.warning`, naming the
  `:only_matching` entry that would serve them. `only: []` (or `only_matching: []`) now lists everything, as
  `Plug.Static` serves everything with it. Migration: give the plug the same `:only` and `:only_matching`
  filters as `Plug.Static`.
- The offline mount reports each hook present in the page and not mounted offline with `console.warn`, once
  per name (never LiveView's own `Phoenix.` hooks). Migration: name a hook that rightly needs the server in
  `exclude` to silence it.

#### Only for code that followed the untagged `main` after 0.1.0

These concern features added after 0.1.0 that changed again before this release; code written against 0.1.0
is not affected.

- Connection state: a store with no bridge mounted and none expected on the page is `"detached"` instead of
  `"connecting"`. Migration: `status === "detached" ? "connecting" : status` where an interface showed
  `"connecting"`.
- Coalesced patches: the first patch after a quiet time no longer goes out alone at once; it goes out at the
  end of its callback with every patch of the store that callback makes. Migration: a callback that navigates
  calls `LiveSlice.flush_patches(socket)` first. Patches a `handle_action/4` makes go out before its reply,
  `invalidate/4` sends the held patches of its store first, and a patch made with a LiveComponent's socket is
  pushed at once.
- A held key goes out with the key the patch gave (an atom or a string) instead of a string, as a patch pushed
  at once does. Migration: server tests assert the keys they patched.
- `If-None-Match` goes only to URLs of the page's origin; `createLiveSliceHook({ conditional })` opts other
  origins in. A 304 to a request without it is an error.
- `retry(id)` sends at once after a push that timed out, and the bridge sends queued calls again after
  settlements and retries.
- `patch/4` and the entry functions raise `ArgumentError` for an unknown option; a connected LiveView that
  renders a bridge sending the actions of a `LiveSlice.Actions` module it does not attach raises at its first
  render; `send_json/3` raises for a `:version` that is not a non-empty string, an integer, a `DateTime`,
  `NaiveDateTime` or `Date`.
- `send_json/3` hashes versions with a comma, a quote, a space or non-ASCII characters into the tag
  (`W/"h<hash>"`); weak comparison and `If-None-Match: *` are honoured.
- Install reports in `live_slice:meta` carry `rank` (the install order), `offlinePage` is null when the offline
  page was not kept, and a reset (`unregisterServiceWorker({clearCaches: true})`) deletes the reports.
- The persistent chunk cache keys an entry with a per-chunk version by the version's type too: such entries
  cached before are fetched again once.
- The persisted record's `seq` and stamps count from the current time in milliseconds rather than from 1.
- A collaborative binding marks stored updates as acknowledged each time the server acknowledges changes, so
  after a reload `unsent` and `unsentSince` leave out what was acknowledged before.
  `LiveSlice.CRDT.MemoryPersistence.save/4` is available again.

### Added

#### Store and actions

- Failed pushes: `retry(id)` sends a failed call again with the same `meta.id` and `meta.base`, and
  `discard(id)` rolls it back and settles it as `"discarded"`; `onFailed` and `onRetry` listeners; `pending()`
  marks `failed: true` and, on the calls it holds back, `blocked: true`. The failed state is persisted with the
  queue and announced to the other tabs.
- `cancel(id)` takes back a queued call that was never pushed: it is rolled back and its promise rejects with
  `"cancelled"`. It returns `false` once the call was pushed.
- Conflicts that wait for a person: `onConflict: "park"` (or a resolver that returns `"park"`, or a promise of
  `{ args }` or `null`) parks the call; `resolveConflict(id, "mine" | "theirs", { args })` resolves it, and
  `pending()` lists it with `parked: { reason, state }`. Parked calls are persisted and shared between tabs.
- The confirmed state is public: `getConfirmedState()`, `getConfirmed(key)` and
  `subscribeConfirmed(selector, listener, { equals })`; `reducers` fold a key the server writes into the
  confirmed state in the same write.
- The promise of a server action carries `id` (its mutation id) and `queued` (resolves `true` when the call
  waits for a connection); `onQueued(listener)`; `pending()` entries carry `at`, the time the call was made.
- Transport API for transports of their own: `exhausted(id)`, `pushFailed(id, reason)`, `markQueued(id)`,
  `setConnection(status)` and `noteServerData(at?)`.

#### Bridge and connection

- Connection state per store: `store.connection` (`"connected"`, `"connecting"`, `"reconnecting"`,
  `"offline"` or `"detached"`), `store.serverAt` (when the page last received server data for the store),
  `onConnection(listener)`, and `connectionKeys: { status, serverAt }` to write both into store keys.
- `flushMirror(store, key)` pushes mirrored keys at once instead of when their debounce elapses.
- Conditional fetches: the bridge sends the `ETag` of an invalidate response back as `If-None-Match` and keeps
  the value on a `304 Not Modified`; `createLiveSliceHook({ conditional })` allows it for other origins.
  `LiveSlice.send_json/3` answers such fetches with a weak `ETag`, from a hash of the JSON or from `version:`.
- `defineInvalidation(store, key, { params, debounce })` adds query parameters from the store's state to the
  server's invalidate URL and fetches again when they change.
- `LiveSlice.Actions`: `use LiveSlice.Actions, store: ..., actions: [...]` defines a store's server actions
  once; attached with `on_mount` and rendered with `<LiveSlice.bridge module={...} />`, it lets every page
  send the store's queue. A bridge logs a warning when server actions are queued and no bridge of the page
  sends them.

#### Server patches

- Entry functions change entries inside one key: `put_entries/5`, `merge_entries/5`, `delete_entries/5`,
  `append_items/5` and `prepend_items/5` (with `limit:`). They apply to the confirmed value of the key.
- Coalescing: `coalesce: [quiet: ..., max_wait: ..., keep: [...]]` on `use LiveSlice`, or `coalesce:` per call
  (on `patch/4` and the entry functions, also in a LiveView that does not `use LiveSlice`), holds a LiveView's
  patches and sends them merged, without timers in the application. `keep` names keys whose every value must
  reach the client. `LiveSlice.flush_patches(socket)` (or `flush_patches(socket, store)`) sends what waits.

#### Collaborative keys

- Following the store: `doc` may be a function of the store's state that returns the document's name, or
  `null` for none; `binding.name`, `binding.loaded` and `onLoad({ name })` tell which document is open and
  when its local copy has loaded. The LiveView sends `resync` once its `crdt_document/2` names the document.
- Unsent changes: `binding.unsent`, `binding.unsentSince` and `unsent` in the status key, kept across a
  reload.
- Background delivery of offline changes to documents no binding has open: `listUnsentDocuments()`,
  `deliverUnsentDocuments({...})` and `dropUnsentDocument(name, ...)` in `live_slice/crdt`. The LiveView
  accepts a delivery through the `accept_crdt_delivery/3` callback; the server refuses by default.
- `LiveSlice.CRDT.delete/3` takes `meta:` (who deleted, why), which every client gets in `onReset` as `meta`;
  `delete(doc_name, opts)` deletes on the default server. Persistences may implement `save/5`, which stores
  the metadata, and return it from `load/2`.
- `carryOver` (off by default) on `createCollaborativeKey` and `deliverUnsentDocuments`: after a delete, the
  changes the server never acknowledged are put onto the new generation, once across tabs, reloads and
  background deliveries. `onReset` reports `carried`, `carriedValue` and `notCarried` (why nothing was
  carried).

#### Persistence and tabs

- `persist.share` takes `true`, `false` or a list of the keys to share between tabs.
- `removeStore(name, { clearPersisted: true })` is announced to the other tabs, which stop writing the
  record, put their persisted keys back to the store's initial values and call `store.onCleared(listener)`.

#### Service worker and offline

- `essential` in the worker's options: patterns of the precache URLs that fail the install.
- Install reports: the worker posts `{type: "live_slice:install", version, ok, failures}` to every page of
  the origin and records it in `live_slice:meta`, each failure naming its URL; the `onInstallFailed` option of
  `registerServiceWorker` is called with them.
- `offlineReadiness({ pages })` in `live_slice/offline` reads the caches to tell whether this device opens the
  page offline now, and if not, why.
- `:only_matching` filter of `LiveSlice.ServiceWorker`, as `Plug.Static`'s.
- `createOfflineMount({ mountAll: true, exclude: [...] })` mounts every object hook offline except the ones
  named.

#### Chunk loader and columns

- Per-chunk versions: `chunkVersionsKey` (or `chunkVersions` and `loader.setChunkVersions`); the chunk's
  version is the third argument of `url(chunk, version, chunkVersion)`, and only chunks whose version changed
  are fetched again.
- `LiveSlice.Columns` column types `:int16` and `:uint16`, decoded as `Int16Array` and `Uint16Array`.

#### Testing helpers

- `live_slice/testing`, for application tests in Node: `FakeLiveView`, `deferred`, `nextTurn`,
  `jsonResponse`, `createReferenceServer(Y)` (the collaborative key protocol as `LiveSlice.CRDT` speaks it),
  `createFakeIndexedDB()` and `createFakeTabs({ storage })`, whose `openTab()` gives a second tab its own store
  registry. Nothing else in live_slice imports it.

### Changed

- Every listener event about a call (`onPending`, `onQueued`, `onFailed`, `onRetry`, `onConflict`,
  `onRejected`, `onSettled`) and the context of an `onConflict` resolver carry `at`, the time the call was
  made; it is absent only for an entry stored by an older version. A test that compares whole events sees one
  more field.
- `onReset` of a collaborative key also receives `meta`, `value`, `unsent`, `carried`, `carriedValue` and
  `notCarried` (`false`, `null` and `"off"` without `carryOver`).
- Document storages: `load` and `setGeneration` may resolve with `carry`, `setGeneration` passes `decide` what
  is stored as a second argument, and its change may hold `carry` and `append` (see `crdt_storage.js`). Custom
  storages that ignore them keep working, with the limits listed below.
- Tabs also post `{type: "attempted", id, attempts}` for each push of the sending tab; older tabs ignore it.
- `LiveSlice.Columns` checks each distinct string of a dictionary column for UTF-8 once, not each record,
  which makes dictionary columns faster to build.

### Fixed

- A store no longer writes its persisted record when only keys that are not persisted changed before it
  finished hydrating; it used to write its whole persisted state, unchanged.
- With tab coordination, a tab that took over the queue and adopted a resubmitted call before it heard of the
  resubmission no longer rejects the original call as a conflict: the resubmission takes its place and its
  caller.

### Known limitations

- Coalesced patches that still wait when the LiveView ends are not sent, including on `push_navigate/2` and
  `redirect/2`: call `LiveSlice.flush_patches(socket)` before navigating. A key patched twice while held
  reaches the client with its last value only, unless it is named in `keep`.
- A tab still running an older bundle after a deploy cannot apply `ops` patches or decode `:int16`/`:uint16`
  columns; it relies on `phx-track-static` to reload (see Breaking changes).
- With tab coordination, the tab that sends the queue also moves the `base` of calls it adopted from other
  tabs when an earlier call is confirmed, judging from its own confirmed state rather than the state of the
  tab that made the call.
- A bridge inside a nested LiveView (`live_render`) reached by live navigation comes with that LiveView's join
  patch, after the parent's hooks mounted, so those hooks can read `"detached"` before the store turns
  `"connecting"`.
- Carry-over of unsent changes: the carried content is written again at the end of each root, so content
  others added since the delete may land before or after it; deletions are not carried and a text loses its
  formatting. A function that refuses holds only for its own tab: another tab whose function accepts carries
  what it holds. A tab without a local storage (`persistence: null`) carries only the changes it made itself.
  With a custom storage that does not pass `decide` what it holds, only the tab that switches the copy
  carries and a tab reports only what it carried itself; with one that ignores `carry` and `append`, the
  carried changes are stored after the switch, so a reload in between loses them. A background delivery that
  finds the copy switched by a tab that recorded no carry-over reports `notCarried: "unknown"` and carries
  nothing.
- `deliverUnsentDocuments` runs only when the application calls it, for example from `onConnection`.
- [Known limits](guides/known-limits.md) lists the library's other limits.

## [0.1.0] - 2026-12-01

No tag was made for 0.1.0; this changelog takes it as the state of `main` at commit `75e5f14`, before the
changes listed under 0.2.0.

### Added

- A synchronous client-side store for LiveView hooks (`createStore`, `ensureStore`, `removeStore`), a bridge
  hook (`LiveSliceHook`) and the `LiveSlice` Elixir module: mirrored keys, `patch/3`, `invalidate/4` and DOM
  bindings.
- Optimistic server actions handled by `handle_action/4`, with rollback, version conflicts (`base`, `record`,
  `onConflict` resolvers) and an offline queue persisted in IndexedDB and shared between tabs.
- Persisted keys (`persist`) with versions and migrations.
- Collaborative keys (`live_slice/crdt` and `LiveSlice.CRDT` on the optional `y_ex` dependency), with document
  generations and server deletes.
- `live_slice/data`: a chunk loader, a persistent chunk cache and the `LiveSlice.Columns` binary codec.
- `live_slice/maplibre`: a MapLibre GL JS binding (`bindMap`).
- `live_slice/sw` and `live_slice/offline` with `LiveSlice.ServiceWorker`: a service worker and an offline
  mount for an offline cold start.

[Unreleased]: https://github.com/CountlinkX-Solutions/live_slice/compare/v0.2.1...main
[0.2.1]: https://github.com/CountlinkX-Solutions/live_slice/tree/v0.2.1
[0.2.0]: https://github.com/CountlinkX-Solutions/live_slice/tree/v0.2.0
[0.1.0]: https://github.com/CountlinkX-Solutions/live_slice/tree/75e5f14
