Skip to content
CoCreateJSPublic

About

Local-first JavaScript document database with rich queries, automatic indexing, and distributed data support.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

CoCreateDB

A client-server database engine for building distributed databases, built around living leaves, automatic indexing and configurable roots.

CoCreateDB keeps its working set in memory and uses one replaceable persistence resource, backed by its built-in filesystem or browser Origin Private File System (OPFS) adapter, for storage, recovery and pressure relief. Objects retain their identity as they are queried and updated, while index entries reference the objects directly. The engine provides a common CRUD interface for data and structural leaves without requiring an external database provider or network connection.

CoCreateDB runs as a local database in both browser clients and Node.js servers. CoCreate CRUD and communication layers can connect those database instances into a distributed application. Each instance owns its local Hot/Warm state; the client and server can therefore perform local database work without treating the browser as only a remote UI or cache.

Development status: this README describes the current Next implementation. Persistence receives leaf, branch and configuration operations; complete external durability, distributed acquisition and production integration remain separate work. This is not yet a production release.

Features

  • Adaptive Hot-memory and Warm-local-disk residency with direct UUID lookup.
  • Automatic indexing of scalar values, including nested keys using dot notation.
  • Living leaves and index entries that reference the original object.
  • Configurable root hierarchies with dynamic request-driven root names.
  • Shared create, read, update and delete operations across configured roots.
  • Indexed equality/range queries, AND/OR/NOR selection, multi-field sorting and pagination.
  • Update operators through @cocreate/utils.
  • Transferable structural configuration that preserves root identities.
  • Independent local DB instances in standalone applications and worker processes.
  • Replaceable persistence and distributed communication through external capabilities.

Client-server database model

Application code imports the same @cocreate/db entry in both environments. The entry composes Tree, CRUD, query planning and one persistence resource. By default DB initializes its internal persistence subsystem; custom providers use the same execute(request) and queue contract. Set persistence: false for memory-only operation.

Runtime Storage and default Processing model
Browser client Built-in persistence using OPFS by default Disk-first with persistence; adaptive when disabled
Node server Built-in persistence using the filesystem by default Adaptive by default; existing disk-first and disk-cache settings use persistence
Node worker Owns its DB instance and local Trees Executes CRUD, planning, indexing, writes and harvesting directly

The DB engine supplies local CRUD, UUID identity, roots, indexes and residency. Client-server transport, awareness, recipient selection, synchronization and remote acquisition belong to the surrounding CoCreate CRUD, Socket, IPC, Mesh and Workflow layers. They can use the DB instances to build a distributed database, but importing this package alone does not establish connections or replicate changes automatically. See runtime integration and the architecture specification.

Getting started

Package: @cocreate/db · Repository: CoCreateJS/db

For the current development implementation, install dependencies from the checked-out Next branch:

npm install
npm test

The examples below use the development source. Once this implementation is published, use the package import @cocreate/db instead.

import DB from '@cocreate/db'

const database = await DB.init({ organizationId: 'example' }, {
    prompt: false,
    config: { roots: {
        storage: {},
        database: { parent: 'storage' },
        array: { parent: 'database' },
        object: { parent: 'array' },
        index: { parent: 'array' }
    } }
})
const context = {
    organizationId: 'example',
    storage: 'production',
    database: 'application',
    array: 'products'
}
const created = await database.send({
    ...context,
    execute: 'object.create',
    object: { name: 'Keyboard', price: 80, quantity: 10 }
})

const uuid = created.object[0].uuid

const result = await database.send({
    ...context,
    execute: 'object.read',
    object: { uuid }
})

send() returns the CRUD envelope with a success flag and an array under the requested root name. The input may be a single object or an array of objects. Check success before using the result; failures include an error array.

CRUD operations

Read

Read by UUID directly, by a named identity, or by a filter:

const result = await database.send({
    ...context,
    execute: 'object.read',
    filter: {
        query: { price: { $gte: 50, $lte: 100 } },
        startingIndex: 0,
        limit: 20
    }
})

A UUID identifies a leaf directly. Supplied root constraints are still checked. Filters support dot-notation keys such as profile.name. A filter limit of 0 requests all local matches. Results describe the local database, not necessarily the complete contents of an external storage provider or cluster.

Update

const result = await database.send({
    ...context,
    execute: 'object.update',
    object: { uuid, '$inc.quantity': 5, price: 90 }
})

The update response contains resulting live leaves under object and accepted mutations under $update. Utils owns the shared operator and timestamp reconciliation semantics.

Delete

const result = await database.send({
    ...context,
    execute: 'object.delete',
    object: { uuid }
})

