npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

db4ai

v0.3.6

Published

AI-powered database operations with CapnWeb RPC transport for db4

Readme

db4ai

npm version license TypeScript

(GitHub, npm)

The all-in-one client SDK for db4 - a globally distributed database built on Cloudflare's edge infrastructure.

Description

db4ai is the all-in-one client SDK for interacting with db4, a globally distributed document database built on Cloudflare's edge infrastructure. It provides:

  • Schema definition with DB() from IceType
  • Type-safe queries with full TypeScript inference
  • Real-time subscriptions via WebSocket
  • Automatic connection pooling and retry logic
  • Zero-configuration deployment when used with Cloudflare Workers service bindings

Features

  • Works in Cloudflare Workers, Node.js, and browsers
  • Type-safe queries powered by IceType schemas
  • Real-time subscriptions with WebSocket support
  • Automatic connection pooling and retry logic
  • Zero-config in Workers with service bindings

Installation

npm install db4ai

Usage

Schema-First (Recommended)

Define your schema using IceType and create a typed client:

import { DB, createClient } from 'db4ai'

// Define your schema using IceType
const schema = DB({
  User: {
    id: 'cuid!',
    email: 'string! #unique',
    name: 'string?',
    posts: '[Post] -> author',
  },
  Post: {
    id: 'cuid!',
    title: 'string!',
    content: 'text',
    author: 'User! <- posts',
  },
})

// Create a client from the schema
const db = createClient({ schema })

// Full type inference - no codegen needed
const user = await db.users.create({ email: '[email protected]', name: 'Alice' })
const posts = await db.posts.find({ where: { 'author.id': user.id } })

Direct Client

For when you have types defined separately:

import { db4 } from 'db4ai'
import type { Schema } from './schema'

// Initialize the client
const db = db4<Schema>({
  endpoint: 'https://your-db4.workers.dev',
  apiKey: process.env.DB4_API_KEY
})

// Create a document
const user = await db.users.create({
  name: 'Alice',
  email: '[email protected]'
})

// Query with type safety
const admins = await db.users.find({
  where: { role: 'admin' },
  orderBy: { createdAt: 'desc' },
  limit: 10
})

// Real-time subscriptions
const unsubscribe = db.users.subscribe(
  { where: { role: 'admin' } },
  (users) => console.log('Admins updated:', users)
)

Usage in Cloudflare Workers

When running inside a Cloudflare Worker, use the service binding for zero-latency access:

import { db4 } from 'db4ai'
import type { Schema } from './schema'

export default {
  async fetch(request: Request, env: Env) {
    const db = db4<Schema>({ binding: env.DB4 })

    const users = await db.users.find()
    return Response.json(users)
  }
}

API

Main client SDK for db4 databases:

function db4<Schema>(config: DB4Config): DB4Client<Schema>;

interface DB4Client<Schema> {
  [K in keyof Schema]: Collection<Schema[K]>;
}

Client Initialization

// Remote endpoint
const db = db4<Schema>({ endpoint, apiKey })

// Service binding (Workers only)
const db = db4<Schema>({ binding: env.DB4 })

// With options
const db = db4<Schema>({
  endpoint,
  apiKey,
  timeout: 30000,
  retries: 3,
  cache: 'default'
})

Collection Operations

// Create
await db.collection.create(document)
await db.collection.createMany(documents)

// Read
await db.collection.get(id)
await db.collection.find(query)
await db.collection.findOne(query)
await db.collection.count(query)

// Update
await db.collection.update(id, changes)
await db.collection.updateMany(query, changes)
await db.collection.upsert(query, document)

// Delete
await db.collection.delete(id)
await db.collection.deleteMany(query)

Query Options

const results = await db.users.find({
  where: {
    age: { $gte: 18 },
    status: 'active'
  },
  select: ['id', 'name', 'email'],
  include: {
    posts: { limit: 5 }
  },
  orderBy: { createdAt: 'desc' },
  limit: 100,
  offset: 0
})

Transactions

const result = await db.transaction(async (tx) => {
  const user = await tx.users.create({ name: 'Bob' })
  await tx.accounts.create({ userId: user.id, balance: 0 })
  return user
})

Real-time Subscriptions

// Subscribe to query results
const unsubscribe = db.users.subscribe(query, callback)

// Subscribe to a single document
const unsubscribe = db.users.subscribeOne(id, callback)

// Cleanup
unsubscribe()

Type Safety

db4ai provides full TypeScript inference from your IceType schema:

import { DB, createClient } from 'db4ai'

// Schema definition using DB()
const schema = DB({
  User: {
    id: 'cuid!',
    name: 'string!',
    email: 'string! #unique',
    age: 'int?',
    posts: '[Post] -> author',
  },
  Post: {
    id: 'cuid!',
    title: 'string!',
    content: 'text!',
    author: 'User! <- posts',
  },
})

const db = createClient({ schema })

// Full type inference - no codegen needed
type User = typeof db.types.User
// {
//   id: string
//   name: string
//   email: string
//   age?: number
//   posts?: Post[]
// }

Documentation

For complete documentation, visit db4.dev/docs

Related Packages

See Also

License

MIT