@mika/undercurrent (1.0.2)

Published 2026-11-17 17:06:13 +00:00 by mika

Installation

@mika:registry=
npm config set @mika:registry=
npm install @mika/undercurrent@1.0.2
"@mika/undercurrent": "1.0.2"

About this package

Undercurrent

Undercurrent is the reference server implementation for Blackcurrant. It exposes selected Postgres resources through sync, reconciliation, mutation, and server manifest routes in an Express application. The app owns authentication, domain rules, non-synced tables, and Postgres migrations.

Installation And Compatibility

Configure the @mika scope in your application's .npmrc:

@mika:registry=https://git.mikabytes.com/api/packages/mika/npm/

For private package access, put the following in your user-level ~/.npmrc and supply NPM_TOKEN through your shell or secret manager:

//git.mikabytes.com/api/packages/mika/npm/:_authToken=${NPM_TOKEN}

Use a Forgejo access token permitted to read the packages. Keep credentials out of project files. See the Forgejo npm registry guide.

npm install @mika/undercurrent express postgres

This checkout prepares Undercurrent 1.0.2 and is verified against Blackcurrant 4.0.0, commit b49bbdf. Publication is a separate step; use the checkout below to run these changes before 1.0.2 is published. Older Blackcurrant versions are not part of this checkout's compatibility verification.

The libraries' package versions are separate from your application runtime version. The example uses "1.0.0"; configure the same exact string in the Blackcurrant client and Undercurrent server. Use a SemVer-compatible spelling without leading zeroes, rather than "2026.05.13". When resource metadata or client schema changes, append migrations and bump your application's runtime version. Do not change an already deployed same-version manifest.

Quick Start

The complete notes example is a public, read-only sync service. Every principal can see every note; it enables no client mutation routes. Adapt the principal resolver and visibility query to your app's access rules before using it for private data.

First apply the app-owned Postgres migration to a new example database. The migration includes the two infrastructure tables and the managed Notes table. SCHEMA.md explains that storage contract; Undercurrent validates it and does not run Postgres migrations for you.

In an installed host app, save this as app.js (with "type": "module" in its package.json):

import express from "express";
import { Undercurrent } from "@mika/undercurrent";

export const version = "1.0.0";

export async function createNotesApp(sql) {
  const app = express();
  const undercurrent = Undercurrent({
    app,
    sql,
    version,
    clientMigrations: [{
      id: 1,
      name: "create_notes",
      sql: `create table Notes (
        id text primary key,
        createdAt text not null,
        updatedAt text not null,
        title text not null,
        body text,
        publishedAt text
      )`,
    }],
    principal: async () => "anonymous",
  });

  const notes = undercurrent.resource("Note", {
    optimistic: false,
    fields: {
      title: "text",
      body: { type: "text", nullable: true },
      publishedAt: { type: "timestamp", nullable: true, readonly: true },
    },
    visible: ({ sql }) => sql`select "id" from "Notes"`,
  });

  await undercurrent.ready();
  return { app, undercurrent, notes };
}

Then start it from your application's entry point:

import postgres from "postgres";
import { createNotesApp } from "./app.js";

const sql = postgres(process.env.DATABASE_URL);
const { app } = await createNotesApp(sql); // ready() completes before listening
app.listen(3000);

To run the equivalent example directly from this repository, with Node.js 24+ and a new Postgres database:

npm ci
export DATABASE_URL='postgres://localhost/undercurrent_example'
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f examples/notes/schema.sql
node examples/notes/server.js

From another terminal:

curl -N 'http://localhost:3000/sync/0/-1?version=1.0.0'

The empty database produces manifest, hello, then idle heartbeats. Seed or change managed rows through undercurrent.write(...) to produce synced notes. The matching SQLite migration is sent in the manifest; the client does not receive Postgres's isDeleted column. The example resource is non-optimistic because it has a readonly synced field.

Field And Authentication Contracts

A scalar field such as title: "text" is non-null and client-modifiable. Descriptors accept type, optional boolean nullable, and optional boolean readonly. Nullable fields must be present with either a value or explicit JSON null. Readonly fields remain in manifests, readable snapshots, and storage, but clients must omit them from mutation bodies. Create/modify hooks return all synced fields, including readonly ones, and all private fields; server-managed timestamps may be omitted. See API.md for hook shapes.

Resources with readonly fields cannot be optimistic. Declaration rejects that combination before serving a manifest, following the Blackcurrant resource contract.

Authentication is app-owned. Return an anonymous principal only for known missing/invalid auth; let session-store exceptions fail the request instead of clearing auth cookies. Sync resolver exceptions send a terminal SSE protocol error after manifest, without hello. The operational undercurrent association cookie preserves existing response cookies and is not an auth secret.

Protocol References

Blackcurrant is authoritative for the wire protocol:

In the Mikabytes workspace, the client checkout is commonly at ../blackcurrant/main relative to this repository, or ../../blackcurrant/main from the older undercurrent/main worktree layout.

Path Purpose
GET /sync/<visibility>/<seq>?version=<runtime-version> SSE setup, compact frames, and reconciliation requests.
POST /reconciliation/<seq>?version=<runtime-version> Repair the client's complete visible object set with streamed NDJSON.
POST <resource-path> Add an object when a create hook is registered.
PUT <resource-path>/<id> Modify an object when a modify hook is registered.
DELETE <resource-path>/<id> Delete an object when a delete hook is registered.

Login, logout, uploads, and session management belong to the host application. Its endpoints can use undercurrent.write(...) for managed resource writes.

Verification

Use Node.js 24+ for the canonical suite (the example schema check uses built-in SQLite). Set TEST_DATABASE_URL to a disposable Postgres database where the role can create schemas and the citext extension. Tests create and remove isolated schemas; do not use a production database.

TEST_DATABASE_URL='postgres://localhost/undercurrent_test' npm test

For full client compatibility verification, also provide a Blackcurrant 4.0.0 checkout with its existing dependencies installed:

BLACKCURRANT_PATH=/path/to/blackcurrant TEST_DATABASE_URL='postgres://localhost/undercurrent_test' npm test

Without BLACKCURRANT_PATH, the cross-library test is explicitly skipped. With it, the actual Blackcurrant Node test runtime consumes the example's manifest, applies SQLite migrations, and reads synced snapshots. The regular suite also executes the README module against Postgres and checks its schema and snapshots against SQLite. requirements/README.md describes verification domains.

Documents

Path Purpose
ARCHITECTURE.md Components and data flow.
API.md Implemented application API.
SCHEMA.md Postgres, resource, manifest, and serialization contracts.
UPGRADING-2X.md Migration guidance for older servers.
DECISIONS.md Durable project decisions.
requirements/ Canonical behavior and proof index.
test/ Canonical executable proof.
changes/ Change history and verification records.
AGENTS.md Agent workflow instructions.

Dependencies

Dependencies

ID Version
express ^5.2.1
postgres ^3.4.9
yaml ^2.9.0
Details
npm
2026-11-17 17:06:13 +00:00
10
2026-11-19 21:05:23 +00:00
mikabytes
UNLICENSED
latest
137 KiB
Assets (1)
Versions (3) View all
1.0.2 2026-11-17
1.0.1 2026-05-25
1.0.0 2026-05-19