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

@fitzzero/quickdraw-core

v5.1.4

Published

Fast fullstack patterns for real-time applications with Socket.io and TanStack Query

Downloads

4,783

Readme

@fitzzero/quickdraw-core

Typed real-time fullstack services on Socket.IO, TanStack Query and Prisma. A service is declared once, as a contract in the app's shared package; the server implements it and the client is typed from it. Writes are tracked, so every subscriber's live rows, lists and cached queries follow them without a single hand-written event.

  • Contracts: methods, projections, field tiers, collections, streams, channels and events, as plain data plus schemas (Standard Schema; Zod 4.2 or later where JSON Schema is needed).
  • Services: qd.defineService(contract, { ... }), one handler per method, access declared and failing closed, row policies shared by every surface.
  • Live data: tracked Prisma writes become entity frames, collection deltas and change topics, with revisions, resume after reconnect, and revocation when access is lost.
  • Client: qd.<service>.<member> hooks over TanStack Query, live entities and collections, optimistic mutations, one invalidation coordinator.
  • Kits: read/write, search, sharing and membership, admin, presence and streams, auth routes.
  • Transports: Socket.IO (protocol 5), HTTP, in process, MCP, and a shim for 4.x clients.
  • Testing: a real test server, access matrices, performance budgets that count statements and bytes, strict development warnings.

Design record: docs/rfcs/0003-v5.md.

Install

bun add @fitzzero/quickdraw-core zod
bun add express socket.io @prisma/client                   # the server
bun add socket.io-client @tanstack/react-query react        # the web app
bun add -d @fitzzero/quickdraw-lint @fitzzero/quickdraw-skills oxlint

Node 24 or later. Every peer dependency is optional: install the ones the entries you import need.

| Entry | Needs | | --------------------------------------- | ----------------------------------------------------------------------- | | . (contracts, errors, protocol types) | a Standard Schema library: Zod 4.2 or later where JSON Schema is needed | | ./server, ./server/mcp | socket.io; an Express 4 or 5 app (or none) for the HTTP transport | | ./server/auth | express-rate-limit for its default sign-in limits | | ./server/express | express-rate-limit | | ./server/otel | @opentelemetry/api | | ./prisma | @prisma/client 7 | | ./client | socket.io-client, @tanstack/react-query 5, react 19 | | ./client/core | socket.io-client | | ./utils, ./parser | nothing more | | ./testing | socket.io, socket.io-client | | ./testing/client | the ./client peers, and @testing-library/react | | ./testing/prisma | pg or @electric-sql/pglite |

Quick start

A board of tasks in the quickdraw template's layout: contracts in packages/shared, the server in apps/api, the web app in apps/web. The examples in this README compile: they are copies of packages/core/test/readme/, which the package's typecheck builds. The pieces the quick start imports without showing (the schemas, the auth helpers, the Prisma models) are under The example app.

1. The contract

packages/shared/src/contracts/task.ts. The shared package exports the contracts, and a map of them for the client: contracts = { label, project, task }.

import { crud, defineContract, mutation, query } from "@fitzzero/quickdraw-core";
import { z } from "zod";
import { cardSchema, taskSchema } from "../schemas";

export const taskContract = defineContract("taskService", {
  // what the service is for: MCP tools and the generated docs show it
  describe: "Tasks on a project's board.",
  // the full row; it must contain `id: string`
  entity: taskSchema,
  // lean shapes of the row
  projections: { card: cardSchema },
  // only callers with Admin on the task receive notes
  fields: { notes: "Admin" },
  methods: {
    // the read/write kit's get (one task by id) and create
    ...crud.contract({
      entity: taskSchema,
      get: true,
      // `id`: one the client may make (`newId()`), which the create keeps
      create: {
        input: z.object({ id: z.string().optional(), projectId: z.string(), title: z.string() }),
      },
    }),
    rename: mutation({
      input: z.object({ id: z.string(), title: z.string() }),
      output: "entity",
      describe: "Renames a task.",
    }),
    countOnBoard: query({
      input: z.object({ projectId: z.string() }),
      output: z.number(),
      // fetched again whenever the project's board changes
      watch: { collection: "board", scope: (input) => input.projectId },
      describe: "Counts the tasks on a project's board.",
    }),
  },
  collections: {
    // every task of a project, live, in board order
    board: {
      describe: "A project's tasks, in board order.",
      scope: "projectId",
      item: "card",
      order: [
        ["ordinal", "asc"],
        ["id", "asc"],
      ],
      // sent for the whole board
      index: ["status", "ordinal", "assigneeId"],
      views: { mine: (row, who) => row.assigneeId === who.userId },
    },
  },
});

2. The service

The app states its types once, with one tracked database client.

import { trackPrisma } from "@fitzzero/quickdraw-core/prisma";
import { prisma } from "@project/db";

// Every write through `db` is tracked: subscribers see it. Apply trackPrisma
// last, after any other client extension.
export const db = trackPrisma(prisma);
import { initQuickdraw, type Principal } from "@fitzzero/quickdraw-core/server";
import type { contracts } from "@project/shared";
import type { db } from "./db";

/** Who calls: a signed-in user, or an agent acting for one. */
export interface AppPrincipal extends Principal {
  readonly kind: "user" | "agent";
}

// The app's types, stated once: every service, handler and caller is typed from them.
export const qd = initQuickdraw<{
  db: typeof db;
  principal: AppPrincipal;
  // what the MCP bridge's context hook gives an agent's calls, as ctx.mcp
  mcp: { readonly scopes: readonly string[] };
  contracts: typeof contracts;
}>();

apps/api/src/services/task.ts implements every method of the contract, each with its access: the read/write kit's get and create in one spread, and a handler for each of the others:

import { crud, inherit } from "@fitzzero/quickdraw-core/server";
import { projectContract, taskContract } from "@project/shared";
import { qd } from "../quickdraw";

export const taskService = qd.defineService(taskContract, {
  // the Prisma model its rows live in
  model: "task",
  // the level on the task's project
  access: inherit({ from: projectContract, via: "projectId" }),
  // a board opens with Read on its project
  collections: { board: { anchor: projectContract } },
  methods: {
    // the kit implements get and create; each names who may call it
    ...crud.handlers(taskContract, {
      access: {
        get: { entry: "Read" },
        create: { scope: "Moderate", of: projectContract, id: "projectId" },
      },
    }),
    rename: {
      access: { entry: "Moderate" },
      // return the row: the framework sends the projection's fields, dates as ISO strings
      handler: ({ input, db }) =>
        db.task.update({ where: { id: input.id }, data: { title: input.title } }),
    },
    countOnBoard: {
      access: { scope: "Read", of: projectContract, id: "projectId" },
      // identical concurrent calls by one user run once
      share: "caller",
      handler: ({ input, db }) => db.task.count({ where: { projectId: input.projectId } }),
    },
  },
});

