Corestore
Factory and replication manager for groups of named Hypercores.
Corestore manages many related Hypercores behind one storage root and one replication surface. It is the helper you usually share across Hyperbee, Hyperdrive, and Autobase instances. For upstream source and changelog context, see the Corestore repository.
Install
npm i corestoreQuickstart
import Corestore from 'corestore'
const store = new Corestore('./app-storage')
await store.ready()
const messages = store.get({
name: 'messages',
valueEncoding: 'json'
})
await messages.ready()
await messages.append({ text: 'hello from corestore' })
console.log(await messages.get(0))
await store.close()API Reference
Constructor and lifecycle
new Corestore(storage, options = {})
Create a new Corestore instance.
| Parameter | Type | Default | Description |
|---|---|---|---|
storage | string|object | — | can be either a hypercore-storage instance or a string. |
options | CorestoreOptions | {} | Store options. |
- Throws:
ASSERTIONifprimaryKeyis set on a root store withoutunsafe: true.
await store.ready()
A promise that resolves once the storage seed is loaded and properties such as store.primaryKey are available.
await store.close()
Fully close this Corestore instance.
await store.suspend()
Suspend the underlying storage for the Corestore.
| Parameter | Type | Default | Description |
|---|---|---|---|
options | object | {} | Suspend options. |
- Returns:
Promise<void>— Resolves once the storage is flushed and suspended.
await store.suspend()await store.resume()
Resume a suspended Corestore.
- Returns:
Promise<void>— Resolves once the storage is resumed.
await store.resume()Store properties
store.storage
The backing storage adapter used for aliases, seeds, and Hypercore data files.
- Returns:
object
store.primaryKey
The 32-byte primary key used to deterministically derive writable named cores and namespaced key pairs.
- Returns:
Buffer
store.readOnly
true when the store was opened without write access.
- Returns:
boolean
store.manifestVersion
The Hypercore manifest version used when Corestore creates new writable cores.
- Returns:
number
store.active
true when the store should automatically attach loaded cores to active replication streams.
- Returns:
boolean
Loading cores and scoping sessions
store.get(key | { name: 'a-name', ...hypercoreOpts})
Loads a Hypercore, either by name (if the name option is provided), or from the provided key (if the first argument is a Buffer or String with hex/z32 key, or if the key options is set).
| Parameter | Type | Description |
|---|---|---|
opts | Buffer|string|object | A key (Buffer/hex/z32 string), or an options object with name, key, or discoveryKey plus Hypercore options. |
- Returns:
Hypercore— A Hypercore session for the requested core.
const core = store.get({ name: 'my-core' })storeA.session()
Create a new Corestore session. Closing a session will close all cores made from this session.
| Parameter | Type | Description |
|---|---|---|
opts | object | Session options (forwarded to the new Corestore). |
- Returns:
Corestore— A new Corestore session sharing the same storage.
const session = store.session()store.namespace(name)
Create a new namespaced Corestore session. Namespacing is useful if you're going to be sharing a single Corestore instance between many applications or components, as it prevents name collisions.
| Parameter | Type | Description |
|---|---|---|
name | string|Buffer | Namespace name; combined with the current namespace to derive a new one. |
opts | object | Session options (forwarded to the new Corestore). |
- Returns:
Corestore— A new namespaced Corestore session.
const ns1 = store.namespace('a')
const ns2 = ns1.namespace('b')
const core1 = ns1.get({ name: 'main' }) // These will load different Hypercores
const core2 = ns2.get({ name: 'main' })Replication and discovery
store.replicate(optsOrStream)
Creates a replication stream that's capable of replicating all Hypercores that are managed by the Corestore, assuming the remote peer has the correct capabilities.
| Parameter | Type | Description |
|---|---|---|
isInitiator | boolean|Stream | true/false to initiate, or an existing stream/connection to replicate over. |
opts | object | Replication options, forwarded to the protocol stream. |
- Returns:
Stream— The replication stream.
const swarm = new Hyperswarm()
// join the relevant topic
swarm.join(...)
// simply pass the connection stream to corestore
swarm.on('connection', (connection) => store.replicate(connection))store.findingPeers()
A completion callback. Call it after the current peer-discovery pass finishes so pending update waits on loaded cores can unblock.
- Returns:
Function— Adonefunction to call once peer discovery has finished.
const done = store.findingPeers()
swarm.flush().then(done, done)store.list(namespace)
Creates a discovery key stream of all cores within a namespace or all cores in general if no namespace is provided.
| Parameter | Type | Description |
|---|---|---|
namespace | Buffer | to scope to; omit to list all cores. |
- Returns:
Readable— A stream of discovery keys.
for await (const discoveryKey of store.list()) console.log(discoveryKey)store.getAuth(discoveryKey)
The storage-layer auth metadata for that core, including manifest details when available.
| Parameter | Type | Description |
|---|---|---|
discoveryKey | Buffer | Discovery key of the core to look up. |
- Returns:
Promise<object\|null>— The auth record, ornullif not stored.
const auth = await store.getAuth(discoveryKey)Key derivation and maintenance
await store.createKeyPair(name, ns = this.ns)
Generate a key pair seeded with the Corestore's primary key using a name and a ns aka namespace. ns defaults to the current namespace.
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | to derive the key pair from. |
ns | Buffer | this.ns | — |
- Returns:
Promise<{publicKey: Buffer, secretKey: Buffer}>— The derived key pair.
const keyPair = await store.createKeyPair('signer')store.audit(opts = {})
An audit report describing the state of the backing store and any detected inconsistencies.
| Parameter | Type | Default | Description |
|---|---|---|---|
opts | object | {} | Audit options (e.g. dryRun). |
- Returns:
AsyncGenerator<object>— Yields a result per core as it is audited.
for await (const report of store.audit()) console.log(report)await store.staticify(core, opts)
A reopened Hypercore whose manifest is converted into a static prologue-based manifest for the current data snapshot.
| Parameter | Type | Description |
|---|---|---|
core | Hypercore | The source core to snapshot. Must have data. |
opts | object | Options forwarded to store.get() for the new core. |
- Returns:
Promise<Hypercore>— The new static Hypercore. - Throws: if the core has no data to staticify.
const staticCore = await store.staticify(core)Watchers
store.watch((core) => {})
Register a callback called when new Hypercores are opened. core is the internal core for the opened Hypercore. It can be used to create weak references to a Hypercore like so:
| Parameter | Type | Default | Description |
|---|---|---|---|
fn | Function | > {} | Callback invoked with the internal core each time a Hypercore is opened. |
- Returns:
void
store.watch(function (core) {
const weakCore = new Hypercore({ core, weak: true })
})store.unwatch(callback)
Unregister a callback used with store.watch(callback) so it no longer fires.
| Parameter | Type | Description |
|---|---|---|
callback | Function | The callback previously passed to store.watch(). |
- Returns:
void
store.unwatch(onCore)Group notifications (experimental)
store.notifyGroup(topic)
Get a handle for updates from all hypercores with the group topic set.
| Parameter | Type | Description |
|---|---|---|
topic | Buffer | The 32-byte group topic to watch. |
- Returns:
GroupNotifyHandle— A handle that emitsupdatewhen a core in the group changes.
const handle = store.notifyGroup(topic)
handle.on('update', () => console.log('group changed'))Group notifications are experimental. The API is subject to change and may break in any release.
handle.update(opts = {})
Gets updates for the topic the handle is for.
| Parameter | Default |
|---|---|
opts | {} |
| Option | Default | Description |
|---|---|---|
since | 0 | What timestamp to start returning updates from. Default 0 returns all updates |
reverse | true | Flag to return updates in reverse order. Defaults to true so latest returned first |
for await (const key of handle.updates()) {
// ...
}handle.destroy()
Destroys and unregisters the handle from its store.
handle.on('update', callback)
Calls the callback whenever a core with the topic for the handle updates.
store.on('group-active', (topic) => {})
The group-active event emits whenever an opened Hypercore in the store updates. The topic is the group topic the core belongs to.
Types
CorestoreOptions
Options for the {@link Corestore} constructor. Any other options are forwarded
to the underlying hypercore-storage instance.
| Property | Type | Default | Description |
|---|---|---|---|
primaryKey | Buffer | — | The 32-byte master key from which all writable named cores are derived. Generated and persisted automatically when omitted. |
writable | boolean | true | Set to false to open the store read-only; loaded cores default to read-only too. |
readOnly | boolean | false | Open the backing storage in read-only mode. |
active | boolean | true | Whether loaded cores are automatically attached to active replication streams. |
unsafe | boolean | false | Acknowledge that passing primaryKey directly is unsafe; required when primaryKey is set on a root store. |
Errors
Coded errors this module can throw — catch them via err.code.
| Error | Thrown when |
|---|---|
ASSERTION | if primaryKey is set on a root store without unsafe: true. |
See also
- Work with many Hypercores using Corestore—the task-oriented guide that shows how to share one store across your app.
- Hypercore—the append-only log type Corestore opens and co-replicates.
- Hyperbee—commonly layered on top of named Hypercores from one store.
- Hyperdrive—usually keeps filesystem metadata and content stores inside one shared Corestore.
- Autobase—multi-writer views often coordinate their input cores through one Corestore.
- Hyperswarm—pass swarm connections to
store.replicate()to co-replicate all managed cores over one stream. - Upstream Corestore repository—source, releases, and implementation details.