# knotkit/cas

> Addresses wire-envelope artifacts by content hash and stores them through an injected backend

## Use

```ts
import { contentAddressedStore } from 'knotkit/cas'
import { xxh64 } from 'knotkit/hash'

const blobs = new Map<string, Uint8Array>()
const hasher = xxh64()

const store = contentAddressedStore({
  // Any object with has/get/set works: a Map, S3 client, or fetch-backed store.
  backend: {
    has: async (address) => blobs.has(address),
    get: async (address) => blobs.get(address),
    set: async (address, bytes) => void blobs.set(address, bytes),
  },
  // Injected, so the address can be reproduced by every reader that shares it.
  hash: (bytes) => hasher.encodeHex(hasher.bytes(bytes)),
  // One store addresses one family of artifacts.
  magic: Uint8Array.of(0x4b, 0x4b, 0x48, 0x50),
})

const artifact = {
  payloadVersion: 1,
  packageHeader: Uint8Array.of(1, 0, 0, 0),
  sections: [{ tag: 1, bytes: new Uint8Array([1, 2, 3]) }],
}

const address = await store.add(artifact)

address // a 16-character hex address for these exact bytes

await store.add(artifact) // one stored copy: the address is already present
const envelope = await store.get(address) // re-hashed, then decoded
```

## What it solves

* store the same artifact once no matter how many callers write it
* prove that the bytes a store returned are the content a key names
* share artifacts between processes that do not share a filesystem
* keep serialized structures in an object store, a browser cache, or a Map behind one interface

## Worked example

* 12 writes requested, 3 distinct blobs stored.
* Reading 558718ba60ab8ed6 verifies its address and returns payload 1.
* Identical artifact bytes share one address and one backend entry.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/cas/demo.ts) against `knotkit/cas`.

## API

| Export                                                                             | Returns                 | Does                                                                                                      |
| ---------------------------------------------------------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------- |
| [`contentAddressedStore`](/reference/knotkit/cas/functions/contentaddressedstore/) | `ContentAddressedStore` | Bind a backend, a deterministic content hash, and one family magic into a deduplicating, verifying store. |

Cost per member. Open a row for every operation.

`contentAddressedStore` 4 members

| Member      | Cost          |
| ----------- | ------------- |
| `addressOf` | O(n)          |
| `add`       | O(n)          |
| `has`       | O(1) expected |
| `get`       | O(n)          |

## What you pass in

| Input                                     | Type                            | Get one from                    |
| ----------------------------------------- | ------------------------------- | ------------------------------- |
| content hash from framed bytes to address | `(bytes: Uint8Array) => string` | `knotkit/hash or crypto.subtle` |
| durable storage                           | `ArtifactBackend`               | `the caller's backend`          |

## Errors

Every error this module throws is `CasInvalidInputError` or `CasParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `CasInvalidInputError`

  `INVALID_ARTIFACT`

* `CasParseError`

  `INVALID_ADDRESS` `INVALID_HASH` `HASH_FAILURE` `BACKEND_FAILURE` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH` `UNKNOWN_KIND` `ADDRESS_MISMATCH` `ADDRESS_COLLISION`

## When not to use it

| If you need to…                                                          | Use instead                                                                   |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------- |
| persist a structure to local disk in one process                         | the structure package's serialize function and the platform file API          |
| an artifact that must be readable without the hash that produced its key | a caller-chosen storage key and an envelope from knotkit/wire                 |
| cryptographic collision resistance or signed artifacts                   | crypto.subtle with SHA-256, or signature verification over the envelope bytes |
| a cache with eviction, expiry, or least-recently-used ordering           | [`knotkit/cache`](/modules/cache/)                                            |
| mutable blobs whose key stays stable as content changes                  | a plain key-value backend; a content address changes with the content         |

## Performance

Measured by the suite in [`packages/cas/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/cas/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/casCopy prompt

```
Use knotkit/cas for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/cas'.

Exports:
- `contentAddressedStore` → `ContentAddressedStore`: Bind a backend, a deterministic content hash, and one family magic into a deduplicating, verifying store.

Inputs and their sources:
- content hash from framed bytes to address: `(bytes: Uint8Array) => string` from `knotkit/hash or crypto.subtle`
- durable storage: `ArtifactBackend` from `the caller's backend`

Use something else when:
- persist a structure to local disk in one process → the structure package's serialize function and the platform file API
- an artifact that must be readable without the hash that produced its key → a caller-chosen storage key and an envelope from knotkit/wire
- cryptographic collision resistance or signed artifacts → crypto.subtle with SHA-256, or signature verification over the envelope bytes
- a cache with eviction, expiry, or least-recently-used ordering → knotkit/cache
- mutable blobs whose key stays stable as content changes → a plain key-value backend; a content address changes with the content

Errors are CasInvalidInputError or CasParseError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/cas.md
Types: node_modules/knotkit/cas/ and https://knotkit.jkomyno.dev/reference/knotkit/cas/
```

## See also

* [API reference](/reference/knotkit/cas/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/cas/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/cas/knotkit.capability.json)suggest a change to the source record