3. The server

apps/api/src/index.ts: the services on the app's own Express app.

import { socketAuth } from "@fitzzero/quickdraw-core/server/auth";
import express, { type Express } from "express";
import { jwtSecret, loadGrants, sessions } from "./auth";
import { db } from "./db";
import { qd, type AppPrincipal } from "./quickdraw";
import { labelService } from "./services/label";
import { projectService } from "./services/project";
import { taskService } from "./services/task";

// the web app's origins: CORS, and the pages that may open a socket with the session cookie
const webOrigins = ["http://localhost:3000"];

export const app: Express = express();

export const server = qd.createServer({
  // the HTTP transport is mounted on it: POST /qd/{service}/{method}
  app,
  services: [labelService, projectService, taskService],
  db,
  cors: { origin: webOrigins, credentials: true },
  auth: {
    // the session cookie the auth routes set, else a bearer token (`auth.token`); none is anonymous
    authenticate: socketAuth({
      sessions,
      jwtSecret,
      allowedOrigins: webOrigins,
      loadPrincipal: (userId): AppPrincipal => ({ userId, kind: "user" }),
    }),
    loadServiceAccess: (userId) => loadGrants(userId),
    // a tracked write to User.serviceAccess refreshes that user's open sockets
    serviceAccessSource: { model: "user", column: "serviceAccess" },
  },
  // close on SIGTERM and SIGINT; the process is never exited
  handleSignals: true,
});

server.httpServer.listen(4000);

4. The client

import { createQuickdrawClient } from "@fitzzero/quickdraw-core/client";
import { contracts } from "@project/shared";

// One typed client for the app: qd.task and qd.project, from the contracts.
export const qd = createQuickdrawClient(contracts);
"use client";

import { QuickdrawProvider } from "@fitzzero/quickdraw-core/client";
import type { ReactNode } from "react";
import { qd } from "../lib/quickdraw";

export function Providers({ children }: { readonly children: ReactNode }) {
  // Cookie sessions need no `auth`; a bearer token is `auth={token}`.
  return (
    <QuickdrawProvider client={qd} url="http://localhost:4000">
      {children}
    </QuickdrawProvider>
  );
}
"use client";

import { qd } from "../lib/quickdraw";

export function TaskBoard({ projectId }: { readonly projectId: string }) {
  // Live: tasks added, changed, moved or removed by anyone show at once.
  const { items, isLoading } = qd.task.board.useCollection(projectId);
  const { data: count } = qd.task.countOnBoard.useQuery({ projectId });
  // Optimistic: the new title shows before the server answers.
  const rename = qd.task.rename.useMutation();

  if (isLoading) {
    return <p>Loading…</p>;
  }
  return (
    <section>
      <h2>{`${String(count ?? items.length)} tasks`}</h2>
      <ul>
        {items.map((task) => (
          <li key={task.id}>
            {task.title}
            <button type="button" onClick={() => rename.mutate({ id: task.id, title: "Done" })}>
              Rename
            </button>
          </li>
        ))}
      </ul>
    </section>
  );
}

When another user adds, renames or moves a task, the board changes at once, and countOnBoard is fetched again because it watches the board.

The example app

The quick start is part of a small app in the template's layout, whose every file compiles with the package: packages/core/test/readme/. The label and project services the server registers are there, with the other sections' examples. These are the pieces the quick start imports without showing, which an app writes itself.

The schemas the contracts are built on, packages/shared/src/schemas.ts (the shared package exports them beside the contracts):

import { z } from "zod";

export const projectSchema = z.object({ id: z.string(), name: z.string(), ownerId: z.string() });

export const taskSchema = z.object({
  id: z.string(),
  projectId: z.string(),
  title: z.string(),
  status: z.string(),
  ordinal: z.number(),
  assigneeId: z.string().nullable(),
  notes: z.string().nullable(),
});

/** The lean shape a board shows. */
export const cardSchema = taskSchema.omit({ notes: true });

The sessions, the secret and the grants the server reads, apps/api/src/auth.ts. Sessions are issued by the auth routes, mounted on the same app (see the auth routes kit). verifySession checks a bearer token against the session store on every call (bearerAuth), so a signed-out or revoked session stops at once:

// The app's sessions, token check and grants, for the README's server examples.

import type { AccessLevel } from "@fitzzero/quickdraw-core";
import { bearerAuth, createMemorySessionStore } from "@fitzzero/quickdraw-core/server/auth";
import { db } from "./db";
import type { AppPrincipal } from "./quickdraw";

/** Signs the session JWTs: one secret for the auth routes and `socketAuth`, 32 characters or more. */
export const jwtSecret = process.env.JWT_SECRET ?? "";

/** The sessions the auth routes issue. In production, a store over the database (see the auth routes kit). */
export const sessions = createMemorySessionStore();

/**
 * The agent a bearer token signs in, or `null` for no token: checked against
 * the session store on every call, so a signed-out or revoked session stops
 * at once. An agent, so methods with `kinds: ["user"]` refuse it. Never
 * `verifyJWT` alone, which checks no session.
 */
export const verifySession = bearerAuth({
  sessions,
  jwtSecret,
  loadPrincipal: (userId): AppPrincipal => ({ userId, kind: "agent" }),
});

/** A user's service-wide grants, as stored in `User.serviceAccess`. */
export async function loadGrants(userId: string): Promise<Record<string, AccessLevel>> {
  const user = await db.user.findUnique({ where: { id: userId }, select: { serviceAccess: true } });
  const stored: unknown = user?.serviceAccess;
  return typeof stored === "object" && stored !== null
    ? (stored as Record<string, AccessLevel>)
    : {};
}

The Prisma models of @project/db (packages/db/prisma/schema.prisma), User.serviceAccess among them, which loadGrants reads and serviceAccessSource watches:

model User {
  id            String          @id @default(cuid())
  email         String          @unique
  name          String
  // Service-wide grants, as 4.x apps store them: { "taskService": "Admin" }.
  serviceAccess Json?
  ownedProjects Project[]
  memberships   ProjectMember[]
  assigned      Task[]
}

model Project {
  id        String          @id @default(cuid())
  name      String
  ownerId   String
  // A JSON access list, [{ userId, level }].
  acl       Json?
  archived  Boolean         @default(false)
  owner     User            @relation(fields: [ownerId], references: [id])
  members   ProjectMember[]
  tasks     Task[]
  labels    Label[]
}