The response contains the leaves actually deleted. Structural leaves with children cannot be deleted until those children are removed.

Leaves and roots

A leaf is a data or structural object with a UUID. A root defines its category within the organization’s flat root map. parent identifies the parent root by UUID after resolution. Roots are not separate storage engines.

An unresolved organization root definition can omit UUIDs and name parents directly:

const organizationConfig = {
    roots: {
        storage: {},
        database: { parent: 'storage' },
        array: { parent: 'database' },
        object: { parent: 'array' },
        index: { parent: 'array' }
    }
}

Before executing CRUD, DB assigns UUIDs to roots, resolves parent names to parent UUIDs, and writes the resolved map back to the caller’s organization config. A root without a parent is a primary root. The DB composer uses each request's organizationId to select or create an organization context. Organization is not a configured root; the Tree carries tree.organizationId, and its Disk paths are rooted under that ID.

const database = await DB.init({}, {
    config: {
        roots: {
            $tenant_id: {},
            $project_id: { parent: '$tenant_id' },
            object: { parent: '$project_id' }
        }
    }
})

Create and upsert can establish missing structural ancestors; reads do not create them. Root names in the payload resolve directly through the flat root map, and DB follows parent references through the Trees to reach the requested data. The resolved root map is a top-level property of the internal organization context:

const organization = await database.organizations.get(context.organizationId)
const roots = organization.roots

Each organization owns its root definitions. DB resolves missing UUIDs and stores the resolved definitions with the organization record. Ordinary objects remain in their Trees and persistence resource.

Living leaves and automatic indexing

Each primary Tree maintains its own UUID-keyed leaf Map, field/type indexes, queue and weight. Trees do not share leaves or reference other Trees. Index entries reference their original object rather than storing a second complete copy. Each tree has a root branch and index branches that organize scalar values and support ordered range traversal. Query planning selects an available candidate index and verifies matching objects against the query.

A live leaf internally exposes getValue, setValue, getIndex and delete methods through its prototype. Use tree.execute(payload) or db.send(payload) for supported mutations; direct property assignment bypasses index maintenance. UUID, root and parent are immutable through updates; structural names are also protected.

The index primitives are independently usable from the source modules. Their low-level interfaces are not yet a stable package-level contract. The stateless Tree execution function applies updates through Utils. Ordinary updates mutate live leaves directly; timestamp reconciliation uses cloning only when required by its merge semantics.

Runtime integration

Harvesting removes an entire resident Tree, including its branches and leaves. Pruning is reserved for possible future removal of individual branches or leaves; no pruning API is implemented.

The public entry is import DB from '@cocreate/db' and await DB.init(server, options). The result exposes config, organizations, getOrganization, persistence, execute, send, lifecycle close, and availableMemory. In Node, availableMemory is the fixed number of host available-memory bytes captured when that DB instance starts. db.send(payload) resolves the organization from the payload ID. DB startup roots initialize the platform context; DB reads tenant records and persistence API records through that context and initializes each tenant internally. Root definitions and persistence configuration live at the top level of the internal organization object; memory and engine policy remain on DB config. Each primary Tree owns execution, planning and its persistence port.

The resolved local path is canonical at db.config.path. Organization records do not own a path. organization.db groups organization-scoped root management and payload execution; Tree configuration and dispatch stay internal. DB lifecycle close() rejects new work, waits for active requests, drains Tree indexing and awaits the persistence adapter's idle() when it provides one. If an adapter has queued work but no idle() method, close reports that it cannot confirm storage completion.

const organization = await db.organizations.get(context.organizationId)
organization._id                 // tenant identity
organization.roots               // resolved root entry map
organization.persistence         // tenant persistence API records
organization.db.root.get()       // root configuration API
await organization.db.execute(payload) // organization-scoped payload dispatch
import DB from '@cocreate/db'

// Default local persistence, initialized by DB; Node uses this base directory.
const db = await DB.init(server, { prompt: false, basePath: '/var/lib/cocreate/db' })
const original = db.persistence
// Retain and extend the default implementation.
db.persistence = { ...original, execute(request) { return original.execute(request) } }
// An independent DB with persistence explicitly disabled.
const memory = await DB.init({}, { prompt: false, persistence: false })

An initialized resource can also be supplied as options.persistence or server.persistence. Replacement updates existing and future organization Trees. There is no separate disk property. Provider replacement does not migrate files or drain the old provider. Initialization can optionally prompt through Config.

Bucket persistence (Node)

The built-in persistence subsystem can mirror local writes to S3-compatible Bucket targets. Configure it when initializing DB:

