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

@zanzojs/drizzle

v0.3.2

Published

Drizzle ORM adapter for Zanzo ReBAC. Zero-config Zanzibar Tuple Pattern with parameterized SQL.

Downloads

50

Readme

@zanzojs/drizzle

npm version Drizzle ORM

The official Drizzle ORM adapter for ZanzoJS.

When to use this package

@zanzojs/drizzle serves two distinct purposes:

1. Write-time tuple materialization (materializeDerivedTuples / removeDerivedTuples) When you grant or revoke access via nested permission paths (e.g. folder.admin), you must pre-materialize the derived tuples in the database. This is what makes read-time evaluation fast.

2. SQL-filtered queries for large datasets When you need to fetch a filtered list of resources (e.g. "all documents this user can read") and the dataset is too large to load entirely into memory, the adapter generates parameterized EXISTS subqueries that push the permission filter directly to the database.

[!TIP] Performance Optimized: As of v0.3.0, the adapter automatically groups multiple permission paths into a single EXISTS subquery using an IN clause, providing significant performance gains for complex schemas.

// Without adapter — loads everything into memory and filters (inefficient for large datasets)
const allDocs = await db.select().from(documents);
const myDocs = allDocs.filter(d => snapshot['Document:' + d.id]?.includes('read'));

// With adapter — filter goes directly to SQL (efficient at any scale)
const myDocs = await db.select().from(documents)
  .where(withPermissions('User:alice', 'read', 'Document', documents.id));

Note: For the frontend snapshot flow, you don't need this adapter. The snapshot is generated by loading the user's tuples with engine.load() and calling createZanzoSnapshot(). The adapter is for backend queries that need SQL-level filtering.

Installation

pnpm add @zanzojs/core@latest @zanzojs/drizzle@latest drizzle-orm

Setup

1. Create the Universal Tuple Table

All relationships live in a single table. This is the Zanzibar pattern.

import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';

export const zanzoTuples = sqliteTable('zanzo_tuples', {
  id: integer('id').primaryKey({ autoIncrement: true }),
  object: text('object').notNull(),     // e.g. "Document:doc1"
  relation: text('relation').notNull(), // e.g. "owner"
  subject: text('subject').notNull(),   // e.g. "User:alice"
});

2. Create the adapter

import { createZanzoAdapter } from '@zanzojs/drizzle';
import { engine } from './zanzo.config';
import { zanzoTuples } from './schema';

export const withPermissions = createZanzoAdapter(engine, zanzoTuples);

3. Query pushdown

async function getReadableDocuments(userId: string) {
  return await db.select()
    .from(documents)
    .where(withPermissions(`User:${userId}`, 'read', 'Document', documents.id));
}

Cloudflare D1 & Edge Runtime

Zanzo is fully compatible with Cloudflare Pages and D1. Since the D1 driver for Drizzle is asynchronous, ensuring your adapter is correctly configured is key.

1. Configuration for D1

When using Cloudflare D1, always set the dialect to 'sqlite'.

import { createZanzoAdapter } from '@zanzojs/drizzle';
import { engine } from './zanzo.config';
import { zanzoTuples } from './schema';

// The adapter is synchronous (generates SQL filters), 
// but D1 execution is always asynchronous.
export const withPermissions = createZanzoAdapter(engine, zanzoTuples, {
  dialect: 'sqlite'
});

2. Usage in Next.js (middleware/layout)

When using @cloudflare/next-on-pages, you access the D1 binding via the Request Context.

import { getRequestContext } from '@cloudflare/next-on-pages';
import { drizzle } from 'drizzle-orm/d1';

export const runtime = 'edge';

export default async function Page() {
  const { env } = getRequestContext();
  const db = drizzle(env.DB);
  
  const myDocs = await db.select()
    .from(documents)
    .where(withPermissions('User:alice', 'read', 'Document', documents.id));
    
  return <pre>{JSON.stringify(myDocs)}</pre>;
}

3. Limitations & Differences

  • Async-only: D1 does not support synchronous queries. While withPermissions returns a synchronous SQL object, the final .where() call must be awaited as part of the Drizzle query.
  • AST Complexity: The Edge Runtime has strict CPU and memory limits. Use zanzo check in your CI/CD to ensure your schema doesn't generate overly complex ASTs (standard limit: 100 conditional branches).

Write Operations

Granting access with materializeDerivedTuples

When assigning a role that involves nested permission paths, use materializeDerivedTuples to materialize all derived tuples atomically.

import { materializeDerivedTuples } from '@zanzojs/core';

async function grantAccess(userId: string, relation: string, objectId: string) {
  const baseTuple = {
    subject: `User:${userId}`,
    relation,
    object: objectId,
  };

  const derived = await materializeDerivedTuples({
    schema: engine.getSchema(),
    newTuple: baseTuple,
    fetchChildren: async (parentObject, relation) => {
      const rows = await db.select({ object: zanzoTuples.object })
        .from(zanzoTuples)
        .where(and(
          eq(zanzoTuples.subject, parentObject),
          eq(zanzoTuples.relation, relation),
        ));
      return rows.map(r => r.object);
    },
  });

  await db.insert(zanzoTuples).values([baseTuple, ...derived]);
}

Revoking access with removeDerivedTuples

removeDerivedTuples is the symmetric inverse of materializeDerivedTuples. It identifies all derived tuples to delete.

import { removeDerivedTuples } from '@zanzojs/core';

async function revokeAccess(userId: string, relation: string, objectId: string) {
  const baseTuple = {
    subject: `User:${userId}`,
    relation,
    object: objectId,
  };

  const derived = await removeDerivedTuples({
    schema: engine.getSchema(),
    revokedTuple: baseTuple,
    fetchChildren: async (parentObject, relation) => {
      const rows = await db.select({ object: zanzoTuples.object })
        .from(zanzoTuples)
        .where(and(
          eq(zanzoTuples.subject, parentObject),
          eq(zanzoTuples.relation, relation),
        ));
      return rows.map(r => r.object);
    },
  });

  for (const tuple of [baseTuple, ...derived]) {
    await db.delete(zanzoTuples).where(and(
      eq(zanzoTuples.subject, tuple.subject),
      eq(zanzoTuples.relation, tuple.relation),
      eq(zanzoTuples.object, tuple.object),
    ));
  }
}

materializeDerivedTuples and removeDerivedTuples are symmetric. If materializeDerivedTuples derived a tuple, removeDerivedTuples will identify it for deletion. This guarantees no orphaned tuples.

Documentation

For full architecture details, see the ZanzoJS Monorepo.