// A membership table: role holds an access level ("Read" | "Moderate" | "Admin").
// It has an id, and its pair is unique by @@unique: the write tracker keys
// rows by id, so a table keyed by a composite @@id is never tracked, and a
// member removed from it would never be revoked.
model ProjectMember {
  id        String  @id @default(cuid())
  projectId String
  userId    String
  role      String
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
  user      User    @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([projectId, userId])
  @@index([userId])
}

model Task {
  id           String      @id @default(cuid())
  projectId    String
  parentTaskId String?
  status       String      @default("open")
  ordinal      Int         @default(0)
  title        String
  assigneeId   String?
  notes        String?
  // A flag and a JSON column: every field type the admin kit edits.
  pinned       Boolean     @default(false)
  details      Json?
  createdAt    DateTime    @default(now())
  updatedAt    DateTime    @updatedAt
  project      Project     @relation(fields: [projectId], references: [id], onDelete: Cascade)
  parent       Task?       @relation("Subtasks", fields: [parentTaskId], references: [id], onDelete: SetNull)
  subtasks     Task[]      @relation("Subtasks")
  assignee     User?       @relation(fields: [assigneeId], references: [id], onDelete: SetNull)
  labels       TaskLabel[]

  @@index([projectId, status, ordinal])
}

model Label {
  id        String      @id @default(cuid())
  projectId String
  name      String
  project   Project     @relation(fields: [projectId], references: [id], onDelete: Cascade)
  tasks     TaskLabel[]
}

model TaskLabel {
  id      String @id @default(cuid())
  taskId  String
  labelId String
  task    Task   @relation(fields: [taskId], references: [id], onDelete: Cascade)
  label   Label  @relation(fields: [labelId], references: [id], onDelete: Cascade)

  @@unique([taskId, labelId])
  @@index([labelId])
}

Contracts

A contract is plain data plus schemas, so browser code imports it without any server code (design: docs/rfcs/0003-v5.md, section 2).

export const labelContract = defineContract("labelService", {
  describe: "Labels a project puts on its tasks.",
  entity: labelSchema,
  projections: { chip: z.object({ id: z.string(), name: z.string() }) },
  methods: {
    find: query({
      input: z.object({ name: z.string() }),
      output: nullable("entity"),
      describe: "Finds a label by its name, or null.",
    }),
    chips: query({
      input: z.object({ projectId: z.string() }),
      output: listOf("chip"),
      describe: "Lists a project's labels as chips.",
    }),
    usage: query({
      input: z.undefined(),
      output: z.record(z.string(), z.number()),
      describe: "Counts the tasks of each label.",
    }),
  },
});

