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

@chrono-os/tenancy

v0.2.1

Published

Isolamento por tenant para apps Prisma multi-tenant: extensão de escopo, contexto por request, escolha determinística de membership e gate de cobertura schema x lista. Zero dependências de runtime.

Downloads

610

Readme

@chrono-os/tenancy

Isolamento por tenant para apps Prisma genuinamente multi-tenant (Legaris, MeResponda, nairio-os-api). Zero dependências de runtime; Prisma 5, 6 ou 7.

Regra da casa: app single-tenant nasce tenant-ready (um seam resolveTenantId), não multi-tenant. Este pacote é para quem já tem mais de um tenant no mesmo banco.

import { tenantScope, criarContextoTenant, escolherMembership, ORDEM_MEMBERSHIPS } from '@chrono-os/tenancy'

export const TENANT_MODELS = new Set(['Proposta', 'Familia' /* … */])
export const tenant = criarContextoTenant<{ tenantId: string; userId: string; role: string }>()

export const tenantPrisma = prisma.$extends(
  tenantScope({ field: 'tenantId', models: TENANT_MODELS, getTenantId: () => tenant.obter()?.tenantId }),
)

// main.ts — middleware global, ANTES dos guards: abre o contexto da request
app.use((req, res, next) => tenant.abrir(next))

// no guard (async, com await no banco): preenche o contexto já aberto
const memberships = await prisma.membership.findMany({ where: { userId }, orderBy: [...ORDEM_MEMBERSHIPS] })
const escolha = escolherMembership(memberships, req.headers['x-tenant-id'], 'tenantId')
if (!escolha.ok) throw escolha.motivo === 'sem-vinculo' ? new ForbiddenException() : new NotFoundException()
tenant.definir({ tenantId: escolha.membership.tenantId, userId, role: escolha.membership.role })

Não use enterWith (nem o entrar() da 0.1.0) num guard async. Depois de um await, o enterWith só vale para a promise do próprio guard: o handler não herda, e toda query cai em "tenant ausente". O contexto é aberto no middleware (abrir) e só preenchido no guard (definir).

O que a extensão faz

  • Espalha o campo de tenant no where de toda operação (inclusive findUnique, update, delete — o extendedWhereUnique do Prisma 5+ sustenta) e no data de create/createMany. O do contexto sempre vence um valor forjado pelo chamador.
  • update/updateMany/upsert.update descartam o campo de tenant do data: registro não muda de tenant por escrita.
  • Sem tenant no contexto: lança (fail-closed). onMissingTenant troca a exceção.
  • softDeleteModels + baseClient: leituras filtram deletedAt: null; delete/deleteMany viram update de deletedAt.
  • Model fora da lista passa intacto — por isso o gate abaixo.

Não cobre: escrita aninhada (connect para registro de outro tenant — só a FK segura), $queryRaw/$executeRaw, include de relação para model fora da lista.

Gate de cobertura

"typecheck": "chrono-tenancy-coverage --schema prisma/schema.prisma --source src/tenancy/tenant-prisma.ts --field tenantId && tsc --noEmit"

Falha quando um model do schema tem a coluna de tenant e não está no Set da fonte, ou quando a lista cita model sem a coluna. --exclude A,B declara exceções de propósito.

Membership em ordem determinística

escolherMembership escolhe o vínculo mais antigo (desempate por id) quando a request não pede tenant. Os guards antigos pegavam memberships[0] de um findMany sem orderBy: para quem tinha dois vínculos, o tenant da sessão podia variar entre requests.