import DB from '@cocreate/db'
const db = await DB.init(server, {
    prompt: false,
    basePath: '/var/lib/cocreate/db',
    bucket: {
        url: 'https://db-version-01.s3.us-east-1.amazonaws.com',
        region: 'us-east-1',
        prefix: 'CoCreateDB/'
    }
})

For Node DB instances, the local filesystem adapter runs first; the separate Bucket queue follows completed local writes. Targets can be resolved per organization. Browser OPFS currently uses only the local persistence stage.

In standalone usage no server is required. The host initializes a complete DB in each worker. Every request executes locally; DB does not inspect process roles or forward requests. Network affinity and distributed delivery belong to the host. The size option controls index branch sizing.

Local state defaults to mode: 'adaptive' with memory acknowledgement. Built-in persistence initialization uses basePath (or the existing directory setting); Tree adds each organization's directory. mode: 'disk-cache' clears the DB-managed base on startup.

In Node, each DB instance captures host MemAvailable once at startup as its fixed availableMemory baseline. Telemetry's node-wide memory.max is converted to memory pressure relative to that baseline; thresholds therefore refer to the same startup capacity throughout the DB lifetime. Each instance starts harvesting its own lowest-weight eligible Trees at 75% and stops at 50%. Active operations, indexing and persistence.queue protect pending work. Absent adapters add no storage blocker; harvesting memory-only Trees discards their data.

Memory defaults to { harvestAt: 75, retainAt: 50, rejectAt: 85, resumeAt: 80 }. With persistence enabled, db.send starts rejecting all incoming CRUD when Telemetry utilization reaches memory.rejectAt, returning success: false with error: ['Memory capacity exceeded']. Rejection remains active until utilization falls to or below memory.resumeAt. Between these thresholds, the previous acceptance/rejection state is preserved. This check does not invoke harvesting or depend on reclaimable Trees. Existing operations, indexing, persistence and LFU harvesting continue independently. Memory-only admission is unchanged, and direct organization/standalone Tree APIs retain host-controlled admission. No recovery timer is used.

Eligible Tree engines are persisted and evicted through DB's internal lifecycle. Later requests hydrate the required indexes and payloads from stored roots and files. Traffic routing and node protection remain external.

Import the standalone constructor with import { Tree } from '@cocreate/db'; configure standalone Trees directly with Tree.init() options. Organization Tree configuration is an internal routing detail. DB sends logical resource identities and the configured storage scope; the adapter owns physical paths. The built-in filesystem backend stores organization configuration in <organization>/config.json, primary branch records and index branches in <organization>/<primary>/root.json and <organization>/<primary>/branch/<uuid>.json, and documents in <organization>/<primary>/leaf/<hex-encoded-uuid>.json. Cold leaf reads resolve the primary before accessing storage; UUID-only requests without a full root path may check multiple candidate primaries. There is no separate trees/ directory. Existing files in the earlier layout are not automatically migrated.

Each DB instance manages its own Trees and queues on its process's JavaScript thread. Separate worker processes provide parallelism across instances; DB adds no IPC execution layer. The host controls worker initialization and organization affinity. Physical filesystem layout and shared-disk strategies are handled by the persistence backend.

Browser storage

The shared package entry selects DB's internal platform persistence adapter. The default directory remains ~/.cocreate/db on Node and CoCreateDB in OPFS. The configured path or basePath maps to the adapter's storage scope; the existing directory option also works. Browser default persistence requires OPFS in a secure context. Use persistence: false when storage is not desired or available. Injected providers own their own initialization and configuration.

The browser DB client uses the existing window.CoCreate.socket service when available to send requests and await their responses. It applies incoming successful database events locally without registering Socket listeners. Socket owns the connection; DB does not import Socket or establish one.

Persistence and awareness

Tree exposes persistence.execute(request) and persistence.queue. After indexing, DB hands off each serialized leaf, changed branch and configuration once, with configured storage scope, kind, resource UUID, primary UUID and organization ID. DB does not build filenames or directories. Reads return serialized files; there is no second plain-document read path. Hydration does not echo writes. The provider owns coalescing, timing, execution, errors and retries. Its queue covers pending, in-flight and failed work. tree.persist() delegates to an optional provider method. Disabled ports return no-op responses and an empty map.

CoCreate CRUD → CoCreateDB → CRUD workflow / AST
                              ├─ Persistence
                              ├─ Remote CRUD acquisition
                              └─ Communication

For successful object.create, object.update, and object.delete requests in adaptive mode, the response follows the in-memory leaf-map mutation. Create assigns or accepts a UUID and adds the leaf; update changes the resident leaf; delete removes it from the resident map and records its pending persistence deletion. Create does not read persistence to check a supplied UUID. Cold-leaf hydration and query-based operations may need lookup or matching work before the mutation can be acknowledged.