// No entity: an RPC-only service, with no projections, field tiers or collections.
export const healthContract = defineContract("healthService", {
  describe: "Tells a caller the server is up.",
  methods: {
    ping: query({
      input: z.undefined(),
      output: z.literal("pong"),
      describe: "Answers pong while the server runs.",
    }),
  },
});
  • Every method is a query or a mutation, with an input and an output. The kind decides request sharing, cancellation, the concurrency cap, the MCP read-only hint and which client hook exists.
  • Every member takes a describe, a sentence or two for people and agents: the contract itself (what the service is for), each method (its MCP tool's description), collection, stream, channel and event. quickdraw-docs leads each section of the API docs with it. It is optional in the types; lint's require-describe (a warning) lists each member without one.
  • output is a schema, or a projection: "entity", a named projection, nullable("entity") or listOf("card"). A handler returns database rows for a projection output, and the framework projects them.
  • entity and every projection contain id: string. A contract without an entity is an RPC-only service.
  • Only a query may watch ({ collection, scope: (input) => scopeId }): the client joins that scope's change topic and fetches the query again when it changes.
  • Methods, collections, streams, channels and events share one namespace, because the client exposes each as qd.<service>.<name>. subscribe, unsubscribe, call, then, useEntity, useEntities, admin and names starting with $ are reserved.
  • A service name holds no : or @: it is part of every room name of the service (qd:e:{service}:{id}@{level}, qd:c:{service}:{collection}:{scope}), which must split one way only, so defineContract throws on one.
  • Schemas are any Standard Schema. A projection's keys, admin field metadata, MCP tool schemas and quickdraw-docs read Standard JSON Schema, which Zod 4.2 or later provides; a projection whose schema cannot describe itself declares keys in the service's project option.

Types come from the contract too:

// { id: string; title: string }
export type RenameInput = InputOf<typeof taskContract, "rename">;
// the entity, as the wire has it
export type Task = OutputOf<typeof taskContract, "get">;
// one item of the board
export type Card = ItemOf<typeof taskContract, "board">;

InputOf, ParsedInputOf, OutputOf, EntityOf, ProjectionOf, ItemOf, ScopeOf, IndexRowOf, ViewName and the rest are exported from the package root. FullProjectionOf<C, P> is a projection's full row (what a handler builds, every tiered field present), and ReceivedRow<C, Row> makes a row's tiered fields optional, as a reader receives it.

Services

qd.defineService(contract, definition) implements a contract (design: section 3). methods must implement exactly the contract's methods; each is { access, handler }, plus timeoutMs, and for a query share, ttlMs and version.

export const taskService = qd.defineService(task, {
  model: "task",
  methods: {
    assign: {
      access: { service: "Moderate" },
      // instead of the dispatcher's callTimeoutMs (30 s)
      timeoutMs: 5_000,
      handler: async ({ input, ctx, db }) => {
        // an agent's call carries its token's scopes as ctx.mcp; a user's call has none
        if (ctx.mcp !== undefined && !ctx.mcp.scopes.includes("tasks")) {
          throw new QuickdrawError("FORBIDDEN", "This token may not assign tasks");
        }
        const found = await db.task.findUnique({ where: { id: input.id } });
        if (found === null) {
          // the caller receives the code
          throw new QuickdrawError("NOT_FOUND", "No such task");
        }
        ctx.log.info("assigning", { by: ctx.principal.userId, transport: ctx.transport });
        return db.task.update({ where: { id: input.id }, data: { assigneeId: input.assigneeId } });
      },
    },
  },
});
  • A handler receives { input, ctx, db }: the input after its schema ran, the call's context, and the tracked database client. ctx holds principal (userId, kind, claims, serviceAccess; null only in a "public" method called anonymously), signal (aborts on cancel or time limit), log, requestId, transport ("socket", "http", "mcp", "internal" or "legacy"), touch (below), rooms and presence (realtime, below), mcp (the MCP bridge's context) and services.
  • ctx.services calls the app's services in process, as the same principal, by service name: await ctx.services.projectService.get({ id }). Each call runs the whole pipeline with transport "internal" (input check, access, handler, output check), so access is checked on the inner call too; its writes join the calling method's unit of work, so both flush together once; and it is cancelled with ctx.signal. It carries the calling method's ctx.mcp as well: every call an MCP call makes through ctx.services, nested ones included, sees the MCP call's fields with transport "internal", so tell a token's call apart by ctx.mcp, never by ctx.transport. It is typed by the contracts of initQuickdraw's types, as qd.caller is.
  • timeoutMs is how long the caller waits (else the dispatcher's limits.callTimeoutMs, 30 s). At the limit the caller gets TIMEOUT and ctx.signal aborts, but a handler still running runs on, and what it writes still commits and is pushed: TIMEOUT says the server stopped waiting, not that nothing happened. A method that waits on a slow outside API passes it ctx.signal, calls ctx.signal.throwIfAborted() before it writes the outcome, and sets timeoutMs above its slowest path. The server logs a warning (category quickdraw.call) when a call that answered TIMEOUT goes on to commit writes. A nested ctx.services call's writes flush with its caller's run, so the warning fires only when that outermost call answered TIMEOUT.
  • share: "caller" runs identical concurrent calls of one principal once, share: "all" across principals; ttlMs keeps a shared result. A "all" run's handler sees the first caller's ctx and every caller gets its result, so a result shared across principals must depend on the input only: it never reads ctx.principal, ctx.services, ctx.mcp, ctx.access or a context field made from them (in development, reading one of the first four warns [quickdraw:shared-principal]; copying or logging the whole ctx reads them too). "all" is refused with custom access and on the kit methods whose result depends on the caller (the read/write kit's list and getMany, search, the sharing kit's listShares and listMembers, the admin kit's adminList and adminGet): give those "caller". Callers of a shared run whose levels hide the same fields get one copy of its result, encoded once for all of their sockets. version(input, ctx) answers "not modified" for a query whose result the caller already holds.
  • Every call runs a pipeline: look up, concurrency (16 queries in flight per socket and 64 queued, then RATE_LIMITED; mutations are not queued behind queries), input validation, access, "not modified", sharing, the handler under a time limit (30 s by default), the result shaped to its output (below), output validation outside production, the reply, the flush, and one completion record (onCall). A mutation ignores the caller's cancel: only its time limit ends the call early, and its handler runs on even then (timeoutMs, above).
  • A method's output is sent as it declares it, on every transport and in production too, so a handler may return the whole row: a projection output ("entity", a named projection) sends the projection's keys, stripped per caller (below), and an output schema of the method's own sends what its JSON Schema declares (Zod 4.2 or later). An object keeps the keys its properties declare, and every key only where additionalProperties allows them (z.looseObject, .catchall) or it is a record; an array keeps its items, each reduced by its item schema; a union keeps what any branch declares; a value the schema allows to be anything (z.unknown(), a Date) goes as it is. An output schema without JSON Schema (Zod 3) is sent as the handler returns it.

Errors are QuickdrawError(code, message, data?). Anything else a handler throws reaches the caller as INTERNAL with a generic message, and is logged; Prisma's unique violation becomes CONFLICT and its missing row NOT_FOUND.

| Code | HTTP | Meaning | | ----------------- | ---- | -------------------------------------------------------- | | UNAUTHENTICATED | 401 | no principal | | FORBIDDEN | 403 | access denied | | NOT_FOUND | 404 | unknown service, method or row | | CONFLICT | 409 | unique or state conflict | | VALIDATION | 422 | input failed its schema; data.issues lists paths | | RATE_LIMITED | 429 | limiter or queue overflow; data.retryAfterMs | | CANCELLED | 499 | the caller cancelled | | TIMEOUT | 504 | the server stopped waiting; the handler may still commit | | INTERNAL | 500 | everything else |

An app adds its own fields to every ctx once, through initQuickdraw:

interface AppContext {
  /** The tenant every query of this call is scoped to. */
  readonly tenantId: string;
}

export const qd = initQuickdraw<{ db: typeof db; principal: Principal; context: AppContext }>({
  // runs once per call, before access is checked, so custom checks see it too
  context: (base) => ({ tenantId: String(base.principal?.claims?.tenant ?? "public") }),
});

Access control

Each method declares who may call it, and a service with rows declares one access policy that says how a principal's level on a row is found (design: section 4). Everything fails closed: a method without access does not compile, and a missing grant, an unknown level, a missing id, a row that does not exist or a malformed access list denies.

import { anyOf, crud, custom, inherit, jsonAcl, members } from "@fitzzero/quickdraw-core/server";

export const projectService = qd.defineService(project, {
  // the Prisma model the rows live in
  model: "project",
  access: anyOf(
    // [{ userId, level }] plus Admin for the owner
    jsonAcl("acl", { owner: "ownerId" }),
    members({ model: "projectMember", entry: "projectId", user: "userId", level: "role" }),
  ),
  methods: {
    // the read/write kit's get: Read on the project itself
    ...crud.handlers(project, { access: { get: { entry: "Read" } } }),
    title: {
      // anyone may read any project's name by its id: the form is the whole check, on purpose
      access: "public",
      rowless: true,
      handler: async ({ input, db }) =>
        await db.project.findUniqueOrThrow({ where: { id: input.id }, select: { name: true } }),
    },
  },
});

export const taskService = qd.defineService(task, {
  model: "task",
  // the level on the task's project
  access: inherit({ from: project, via: "projectId" }),
  methods: {
    rename: {
      access: { entry: "Moderate" },
      handler: ({ input, db }) =>
        db.task.update({ where: { id: input.id }, data: { title: input.title } }),
    },
    // the kit's create: Moderate on the project the task goes into
    ...crud.handlers(task, {
      access: { create: { scope: "Moderate", of: project, id: "projectId" } },
    }),
    archiveAll: {
      access: { service: "Admin" },
      handler: async ({ db }) => (await db.task.updateMany({ data: { status: "archived" } })).count,
    },
    claim: {
      access: { entry: "Moderate" },
      // users only: an agent acting for one is refused, whatever its grants
      kinds: ["user"],
      handler: ({ input, ctx, db }) =>
        db.task.update({ where: { id: input.id }, data: { assigneeId: ctx.principal.userId } }),
    },
    triage: {
      // Moderate on the task's project, from a token that may triage: claims add to the form
      access: { entry: "Moderate" },
      claims: (claims, input) => claims?.scope === "triage" && input.status !== "archived",
      handler: ({ input, db }) =>
        db.task.update({ where: { id: input.id }, data: { status: input.status } }),
    },
    assigned: {
      // Read on the project the input names, asked through ctx.access; none named, the caller's
      // own that they may still read
      access: custom(
        async (ctx, input) =>
          input.projectId === undefined || (await ctx.access.can(project, input.projectId, "Read")),
      ),
      handler: async ({ input, ctx, db }) => {
        const readable = await ctx.access.where(task, "Read");
        if (readable === "none") return [];
        return db.task.findMany({
          where: {
            AND: [{ assigneeId: ctx.principal.userId, projectId: input.projectId }, readable],
          },
          take: 100,
        });
      },
    },
  },
});
  • Forms: "public", "authenticated", { service: L } (the user's service-wide grant), { entry: L, id? } (the policy's level on the row; id defaults to input.id), { service: L1, entry: L2 } (either), { scope: L, of, id } (the level on a row of another service) and custom(fn). Without a principal every form but "public" answers UNAUTHENTICATED; a principal that fails gets FORBIDDEN. The levels, lowest first, are Public, Read, Moderate and Admin. A custom form replaces the row check, and a service-wide Admin grant skips it: a check on the caller's claims is claims (below), and one that needs the caller's level on a row asks ctx.access (assigned above, and below).
  • kinds, beside access, says which kinds of principal (principal.kind) may call: initQuickdraw({ kinds: ["user", "agent"] }) for every service the app defines, defineService(contract, { kinds }) for one service, and a method's own kinds (claim above). Each level only narrows the one above it: a wider or empty list is refused when the service is defined. A principal of another kind, or without a kind, gets FORBIDDEN before the form is asked, and no grant passes the check, a service-wide Admin grant included, since a token acting with someone's grants is what it stops. An anonymous caller is left to the form, so a "public" method takes no kinds of its own: a refused caller would call it signed out. A service's list also holds for its entity, collection, topic and stream subscriptions, and its channels drop the messages of other kinds.
  • claims: (claims, input) => boolean, beside access on a method, is a requirement on the caller's verified claims (principal.claims, a token's scope; triage above). It adds to the form, so triage needs Moderate on the task's project and a triage token. It runs right after kinds, outside the access engine, so no grant passes it, a service-wide Admin grant included. Without a principal the call is UNAUTHENTICATED; when it returns anything but true, FORBIDDEN. It is synchronous, and a "public" method takes none. A token narrowed by claims is narrowed only on the methods that declare it; elsewhere it acts with its user's grants (kinds keeps a kind of token out).
  • On a service with a policy, a method whose input has id under a form that asks the policy nothing about the row that id names would let anyone that form admits reach any row by its id, so defineService refuses it, naming the method and the ways out. Those forms are the ones that check no row ("public", "authenticated", { service: L } below Admin), custom(fn), { scope, of, id } (a row of another service) and { entry, id } naming another key. The ways out: a form the policy decides ({ entry: L }, or { service: L, entry: L } to keep the grant, with claims beside it for a check on the caller's claims), or rowless: true on the method when every such caller may reach any row on purpose (the title method above; public profiles, lookups by an id that tells nothing), or when id names a row the method creates (an id the client made, under a scope form). A rowless query under a form that checks no row also answers "not modified" for any id; under any other form it runs its handler every time. A kit's methods take it as rowless: ["get"] in the kit's options. The input's keys come from its JSON Schema: an id in any branch of a union counts, and so does one beside a value JSON Schema cannot write (a Date, a Set). Not checked: an input without JSON Schema (Zod 3) or whose JSON Schema names no keys (a todoSchema without keys), one that is no object (a bare string that is the id itself), a row named by another key (ids, taskId, a nested where.id) under a form that checks the row id names, and an entry form whose id is a function, which names its row in code.
  • A service-wide Admin grant passes every access form on its service (adminBypass: false turns that off), though not kinds or claims. A grant below Admin counts only where the form names service: a Read grant does not read every row.
  • Grants come from principal.serviceAccess, as authenticate returns it or createServer({ auth: { loadServiceAccess } }) loads it for a principal that carries none: at a socket's handshake, for each HTTP call, and for an in-process caller (qd.caller) at its first call. With auth.serviceAccessSource: { model: "user", column: "serviceAccess" }, a tracked write to that column refreshes the user's open sockets (qd:access), and in-process callers load the grants again.
  • Policies: owner(field), jsonAcl(field, { owner? }), members({ model, entry, user, level, levels? }), inherit({ from, via }), anyOf(...), resolver({ levelsFor, where?, reads }) and everyone(level) (every signed-in user has level on every row, reading nothing: public profiles are anyOf(owner("id"), everyone("Read")); unlike rowless: true on a method, it covers subscriptions and lists too). A resolver is app code, so it says what its levels depend on: reads: { columns, memberships } names columns of the service's model and membership tables as members takes them (entry holding this service's row id), and tracked writes to them re-check what it decided, as for the other policies; reads: "none" says nothing a tracked write changes can change a level (the principal's grants alone, say). A resolver with neither is never re-checked, and the server warns [quickdraw:resolver-without-reads] when it starts. Their column and table names are checked against the Prisma client's models at compile time. A lookup is one batched query per table, memoized for the call, so checking 60 ids costs what checking one does. entry access needs a policy; a service without model may only use "public", "authenticated", { service } and custom. inherit uses the parent's policy only: grants on the parent's service do not flow down. A membership table needs an id column (the pair unique by @@unique), or its writes are not tracked and a removed member is never revoked.
  • One policy decides every surface: method calls, entity subscriptions, collection scopes, the kits' lists and searches, streams and channels.
  • When a tracked write lowers or removes someone's access, a relation-form foreign key included (project: { connect }), their sockets leave the rooms anchored on that row and get qd:revoked; a changed level moves them to that level's room. In a cluster the change is broadcast to every node. Every socket's re-resolution settles before the flush's frames go out, a failed one included.
  • server.dispatcher.access gives the same answers to other code: levelsFor(service, principal, ids), accessWhere(service, principal, level) (a where filter for findMany, or "none") and onAccessChanged(listener).
  • ctx.access gives them to a handler or a custom form, as the caller: levelsFor(service, ids), can(service, id, level) and where(service, level) are those bound to ctx.principal, with the grants the call runs with (a socket's, or those an in-process caller loaded); service is a contract or a service name. A form can then check a row no { entry } or { scope } form names: a parent the input names, or a key that is optional, as in assigned above, which passes without a project and needs Read on one it names. Its handler adds where(task, "Read") to its query with AND, so a list without a project still follows the row policy. Never spread the filter into where: it and the input both set projectId, and whichever comes last wins, widening a list with a project or dropping the policy from one without. ctx.access counts levels as { entry } does: a service-wide Admin grant reaches every row (with adminBypass), a row that is not found gives anyone else no level (can is false), and an anonymous caller has none anywhere (an empty map, false, "none"). So a form that asks it about a parent counts a service-wide Admin grant on the parent's service, which { scope, of } does not: prefer { scope: L, of, id } when the input always names the parent. A custom form is still no row check of the method's own id: a method whose input has one needs rowless: true beside it (above). Every method call has it, MCP and ctx.services calls included, and so do the ctx the kits pass to their forms and callbacks; a context no dispatcher built throws INTERNAL on its use, and qd has none: a job asks server.dispatcher.access.
  • createServer({ access: { cacheMs: 30_000 } }) keeps policy lookups across requests; tracked writes to the columns and membership tables the policies read evict them as soon as the write is durable (a transaction's at its commit, a rolled-back one never), so a check later in the same call sees it, as does any other request on that node. Servers behind a cluster adapter evict when the write's flush broadcasts its access change, after the call. A process that broadcasts nothing (a job on a bare createDispatcher, or a server without a cluster adapter) reaches other processes' caches only when the time passes, as do writes the tracked client cannot see, so the cache is off by default. A lookup inside a transaction (db.$transaction, a sharing change) reads the database, never the cache.

Tracked writes

@fitzzero/quickdraw-core/prisma wraps the app's Prisma client so the framework sees every write made through it (design: section 5). Pass the tracked client as db; the server finds the rest on it.

  • Every handler runs in a unit of work. Each create, update, upsert, delete, createMany, updateMany and deleteMany made through db is recorded with its row ids, merged per row, and handed to the flush sinks once the response has been sent, with one revision per flush. A handler may return db.task.update(...) without awaiting it.
  • A write that certainly changed nothing is not recorded, so it sends no frame, no collection delta, no topic change and no refreshEntry: an updateMany, updateManyAndReturn or deleteMany that matched no row, and a data (or an upsert's update) with nothing to write, {}. An upsert with update: {} ("make sure this row exists") reads the row first in its place: one statement when the row is there, and the upsert after it when it is not. Every other write is recorded, one that sets a column to the value it already held too: the values the framework reads before a write cannot prove it changed nothing, since another write may land between that read and the write.
  • Writes inside db.$transaction join the unit only when it commits; a rollback drops them. Prefer the interactive form (db.$transaction(async (tx) => ...)): an array-form db.$transaction([...]) has no transaction client, so the rows a deleteMany or updateMany in it reads first, and the old values an update that moves a row or changes who may see it reads first, are read outside the batch, and rows its earlier statements changed may be missed (a development warning names the model and operation).
  • A transaction nested in an interactive one, tx.$transaction(async (inner) => ...), runs as a savepoint of it (Prisma 7) and is tracked the same way: its writes join the transaction around it when the savepoint is released, and are dropped when it rolls back, even when the transaction around it catches the error and commits. Inside a transaction's callback, write through its client (tx, inner) what must commit or roll back with it. Work on db there runs outside the transaction, on a connection of its own, and is tracked as such: a write (a createMany or updateMany too) commits at once, and a db.$transaction of its own commits on its own, so their frames are sent whatever the transaction then does. (A database with one connection, as PGlite in tests, runs that work only once the transaction ends.) A transaction's client writes to its own transaction wherever it is used, inside another transaction's callback too, and once that transaction ended its writes are refused, as Prisma refuses them. An array-form $transaction([...]) begun on either client is a transaction of its own, as Prisma runs it: the root client's operations in it commit with it, while one made on tx in it runs in tx's transaction (the tracking hook awaits it there; Prisma alone would run it in the batch).
  • Write many rows in one statement when every row gets the same data (updateMany, createMany). When each row's data differs (moving tasks to different projects, say), write each row by id inside an interactive transaction: inside db.$transaction(async (tx) => ...), loop over the rows and await tx.task.update({ where: { id }, data }) for each. Neither the N+1 warning nor no-db-call-in-loop counts those writes.
  • A service lists the other models its handlers write (writes: ["taskLabel"]); the no-foreign-write lint rule checks it.
  • Jobs, scripts and webhooks wrap their writes in qd.run(fn), which flushes before it returns. A write made outside any unit of work flushes on its own on the next tick, with a development warning. Inside a handler qd.run joins the handler's unit; background work the reply does not wait for (a push sent after a message, pruning what it reports dead) runs in qd.run(fn, { detached: true }), a unit of its own that flushes when fn settles (catch what the promise rejects with: nothing awaits it). Before any server exists (a seed at boot, before createServer), qd.run(fn) still runs fn in a unit of its own, and its writes reach no one: no socket can be subscribed yet (behind a cluster, write after createServer when other nodes' subscribers must hear of it).
export async function markStale(before: Date): Promise<number> {
  // a job's writes flush to subscribers when qd.run settles, as a method's do
  const { count } = await qd.run(() =>
    db.task.updateMany({
      where: { status: "open", updatedAt: { lt: before } },
      data: { status: "stale" },
    }),
  );
  return count;
}
  • A helper that writes takes the tracked client by its type. trackPrisma returns Tracked<C>: still a C wherever one is asked for, while the untracked client is no Tracked<C>. Type the helper's client Tracked<PrismaClient>, or TrackedTransaction<PrismaClient> when it may also run inside db.$transaction(async (tx) => ...), whose tx is one (db is one too), and the untracked client passed to it is a type error. A helper typed PrismaClient takes either client. Both types are type-only, on ./prisma and on the root export, so a shared package names them without Prisma. no-untracked-write reads the type too, when the file imports it from quickdraw (under any name): a parameter, a destructured binding or a class member so typed may be named prisma.
import type { TrackedTransaction } from "@fitzzero/quickdraw-core/prisma";
import type { PrismaClient } from "@project/db";

// takes the tracked client, or a transaction's: passing the untracked `prisma` is a type error
export async function reopenStale(
  client: TrackedTransaction<PrismaClient>,
  projectId: string,
): Promise<number> {
  const { count } = await client.task.updateMany({
    where: { projectId, status: "stale" },
    data: { status: "open" },
  });
  return count;
}

export async function restoreProject(projectId: string): Promise<number> {
  return await qd.run(() =>
    db.$transaction(async (tx) => {
      await tx.project.update({ where: { id: projectId }, data: { archived: false } });
      return await reopenStale(tx, projectId);
    }),
  );
}
  • Not seen: the related rows of a nested write ({ labels: { create: [...] } }, which warns in development), raw SQL and database cascades. A foreign key a nested write sets on the written row (project: { connect }, parent: { disconnect: true }) is seen: such an update or upsert reads the row's interested columns first, one more statement. Before deleting a row, delete or clear through db the rows a cascade would take with it (for the admin kit's adminDelete, in its prepare). Record raw SQL with ctx.touch("task", ids), or { removed: true } for deleted rows. A touch inside a transaction's callback joins that transaction, as a write through tx there would: touch a root db.$executeRaw made there after the callback, or the transaction's rollback drops it. A job gets the same touch from qd.run, whose fn receives { touch, log, principal: null }:
export async function spreadOrdinals(projectId: string): Promise<void> {
  await qd.run(async (ctx) => {
    const rows = await db.$queryRaw<{ id: string }[]>`
      UPDATE "Task" SET "ordinal" = "ordinal" * 2 WHERE "projectId" = ${projectId} RETURNING "id"`;
    // raw SQL is invisible to the tracked client: record the rows it changed
    ctx.touch(
      "task",
      rows.map((row) => row.id),
    );
  });
}
  • Tracked models need a string id column; writes to other models pass through untracked, with one warning. Membership and junction tables included: give them id String @id @default(cuid()) and keep the pair unique with @@unique([...]), never a composite @@id. createServer checks, at start, every model a policy, a membership table or a via junction depends on, and logs [quickdraw:untracked-access-model] as an error, in every environment, for one it cannot track; a test app made with strictWarnings fails to start.
  • createServer({ flushSink }) adds the app's own sinks (an audit log, say); createRecordingSink() on ./testing records what is flushed, for tests.

Projections and entity subscriptions

A projection is the wire shape of a row (design: section 6). Its keys decide what a read selects, so a row is never read wider than what is sent:

import { crud, inherit } from "@fitzzero/quickdraw-core/server";

export const taskService = qd.defineService(task, {
  model: "task",
  access: inherit({ from: projectContract, via: "projectId" }),
  // answers "not modified" from the row's own time
  versionColumn: "updatedAt",
  // a write to a subtask sends its parent again
  affects: [{ service: task, id: "parentTaskId" }],
  project: {
    // a relation count: read with select, built by a pure, synchronous map. Read the relation's
    // ids, which Prisma fetches for the rows read only; its _count aggregates the whole TaskLabel
    // table (a GROUP BY over every row) on every snapshot and flush
    card: {
      select: { title: true, status: true, labels: { select: { id: true } } },
      map: (row: { id: string; title: string; status: string; labels: { id: string }[] }) => ({
        id: row.id,
        title: row.title,
        status: row.status,
        labelCount: row.labels.length,
      }),
    },
  },
  methods: {
    // the kit's get reads the entity's keys only, and sends dates as ISO strings
    ...crud.handlers(task, { access: { get: { entry: "Read" } } }),
    // returns the database row `map` takes: the framework builds the card from it
    card: {
      access: { entry: "Read" },
      handler: ({ input, db }) =>
        db.task.findUniqueOrThrow({
          where: { id: input.id },
          select: { id: true, title: true, status: true, labels: { select: { id: true } } },
        }),
    },
  },
});
  • A count over a relation reads the relation's ids (labels: { select: { id: true } }) and counts them in map: Prisma reads them for the rows read only (a second SQL query, WHERE "taskId" IN (...)). Its _count compiles to a GROUP BY over the whole relation table, joined in, on every snapshot, page and flush that reads the projection. For a relation too large to read (a chat's members), keep a counter column that the writes maintain.
  • A projection's keys come from its schema's JSON Schema (Zod 4.2 or later), or from project: { <name>: { keys } }; a service whose projection has neither fails when it is defined. A handler returning a projection returns rows (a Date is fine where the wire has a string, a Prisma Json column (JsonColumnValue) where it has an object, an array or a record, and extra columns are dropped); with map, it returns what map takes.
  • Fields the contract's fields map puts above the caller's level on a row are stripped from that caller's copy, after any shared run. Only a projection output is stripped per caller ("entity", a named projection, and nullable(...) or listOf(...) of one): a method whose output is a schema of its own sends what that schema declares to every caller its access admits, so a tiered key the schema declares, at any depth (email in a hand-written { id, name, email }, or in { user: { id, email } }), reaches callers below its level. When a server is made, each such method raises the development warning [quickdraw:tiered-field-in-output] (thrown by createTestApp({ strictWarnings: true }), so the test app fails to start): answer "entity" or a projection, or drop the key from the schema. Not warned: a method whose access admits no caller below the field's level ({ service: "Admin" } with the Admin bypass on, { entry: L } with L at the field's level or above), and a kit's methods, which strip their own replies. An output without JSON Schema (Zod 3) cannot be reduced, so in development each tiered key its replies carry raises the warning when a reply first carries it.
  • affects names rows of other services a write changes too ({ service, id: column }, or { service, id: (row) => ids, columns }); they are sent again after the flush, one hop.
  • qd.<service>.useEntity(id) subscribes with qd:sub { s, ids, revs? } (up to 500 ids per batch), which authorizes every id in one lookup, reads the allowed rows in one query and joins the room of each row found for the subscriber's level. A socket is never in the room of a row it could not read.
  • After each flush, subscribers get qd:e: { t: "u", s, id, rev, d } with the whole row (a create, a touch, a projection with map, an affects row), { t: "p", s, id, rev, d } with the changed fields only (an update of plain projection fields), or { t: "r", s, id, rev } (a delete). One read per service per flush, none when no room has subscribers, and each frame is stripped once per subscriber tier.
  • "Not modified" (for qd:sub and for queries returning one projection row by id) comes from versionColumn, or from an in-process change log of recent flushes. The change log sees only this process's writes: an app running several processes without a Socket.IO cluster adapter declares versionColumns or passes changeLog: false. For a query, it comes only when its form checked the row id names (an entry form on id, a scope form on the service's own rows by id, { service: "Admin" }), for a caller the service's Admin bypass passes, or for a rowless method under a form that checks no row ("public", "authenticated", { service: L }): it answers before the handler runs, so it would tell any other caller that the row exists and has not changed. Any other query runs its handler.
  • Revisions are microseconds since the epoch: a flush takes max(Date.now() * 1000, last + 1). Clients compare them as numbers.
  • Behind a cluster adapter (setupRedisAdapter), every touched row is read (deleted ones too) and sent, whole, decided by the row as read at flush time, since other nodes' rooms are not visible and frames from two nodes can arrive out of order; access changes and refreshed grants are broadcast to every node, and a flush sends its frames once every node applied them (without waiting while a node does not answer, fail-open). Flushes take their revisions from a counter in the cluster's Valkey, on Valkey's clock in microseconds, so revisions from all nodes are one order; its key needs persistence or replication. A node whose Valkey connection comes back has its clients reconnect to catch up. Give each deployment its own Valkey, or its own cluster.keyPrefix (which setupRedisAdapter takes as its key): a node applies only its own deployment's events (once every deployment that shares the Valkey runs this version), and a Valkey's db does not separate pub/sub. docs/deploying.md has the wiring, what holds across nodes, what it costs, what happens when a node or Valkey stops answering, and a production checklist.

Collections and change topics

A collection is the rows of one service grouped by a scope value (design: section 7). The contract declares it; the service says whose policy authorizes a scope:

export const task = defineContract("taskService", {
  describe: "Tasks on a project's board.",
  entity: taskSchema,
  projections: { card: cardSchema },
  methods: { ...crud.contract({ entity: taskSchema, get: true }) },
  collections: {
    byProject: {
      describe: "A project's open tasks, in board order.",
      // a column holding the scope value
      scope: "projectId",
      // the projection each item is sent as
      item: "card",
      // membership: only open tasks
      where: { status: "open" },
      // ends in "id": the keyset cursor
      order: [
        ["ordinal", "asc"],
        ["id", "asc"],
      ],
      // sent for the whole scope
      index: ["ordinal", "assigneeId"],
      views: { mine: (row, who) => row.assigneeId === who.userId },
    },
    // each user's own
    assigned: {
      describe: "The tasks assigned to a user.",
      scope: "assigneeId",
      item: "card",
      order: [["id", "asc"]],
    },
  },
});
import { crud, inherit } from "@fitzzero/quickdraw-core/server";

export const taskService = qd.defineService(task, {
  model: "task",
  // derived from the anchor
  access: inherit({ from: projectContract, via: "projectId" }),
  collections: {
    // Read on the project opens its scope
    byProject: { anchor: projectContract },
    // a user opens only the scope that is their id; its items still follow access above
    assigned: { scopeAccess: "self" },
  },
  // opens the service topic to Read grants; closed without it
  watchAccess: { service: "Read" },
  methods: { ...crud.handlers(task, { access: { get: { entry: "Read" } } }) },
});
  • scope is a string column, or via({ model, entry, scope }) for scopes that come from a junction table (a chat in each member's list). order ends in id; limit (default 100) and maxLimit (default 500) size its pages; where is an equality filter on membership; access is the level needed on the anchor (default Read).
  • A junction write adds or removes its entry in the one scope it links. Over the item service's own members table (a members read of the policy, alone or inside anyOf, whose entry is the via's entry and whose user is the via's scope), a link counts only when its role gives at least the collection's access: a role change across that line adds or removes the entry, and a link below it is in no page, count, index, qd:col:items or scoped search. When the item reads the junction (a chat's memberCount), declare via({ model, entry, scope, refreshEntry: true }): every junction write then also sends the entry again, updated, to each scope that still holds it, for one more read of the item per flush.
  • qd:col:sub { s, c, scope } authorizes the scope through its anchor's policy, then answers a page and joins the scope's room; flushes send qd:c deltas to it (added, updated, patched, removed, or reset for more than bulkThreshold rows, default 200). A "self" scope is the subscriber's own user id: its items are stripped at Read, and it may not declare a higher access. On a service with an access policy its items still follow that policy: a page, qd:col:items and every flush hold only the rows its user may read at Read. A row the user loses goes out removed, and a change to their membership of a parent row (or a reload of their grants) sends reset, so the list loads again; a client that resumes the list after such a change reads a page. A change to a parent row's own access columns (a project's owner or access list) reaches the list only at the rows' next write or the list's next load.
  • requires: { service: L }, beside anchor or scopeAccess, also asks for a service-wide grant of at least L on the collection's service, as its methods under { service: L } do: both checks must pass, and a service-wide Admin passes either. It is for a list whose methods need the grant, mine: { scopeAccess: "self", requires: { service: "Read" } } beside methods under { service: "Read" }; a list whose rows its users read by their level on each row (assigned above) takes none. Without the grant, qd:col:sub (cursor pages included), the scope's change topic and a search kept to the scope are FORBIDDEN. The grant comes from the socket's principal, never a read: when the user's grants reload below it (server.access.refresh, a tracked write of the grants column, on any node), each of their sockets leaves the scope with qd:revoked (reason: "access") and gets nothing more of it. A collection without requires is unchanged.
  • Items are visible to everyone in an anchored scope: no per-row policy or field tier applies inside it. Derive the item service's own access from the anchor (inherit from it, as above): a per-row policy on the item service (an owner column, a row's access list) is not applied to an anchored scope's items, so a row it would hide still reaches everyone in its scope. A "self" scope is the exception: its items follow the item service's policy for its user.
  • index sends one small row per member ([id, rev, ...fields], up to 50,000) with the first page, so the client knows the whole membership and order at once; views are pure predicates over index rows the client runs. When a collection declares index, every order column but id must be an index field.
  • A deleted anchor row (a project, for its tasks) closes its scopes with qd:revoked; qd.collections.reset(contract, collection, scope) resets a scope after a change tracked writes cannot describe.
  • qd:watch { s, topic } joins a change topic: {collection}:{scope}, authorized like a subscribe to that scope, or service, which changes whenever any row of the service does, or a row of a model it lists in writes (a game's high scores, which no service owns). A query declares watch: "service" to be invalidated by it. A query over some of those models names them, watch: { service: ["gameScore"] } (type ServiceModelsWatch; the service's model and models in its writes; defineService refuses others), and is invalidated only after a flush that wrote one of them: high scores are not read again when a chat membership the same service writes changes. It is the same topic: its qd:changed frame names the models that changed it (models). The service topic is closed (FORBIDDEN) unless the service declares watchAccess ("public", "authenticated" or { service: level }). A watcher that loses access leaves the topic after one last qd:changed. A watch whose access changed while it was answered is authorized again before it joins the topic, with the socket's principal as it is then, and answered FORBIDDEN when it lost access; it hears nothing until it joins. Entity and collection subscribes re-check the same way, with the grants the socket holds then (a grant lowered mid-subscribe denies, a raised one answers at its level), but from inside their room, which they need to catch every change after the snapshot