This document explains Quark's distribution architecture and the philosophy behind what gets published to the registry versus what gets scaffolded locally.
Note: The
adminrole in the RBAC system is an auth concept (highest privilege level). It is unrelated to the removed@usequark/quark-adminpackage, which was a scaffolded CRUD UI.
Traditional web frameworks force a choice:
Quark takes a hybrid approach:
┌─────────────────────────────────────────────────────┐
│ Your Application (@yourapp/web, @yourapp/worker) │
│ ├─ imports @usequark/quark-core (from registry) │
│ └─ imports @yourapp/db, @yourapp/jobs (local) │
├─────────────────────────────────────────────────────┤
│ @usequark/quark-core (npmjs.org) │
│ - createAuthConfig() │
│ - createQueue(), createWorker() │
│ - AppError, ValidationError │
│ - validateBody(), validateParams() │
│ ❌ No database client (no Prisma) │
│ ❌ No domain-specific logic │
├─────────────────────────────────────────────────────┤
│ @yourapp/db (Local - Always Scaffolded) │
│ - schema.prisma (YOUR models) │
│ - PrismaClient instantiation │
│ - Query builders for your domain │
├─────────────────────────────────────────────────────┤
│ @yourapp/ui (Local - Optional) │
│ - Full component library with dark mode support │
│ - ThemeProvider, QuarkLogo, Badge, Button, Card, │
│ Table, Dialog, Toast, Input, Select, Skeleton… │
│ @yourapp/jobs (Local - Optional) │
│ @yourapp/config (Local - Optional) │
├─────────────────────────────────────────────────────┤
│ Infrastructure Packages (npm) │
│ - @prisma/client, BullMQ, next-auth, etc. │
└─────────────────────────────────────────────────────┘Infrastructure-Level Utilities
Provider-Agnostic Patterns
More Infrastructure
REDIS_URL is set, in-memory otherwise; apps/web/src/proxy.js wires the core limiter from rate-limiter.js into the web middleware, failing closed by default)@usequark/quark-core/testingCore ships 21 subpath exports. packages/core/package.json is the authoritative list; see packages/core/README.md for what each one contains.
Documentation
Prisma Helpers, Not a Client
createPrismaClient(ClientClass) is a factory that takes your generated client class, so core never imports your generated outputpingDatabase() and pool config helpersparseSchema, getModels, getEnums, coerceId — exported from the ./admin subpath) A Database Client Instance (lives in your local @yourapp/db)
Domain-Specific Logic
Application Configuration
Auth, queues, validation rarely need customization:
createAuthConfig() defaults work for 90% of casesAppError, ValidationError) are universalBenefits of registry distribution:
pnpm update)Every app has unique domain models:
Product, Order, CartOrganization, Subscription, InvoiceJobs are domain-specific:
UI is inherently custom:
Benefits of local scaffolding:
In Core (Registry):
// @usequark/quark-core - Provides defaults
import { createAuthConfig } from "@usequark/quark-core";
export const createAuthConfig = (options = {}) => {
return {
secret: process.env.NEXTAUTH_SECRET,
session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60 },
callbacks: { /* default callbacks */ },
...options // Allow extensions
};
};In Your App (Local):
// apps/web/lib/auth.js - Your customizations
import { createAuthConfig } from "@usequark/quark-core";
import GitHubProvider from "next-auth/providers/github";
export const authConfig = createAuthConfig({
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.userId = user.id;
token.role = user.role; // Custom field
}
return token;
},
async session({ session, token }) {
session.user.id = token.userId;
session.user.role = token.role;
return session;
},
},
});Before (Old Architecture - Circular Dependency):
// ❌ REMOVED: Core had database client
// @usequark/quark-core/src/db/index.js
export const createDbClient = () => {
// Problem: Core depended on @usequark/quark-db
// But db depended on core → circular!
};Now (Core-Only Registry - Clean):
// ✅ Core has NO database client and no Prisma dependency
// @usequark/quark-core exports: auth, queues, validation, errors, and db helpersIn Your Local DB Package:
// packages/db/src/client.js - YOU own this
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client.js";
// Build connection string from YOUR environment
const connectionString = `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}...`;
export const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString })
});Key Points:
./db helper subpath described aboveIn Core (Registry):
// @usequark/quark-core/src/queue/index.js
export const createQueue = (name, options = {}) => {
return new Queue(name, {
connection: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
},
defaultJobOptions: { attempts: 3, ... },
...options
});
};In Your Local Jobs Package:
// packages/jobs/src/definitions.js - YOUR domain jobs
export const JOB_QUEUES = {
EMAIL: "email-queue",
FILES: "files-queue",
VIDEO_PROCESSING: "video-queue", // Your custom queue
};
export const JOB_NAMES = {
SEND_WELCOME_EMAIL: "send-welcome-email",
SEND_RESET_PASSWORD_EMAIL: "send-reset-password-email",
CLEANUP_ORPHANED_FILES: "cleanup-orphaned-files",
TRANSCODE_VIDEO: "transcode-video", // Your custom job
};In Your Worker App:
Handlers are extracted to separate files and registered in a handler map. The worker dispatches jobs to the correct handler automatically.
// apps/worker/src/handlers/video.js - YOUR custom handler
export async function handleTranscodeVideo(bullJob, logger) {
logger.info(`Transcoding video ${bullJob.data.videoId}`);
await transcodeVideo(bullJob.data);
return { success: true };
}
// apps/worker/src/handlers/index.js - handler registry
import { JOB_NAMES } from "@yourapp/jobs";
import { handleSendWelcomeEmail, handleSendResetPasswordEmail } from "./email.js";
import { handleCleanupOrphanedFiles } from "./files.js";
import { handleTranscodeVideo } from "./video.js";
export const jobHandlers = {
[JOB_NAMES.SEND_WELCOME_EMAIL]: handleSendWelcomeEmail,
[JOB_NAMES.SEND_RESET_PASSWORD_EMAIL]: handleSendResetPasswordEmail,
[JOB_NAMES.CLEANUP_ORPHANED_FILES]: handleCleanupOrphanedFiles,
[JOB_NAMES.TRANSCODE_VIDEO]: handleTranscodeVideo, // Your custom job
};
// apps/worker/src/index.js - generic dispatch (no changes needed)
// The worker loops over JOB_QUEUES and dispatches to jobHandlers automatically.Key Points:
packages/db/src/client.js can also skip the adapter and reuse a globalThis cache in development. Same rule: the client lives in your db package, never in core.
// packages/db/src/client.js
import { PrismaClient } from "./generated/prisma/client.js";
const globalForPrisma = globalThis;
export const prisma = globalForPrisma.prisma || new PrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}Domain-specific logic (bookings, CRM, CMS, ecommerce, AI) is no longer scaffolded as packages. Instead, embedded skills teach AI tools to build these systems on demand. See docs/DESIGN_NOTES.md for the design rationale.
Skills live in <harness>/skills/ (default .opencode/skills/). Each skill contains domain context, Quark framework patterns, example models, and a workflow. The AI reads the skill and generates code that fits the user's exact requirements.
Reference implementations are archived at docs/archive/reference/verticals/. Study them for the complete model set, validation, and business logic, then adapt to the user's requirements.
# 1. Create new app
npx @usequark/quark-create-app my-app
# 2. Core provides auth, queues, validation, errors
import { auth } from "@usequark/quark-core";
import { prisma } from "@yourapp/db";
# 3. Build domain features using skills
# The AI reads the embedded skill and generates code on demandDomain logic is built on demand via skills, not scaffolded as packages:
# The embedded skills teach your AI tool to build:
# - Bookings system (model, CRUD, business logic)
# - CRM (contacts, deals, pipeline)
# - CMS (pages, content, publishing)
# - E-commerce (products, orders, checkout)
# - AI features (assistants, RAG, embeddings)
# Reference implementations archived at docs/archive/reference/verticals/// ✅ Good: Extend core
import { createAuthConfig } from "@usequark/quark-core";
export const authConfig = createAuthConfig({
providers: [CustomProvider()],
});
// ❌ Avoid: Rewriting from scratch
export const authConfig = {
providers: [CustomProvider()],
// ... missing all core defaults
};Core should work standalone:
// ✅ Good: Core works in any app
import { createQueue } from "@usequark/quark-core";
const q = createQueue("jobs");
// ❌ Bad: Core depends on app setup
import { config } from "./config"; // App-specific
import { db } from "./db"; // App-specific# Core has its own tests
cd packages/core
pnpm test
# Apps test their customizations
cd apps/web
pnpm testQuark includes a comprehensive E2E testing approach to validate the entire project creation and startup workflow.
All of these are packages/cli scripts. Run them through the filter, or cd packages/cli first. None of them exist at the repo root.
1. Unit Tests - Template and scaffold validation
pnpm --filter @usequark/quark-create-app testFast validation that templates are valid and dependencies are correct.
2. E2E Scaffolding Test - Full project creation
pnpm --filter @usequark/quark-create-app test:e2eValidates project scaffolding process (file creation, replacements, structure).
3. Full Lifecycle Test - Create → Install → Deploy → Startup (Optional)
pnpm --filter @usequark/quark-create-app test:e2e:fullRuns the complete workflow:
--no-prompts flagTakes ~40 seconds, requires Docker and available system resources.
# Quick validation
pnpm --filter @usequark/quark-create-app test
# Scaffolding only
pnpm --filter @usequark/quark-create-app test:e2e
# Full lifecycle (requires Docker)
pnpm --filter @usequark/quark-create-app test:e2e:full
# With build verification
pnpm --filter @usequark/quark-create-app test:build
# With generated image security scanning
QUARK_CLI_SCAN_IMAGES=1 pnpm --filter @usequark/quark-create-app test:buildContainer runtime selection follows two rules:
For continuous integration pipelines:
# Example: GitHub Actions
- name: Test CLI Creation
run: |
cd packages/cli
pnpm test # Always fast unit tests
pnpm test:e2e # Scaffolding validation
# pnpm test:e2e:full # Optional: full lifecycle (slow, needs Docker)Quark keeps required PR-time image scanning focused on the source Dockerfiles in ci.yml. Generated scaffold image scanning uses the same test-build.js harness and runs separately as a non-blocking workflow so the deploy contract stays validated without making every PR pay the full scaffold/build/scan cost.
All tests use the --no-prompts flag to run without user input:
// test-e2e-full.js
await execute(`${cliPath} ${projectName} --no-prompts --packages ui,jobs`, {
cwd: E2E_TEST_DIR,
timeout: 60000,
});This enables:
For manual testing with prompts, simply run without the flags:
npx @usequark/quark-create-app my-test-appAs your app grows:
Quark ships with a complete CSS token layer. Every colour, radius, and surface value is defined in one place - change it once and the entire UI updates.
Design tokens live in apps/web/src/app/globals.css, but not in the @theme inline block. They are declared dark-first in :root, then overridden for light by @media (prefers-color-scheme: light) and by [data-theme="light"]:
:root {
/* Shape - 0px for sharp, 0.25rem for rounded, 0.5rem for pill */
--radius-default: 0px;
/* Primary brand colour - swap this one value to change every button, link, and accent */
--color-primary: #377dff;
--color-primary-hover: #5594ff;
/* Surfaces */
--color-bg: #09101a;
--color-surface: #101827;
--color-surface-hover: #1c2642;
/* Borders */
--color-border: #263044;
--color-border-hover: rgba(55, 125, 255, 0.4);
}
@media (prefers-color-scheme: light) {
/* OS says light AND the user hasn't explicitly pinned dark via the toggle */
:root:not([data-theme="dark"]) {
--color-primary: #1d4ed8;
--color-primary-hover: #1a56db;
--color-bg: #f7f8fa;
--color-surface: #ffffff;
}
}
/* User explicitly toggled to light */
:root[data-theme="light"] {
--color-primary: #1d4ed8;
/* ...same overrides as above... */
}@theme inline (near the bottom of the file) re-exports each of those tokens so Tailwind registers them as first-class utilities - it holds references, not values:
@theme inline {
--color-primary: var(--color-primary);
--color-bg: var(--color-bg);
--radius-default: var(--radius-default);
}Component-level variables (--btn-*, --badge-*, --input-*, ...) sit in their own block in the same file and reference the tokens with var(--...). To retheme a scaffolded project, edit the :root and [data-theme="light"] blocks - no component files need touching.
--radius-default controls global border-radius for cards, inputs, buttons, and badges:
| Value | Effect |
|---|---|
0px | Sharp, editorial (default) |
0.25rem | Subtle rounding |
0.5rem | Modern/rounded |
9999px | Full pill |
Components reference these via Tailwind v4 paren syntax, for example rounded-(--btn-radius).
Quark uses data-attribute dark mode, not Tailwind's dark: class prefix:
/* In globals.css */
@custom-variant dark (&:is([data-theme="dark"] *));The ThemeProvider component (from @usequark/quark-ui in the monorepo, @scope/ui in a scaffolded project) sets data-theme="dark" on the <html> element. This means:
dark:bg-surface works in component files[data-theme="dark"] overridesprefers-color-scheme is used by the FOUC script and by the :root light overrides, so an unpinned first visit follows the OSBecause the attribute is the source of truth, an explicit user choice always wins over the OS setting.
The scaffold templates in packages/cli/templates/ are generated from monorepo source. After editing globals.css or any UI file, run:
pnpm --filter @usequark/quark-create-app sync-templatesCI checks for drift on every push and fails if templates are stale.
To rebrand a scaffolded project:
--color-primary (and --color-primary-hover) in the :root block of globals.css, plus the matching light values in @media (prefers-color-scheme: light) and [data-theme="light"]--radius-default for the geometry feel[data-theme="light"] block if you changed the dark baseline, so an explicit toggle to light stays coherentQuarkLogo with your own logo componentauth/signin/page.js, auth/register/page.js)Core evolves based on real usage patterns!
Quark ships a dark-mode-first theme system built entirely on CSS custom properties and the HTML data-theme attribute - no class-flipping, no SSR flicker.
data-theme attribute on <html> is the single source of truth - "dark" or "light".@custom-variant dark (&:is([data-theme="dark"] *)) so dark: utility classes react to the attribute, not a dark class.<script> in layout.js reads localStorage.getItem("quark-theme") and prefers-color-scheme synchronously before the first paint, writing data-theme before any React hydration.--color-primary, --color-bg, --color-text, ...) and the landing-page variables that read them (--quark-page-bg, --quark-home-muted, --quark-toast-track, ...) are defined dark-first in :root with light overrides in @media (prefers-color-scheme: light) and [data-theme="light"].@scope/ui)| Export | Type | Purpose |
|---|---|---|
ThemeProvider | Client component | React context; provides theme and setTheme to a subtree |
useTheme() | Hook | Returns { theme, setTheme } from nearest ThemeProvider |
THEME_ATTR | Constant | HTML attribute name ("data-theme") |
THEME_STORAGE_KEY | Constant | localStorage key ("quark-theme") |
THEME_CHANGE_EVENT | Constant | Custom event name for cross-component sync |
// Wrap your app (or a subtree) in ThemeProvider:
import { ThemeProvider } from "@scope/ui";
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
{/* FOUC prevention script goes here (auto-added by Quark) */}
<body>
<ThemeProvider defaultTheme="dark">
{children}
</ThemeProvider>
</body>
</html>
);
}
// Read/set theme in a client component:
import { useTheme } from "@scope/ui";
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
{theme === "dark" ? "Light" : "Dark"}
</button>
);
}ThemeProvider is "use client" but all other components (Card, Badge, Table, QuarkLogo, etc.) are pure Server Components - theme adaptation happens via CSS variables, not JS. The QuarkLogo component specifically uses var(--quark-logo-dark-arc) to ensure the dark arc stroke remains visible against both light and dark backgrounds.
Some sites should not offer theme switching - a marketing page with a specific aesthetic, or an app where dark mode simply doesn't fit. The correct method is to set data-theme statically on <html> and remove the blocking script and toggle. Because the attribute is present in the server-rendered HTML, there is no FOUC and no need for a script.
To lock to light mode, edit apps/web/src/app/layout.js. The shipped file wraps {children} in <ThemeProvider> and injects the blocking themeScript - both have to go, because ThemeProvider re-writes data-theme from localStorage, then defaultTheme, then the OS preference, in a useLayoutEffect that runs after the static attribute is in the DOM:
// Before (dynamic theme system):
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
<body>
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
);
}
// After (light-mode only):
export default function RootLayout({ children }) {
return (
<html lang="en" data-theme="light">
<head />
<body>
{children}
</body>
</html>
);
}themeScript constant and its <script> tag.<ThemeProvider> (and its import). Keeping it silently overrides the static attribute, and defaultTheme does not fix that: ThemeProvider resolves a stored localStorage preference before defaultTheme (packages/ui/src/theme.js), so a visitor who once toggled dark still gets dark. If you must keep it for useTheme() consumers, pin it by clearing the stored preference (localStorage.removeItem("quark-theme")) or document that visitors' stored choice wins over your static theme.data-theme="light" (or "dark") directly to <html>.suppressHydrationWarning - it is only needed when data-theme may differ between server and client.Why not just remove the toggle? Two writers fight over the attribute. The blocking script restores the user's previously stored preference from localStorage on every visit, and ThemeProvider re-applies a preference in a layout effect. A user who previously switched to dark still gets dark even after the toggle is removed. The only reliable fix is to replace both with a static attribute.
Re-enableable flag pattern - if you want to switch back later without hunting through JSX, add a single config constant:
// apps/web/src/lib/theme-config.js
export const FORCED_THEME = "light"; // "light" | "dark" | null (auto/user-controlled)Then drive layout.js from it:
import { FORCED_THEME } from "../lib/theme-config.js";
const themeScript = /* existing blocking script string */;
export default function RootLayout({ children }) {
return (
<html
lang="en"
{...(FORCED_THEME ? { "data-theme": FORCED_THEME } : { suppressHydrationWarning: true })}
>
<head>
{!FORCED_THEME && (
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
)}
</head>
<body>
{FORCED_THEME ? children : <ThemeProvider>{children}</ThemeProvider>}
</body>
</html>
);
}Set FORCED_THEME = null to re-enable the full dynamic system with zero further changes.