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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@lachero/cq

v0.0.5

Published

Type-safe CQRS

Downloads

12

Readme

CQ - Type-Safe CQRS for Modern Frontend

A lightweight, type-safe CQRS (Command Query Responsibility Segregation) library with seamless Vite integration for building full-stack applications. Built on top of the blazing-fast H3 server.

npm version License: MIT

Why CQ?

CQ fills the missing gap in modern frontend development where you want to build a small JavaScript application but also need a lightweight server with full customizability. Instead of reaching for heavy frameworks or complex setups, CQ provides the perfect balance with its Vite plugin integration.

CQ leverages the CQRS pattern to separate read (queries) and write (commands) operations, making your application more maintainable and scalable while providing seamless type-safety across your entire stack.

Features

  • 🔒 Full type-safety between frontend and backend
  • Vite integration with HMR support for server code
  • 🎯 CQRS pattern for clean separation of concerns
  • 📝 Schema validation using Standard Schema
  • 🚀 Zero configuration to get started
  • 🔧 Highly customizable for complex use cases
  • 📦 Lightweight with minimal dependencies
  • 🏃 Built on H3 - leveraging the fastest Node.js server framework

Installation

npm i @lachero/cq
# or
pnpm add @lachero/cq
# or
yarn add @lachero/cq
# or
npm i https://github.com/lacherogwu/cq

Quick Start

💡 Check out the examples/ folder for working examples!

CQ offers two main approaches:

🔥 Vite Integration (File-based auto-discovery)

Perfect for full-stack apps. Auto-discovers .server.ts files and generates type-safe clients:

// vite.config.ts
import { defineConfig } from 'vite';
import { cq } from '@lachero/cq/vite';

export default defineConfig({
	plugins: [cq()],
});

// counter.server.ts
import { query, command } from '@lachero/cq';
import { z } from 'zod';

let count = 0;

export const getCounter = query(async () => ({ count }));

export const setCounter = command(z.object({ value: z.number() }), async ({ value }) => {
	count = value;
	return { count };
});

// counter.ts - Frontend usage
import { getCounter, setCounter } from './counter.server';

const { count } = await getCounter(); // Fully typed!
await setCounter({ value: 42 });

⚡ Fastify Integration (Separate Server)

For existing backends or when you need more control:

// actions.ts
import { query, command } from '@lachero/cq';
import { z } from 'zod';

export const actions = {
	healthcheck: query(() => 'OK'),
	users: {
		createUser: command(z.object({ name: z.string() }), async ({ name }) => ({ id: crypto.randomUUID(), name })),
		getUserById: query(z.object({ id: z.string() }), async ({ id }) => ({ id, name: 'John Doe' })),
	},
};

export type Actions = typeof actions;

// server.ts
import Fastify from 'fastify';
import { cqFastify } from '@lachero/cq/fastify';
import { actions } from './actions';

const fastify = Fastify({ logger: true });

// Register CQ with your actions
fastify.register(cqFastify, { actions });

fastify.listen({ port: 3000 });

// client.ts
import { createActionsClient } from '@lachero/cq/client';
import type { Actions } from './actions';

const api = createActionsClient<Actions>({ url: 'http://localhost:3000' });

// Fully typed calls
const health = await api.healthcheck.query();
const user = await api.users.getUserById.query({ id: '123' });
const newUser = await api.users.createUser.command({ name: 'Jane' });

Advanced Usage

Error Handling

import { query, HTTPError } from '@lachero/cq';

export const getUser = query(z.object({ id: z.string() }), async ({ id }) => {
	const user = await database.user.findById(id);
	if (!user) throw new HTTPError('User not found', { status: 404 });
	return user;
});

Request Context & Authentication

import { query, getEvent, getCookie } from '@lachero/cq';

export const getCurrentUser = query(async () => {
	const event = getEvent();
	const token = getCookie(event, 'auth-token') || event.headers.get('authorization');

	if (!token) throw new HTTPError('Unauthorized', { status: 401 });
	return await verifyAndGetUser(token);
});

Database Integration

import { query, command } from '@lachero/cq';
import { prisma } from './lib/prisma';

export const getUsers = query(async () => prisma.user.findMany());

export const createPost = command(z.object({ title: z.string(), content: z.string(), authorId: z.string() }), async input => prisma.post.create({ data: input, include: { author: true } }));

Configuration

Vite Plugin Options

export default defineConfig({
	plugins: [
		cq({
			debug: true, // Enable debug logging
			logger: {
				level: 'info', // trace | debug | info | warn | error | fatal
				label: 'MY-API', // Custom label (default: 'CQ')
				format: 'pretty', // 'pretty' (dev) | 'json' (prod)
			},
		}),
	],
});

Client Options

const api = createActionsClient<ActionsType>({
	url: 'http://localhost:3000',
	headers: { Authorization: 'Bearer token' }, // or async function
	onRequest: ({ type, action, input }) => console.log('→', action),
	onResponse: ({ type, action, result }) => console.log('✓', action),
	onError: ({ type, action, result }) => console.error('✗', action, result),
});

How It Works

CQ separates Core (action definition + HTTP routing) from Integrations (action organization):

Core

  • query() / command() - Define type-safe actions with validation
  • createH3App() - HTTP server that routes requests to actions
  • createActionsClient() - Type-safe client for consuming actions

Integrations

  • Vite: Auto-discovers .server.ts files, generates clients
  • Others: Manual action organization, use createActionsClient()
// 1. Define actions
export const getUser = query(schema, async (input) => { ... });

// 2a. Vite: Auto-discovered and routed
import { getUser } from './users.server';

// 2b. Other: Manual registry + client
const api = createActionsClient<ActionsType>({ url: '...' });
await api.users.getUser.query({ id: '123' });

Benefits: Framework agnostic core, flexible integrations, end-to-end type safety, consistent H3-powered HTTP layer.

// users.server.ts - Auto-discovered by Vite integration
export const getUserById = query(z.number(), (userId) => { ... });
export const createUser = command(userSchema, (userData) => { ... });

// Frontend - Auto-generated client
import { getUserById, createUser } from './users.server';
const user = await getUserById(123); // Fully typed!

TypeScript Support

CQ is built with TypeScript from the ground up. All server actions are fully typed, and the generated client functions maintain the same type signatures, ensuring end-to-end type safety.

Roadmap

  • OpenAPI export - Generate OpenAPI specs from your CQ actions

We're open to suggestions! Open an issue to share your ideas.

Credits

CQ is inspired by and builds upon the excellent work of:

  • H3 - The minimal and fast server framework that powers CQ's backend
  • SvelteKit's remote functions - Pioneered the concept of seamless client-server function calls with type safety

License

MIT © LacheRo

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.