After the response, the indexer reconciles batched changes and submits changed leaves, branches and Tree configuration to persistence. Indexing continues without awaiting writes; queries use the available index. Adapters coalesce pending file operations and expose their queues for harvesting eligibility. DB owns no persistence queue. Repeated queued changes to one leaf coalesce. tree.close() finishes indexing and request handoff without waiting for storage; db.close() drains DB work and waits for adapter idle() when available. Adapters own I/O errors and queue shutdown. Disk-first uses the same acknowledgement and storage lifecycle, then the composer drops eligible Trees. Memory acknowledgement means the mutation was accepted, not that it is already durable. Distributed delivery, retry and recipient management belong to the surrounding application. The DB returns UUID awareness references for that integration.

These integration designs are documented in persistence and CRUD awareness. External orchestration, complete acquired-leaf hydration, durable ordering and deduplication are not implemented by this engine checkpoint.

Tests and benchmarks

npm test
npm run benchmark -- 1000
BENCH_MODE=restored npm run benchmark -- 1000
npm run benchmark:ranges

Correctness tests and Node.js benchmarks live under test/. See benchmark instructions, baseline reports and provider references.

Local benchmark baseline

November 19, 2026; Node 22.16.0, Linux x64, 1,000 objects, five independent runs, 40 measured query samples and 10 warmups. Fresh configuration; median of run metrics.

Operation Time
Create and index 1,000 75.378 ms
UUID read p50 0.0045 ms
Equality read p50 0.1102 ms
Nested read p50 0.1275 ms
Range read p50 0.2118 ms
Update p50 0.0318 ms
Delete 25 0.7866 ms

These historical measurements were in-process and memory-only, excluding network, workflow and durable storage costs. Historical MongoDB and Redis references are retained separately; they are not controlled equivalent-workload comparisons. No cross-provider performance claim is made.

Specifications

See the specifications index for detailed engine contracts, integration designs and outstanding requirements.

Source structure

src/
├── index.js          Public DB.init and Tree exports
├── runtime.js        Server composition, organization selection and node memory policy
├── persistence/     Lifecycle, local adapters, leaf log and Bucket stage
└── trees/
    ├── index.js     Organization roots, Tree collections and lifecycle
    ├── manager.js    Own leaves, queue, index maintenance and hydration
    ├── planner.js    Stateless query planning
    ├── query.js      Index algebra, ordering and selection
    └── tree/
        ├── index.js    One primary's standalone Tree and persistence port
        ├── execute.js  CRUD on the selected Tree
        ├── context.js   Private context keyed by Tree
        ├── branches.js  Index branches, traversal, hydration and persistence handoff
        └── leaves.js    Living leaves, index entries and leaf residency

Current limitations

Broader data-type support, atomic batches, production authorization, distributed storage coordination and external workflow integration require further development. Document-dependent predicates and container sorting can require payload evaluation; covered queries use indexes before page hydration. Root constraints are not a substitute for authorization. DB initializes its internal persistence subsystem by default; an injected persistence resource owns its own directory and initialization. Memory acknowledgement does not establish local durability; other backing stores and archival policies require external integration. Detached persistence requires external error handling, ordering and shutdown policies.

CoCreateJS

CoCreateDB is part of CoCreateJS, the JavaScript project spanning CoCreate Client and CoCreate Server. Independently usable primitives and configurable workflows allow applications to compose the capabilities they need.

Developed by CoCreate LLC. Licensed under AGPL-3.0 (see repository license).

See the technical whitepaper for the broader architectural vision.

See Transactions vs. Synchronization for the rationale behind selective, workflow-based coordination.

Indexed filtering and sorting

Filters retain the CoCreate Filter/IndexedDB shape: query, ordered sort: [{ key, direction }], index (or startingIndex), and limit. limit: 0 is unbounded. Responses report filter.startingIndex and the next filter.index. Covered predicates select UUIDs from indexes, order the matches, and hydrate the requested page. Document-dependent predicates and container sorting use shared Utils as a fallback. Reads restore only required index paths and payloads and do not schedule indexing. Active operations protect their primary Trees from harvesting until completion.

The built-in local adapter gives configuration and branch writes priority over leaf files. Harvesting may ask persistence to store a selected primary's pending leaves in leaves.log; DB removes the Tree only after its queue protection clears and its operation/index checks still pass. The adapter reads from that log until its background writer finishes the individual files. CRUD acknowledgement does not await this maintenance. See persistence.

About

Local-first JavaScript document database with rich queries, automatic indexing, and distributed data support.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages