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

crinoid

v0.2.0

Published

Reusable Electron main/preload/renderer infrastructure as a normal package.

Readme

crinoid

Reusable Electron main/preload/renderer infrastructure published as a normal package.

Install

pnpm add crinoid

Peer dependencies you must install yourself:

pnpm add react react-dom electron

The optional UI layer (crinoid/ui, crinoid/blocks, crinoid/charts) uses Tailwind v4:

pnpm add -D tailwindcss @tailwindcss/vite

Usage

Main process

// src/main/index.ts
import { createDesktopConfig } from 'crinoid/config'
import { createMainProcess } from 'crinoid/main'

const config = createDesktopConfig({ appName: 'My App' })

createMainProcess({
  config,
  window: {
    preloadPath: join(__dirname, 'preload.js'),
    rendererFile: join(__dirname, '../renderer/main_window/index.html'),
    devServerUrl: process.env.MAIN_WINDOW_VITE_DEV_SERVER_URL
  }
})

Preload

// src/preload/index.ts
import { exposeDesktopApi } from 'crinoid/preload'

exposeDesktopApi()

Renderer

// src/renderer/main.tsx
import { DesktopProviders, AppShell } from 'crinoid/react'
import messages from './locales/en/common.json'

function App() {
  return <AppShell>Your application content</AppShell>
}

createRoot(document.getElementById('root')!).render(
  <DesktopProviders locale="en" messages={messages}>
    <App />
  </DesktopProviders>
)

Typed renderer bridge

// src/vite-env.d.ts
import type { DesktopAPI } from 'crinoid/ipc'

declare global {
  interface Window {
    desktop: DesktopAPI
  }
}

UI components, blocks, and charts

The UI layer is optional and Tailwind-based. Import the package stylesheet once, then add the Tailwind Vite plugin:

/* src/renderer/index.css */
@import "crinoid/ui/styles.css";
// vite.config.mts
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import { createRendererViteConfig } from 'crinoid/vite'

export default createRendererViteConfig({
  root: 'src/renderer',
  plugins: [react(), tailwindcss()]
})
import { Badge, Button, Card, CardContent, CardHeader, CardTitle } from 'crinoid/ui'
import { AreaChart } from 'crinoid/charts'
import { DashboardBlock, StatCard, StatsGrid } from 'crinoid/blocks'
import { AppLayout, Grid, Page, PageHeader, Split, Stack } from 'crinoid/layout'

function Dashboard() {
  return (
    <AppLayout sidebar={<nav>Sidebar</nav>} header={<span>My App</span>}>
      <Page>
        <PageHeader title="Overview" description="Last 7 days" actions={<Button>Refresh</Button>} />
        <Grid cols={1} smCols={2} xlCols={4} gap="md">
          <StatCard label="Users" value="1,248" trend={<Badge>+12%</Badge>} />
        </Grid>
        <Split
          primary={
            <Card>
              <CardHeader>
                <CardTitle>Traffic</CardTitle>
              </CardHeader>
              <CardContent>
                <AreaChart
                  data={[{ day: 'Mon', visits: 120 }, { day: 'Tue', visits: 180 }]}
                  xKey="day"
                  series={[{ key: 'visits', label: 'Visits' }]}
                  height={240}
                />
              </CardContent>
            </Card>
          }
          secondary={<Stack>Recent activity</Stack>}
        />
      </Page>
    </AppLayout>
  )
}

Layout-first defaults

The UI layer is designed so feature code only chooses arrangement, not per-component styling:

  • crinoid/ui components ship complete default styles and intent variants (variant, size). Prefer those over className; reserve className for layout-safe overrides such as width or alignment.

  • crinoid/layout provides AppLayout, Page, PageHeader, Section, Stack, Row, Grid, Container, Toolbar, and Split with gap/column presets.

  • crinoid/patterns provides FormField, FormGrid, ConfirmDialog, DataList, DataListRow, and NavList / NavGroup / NavItem so forms, confirmations, list rows, and sidebar navigation do not need hand-written markup or styles.

  • crinoid/blocks provides page-scale scaffolds: PageBlock, SettingsBlock, AuthBlock, DashboardBlock, and EmptyBlock.

  • crinoid/ui exports shadcn-derived primitives: button, input, textarea, label, card, badge, alert, avatar, separator, skeleton, switch, checkbox, select, dialog, dropdown menu, tabs, table, tooltip, progress, and chart primitives.

  • crinoid/blocks exports composed PageBlock, SettingsBlock, AuthBlock, DashboardBlock, and EmptyBlock layouts built from those primitives.

  • crinoid/charts exports LineChart, AreaChart, BarChart, PieChart, and DonutChart wrappers over Recharts, plus the low-level shadcn ChartContainer / ChartTooltip / ChartLegend primitives.

  • crinoid/layout and crinoid/patterns keep app chrome layout-only: choose page, stack, grid, split, and navigation presets instead of styling each element.

  • cn is exported from crinoid/ui for merging Tailwind classes.

Forge and Vite configuration

// forge.config.ts
import { createForgeConfig } from 'crinoid/forge'

export default createForgeConfig({
  packagerConfig: { executableName: 'my-app' },
  makers: [],
  plugins: []
})
// vite.main.config.mts
import { createMainViteConfig } from 'crinoid/vite'

export default createMainViteConfig('src/main/index.ts')

Foundational features

createMainProcess already wires environments, lifecycle, graceful shutdown, global error handling, global logging, typed IPC, and a window registry. Use the exported pieces directly when you need finer control.

Environment

resolveEnvironment maps NODE_ENV and app.isPackaged onto development, test, or production; unknown NODE_ENV values fall back to the packaging state. createMainProcess uses the resolved environment to pick a default log level.

import { environmentFromProcess } from 'crinoid/environment'

const environment = environmentFromProcess(process.env, app.isPackaged)

Global logging

import { createLogger, createRotatingFileSink, levelFromEnvironment } from 'crinoid/logging'

const logger = createLogger({
  level: levelFromEnvironment(environment.name),
  sink: createRotatingFileSink({ filePath: join(app.getPath('logs'), 'app.log') })
})

logger.info('started', { version: app.getVersion() })
await logger.flush()

Graceful shutdown

Register cleanup tasks; they run concurrently with a per-task timeout when the app quits.

createMainProcess({
  config,
  window: { /* ... */ },
  onShutdown: async () => {
    await database.close()
  }
})

For manual composition, createAppLifecycle wires ready / activate / window-all-closed / before-quit and exposes the shutdown manager.

import { createAppLifecycle, createShutdownManager } from 'crinoid/lifecycle'

const shutdown = createShutdownManager({ logger })
const lifecycle = createAppLifecycle({ app, onReady: init, shutdown })
lifecycle.shutdown.register({ name: 'database', run: () => database.close() })

Global error handling

import { installGlobalErrorHandlers } from 'crinoid/errors'

installGlobalErrorHandlers({ source: process, logger, onError: reportToBackend })

In the renderer, wrap the tree with ErrorBoundary:

import { ErrorBoundary } from 'crinoid/react'

<ErrorBoundary fallback={(error) => <p>{error.message}</p>}>{children}</ErrorBoundary>

Typed IPC

Define a channel once and register a validated handler. The registry rejects untrusted senders and invalid payloads, and returns a disposer.

import { createChannel, createIpcRegistry } from 'crinoid/ipc'

const increment = createChannel<{ by: number }, number>(
  'counter.increment',
  (value): value is { by: number } => typeof (value as { by?: unknown })?.by === 'number'
)

const registry = createIpcRegistry(ipcMain, { origin: 'file:', logger })
const dispose = registry.register({ channel: increment, handle: ({ request }) => counter += request.by })

Multiple windows

import { createWindowRegistry } from 'crinoid/window'

const windows = createWindowRegistry<BrowserWindow>()
windows.open('settings', () => new BrowserWindow({ /* ... */ }))
windows.broadcast('theme.changed', 'dark')

createMainProcess can open extra windows and named child windows directly:

createMainProcess({
  config,
  window: mainWindowOptions,          // main window
  windows: [settingsWindowOptions],   // extra top-level windows
  childWindows: { about: aboutOptions }
})

The renderer opens a child window with await window.desktop.window.open('about').

Window and interface

Declare tray, menus, global shortcuts, and custom chrome through the same options object.

createMainProcess({
  config,
  window: {
    /* ... */
    chrome: { titleBarStyle: 'hiddenInset', alwaysOnTop: true, minWidth: 900 }
  },
  menuTemplate: [{ role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }],
  shortcuts: { CommandOrControl+Shift+I: () => openDevTools() },
  tray: {
    iconPath: join(__dirname, 'tray.png'),
    tooltip: 'My App',
    labels: { show: 'Show', quit: 'Quit' },
    minimizeToTray: true,
    closeToTray: true
  }
})

Dialogs, context menus, and native integration are reachable from the renderer bridge:

await window.desktop.dialog.openDirectory()
await window.desktop.dialog.openFile({ title: 'Open note', filters: [{ name: 'Notes', extensions: ['md'] }] })
await window.desktop.dialog.confirm({ message: 'Delete?', confirmLabel: 'Delete', cancelLabel: 'Keep' })
await window.desktop.contextMenu.show({ items: [{ id: 'copy', label: 'Copy' }], x, y })
window.desktop.app.setBadge(3)
window.desktop.window.setAlwaysOnTop(true)

Compose the pieces directly when you need finer control:

import { createTrayController } from 'crinoid/tray'
import { createShortcutManager } from 'crinoid/shortcuts'
import { createDialogService } from 'crinoid/dialogs'
import { createPlatformIntegration } from 'crinoid/integration'

Application state

import { createStore } from 'crinoid/reactive'
import { createPersistentStore } from 'crinoid/persistent'
import { createRecentItems } from 'crinoid/recent-items'

const store = createStore({ theme: 'light' })
store.subscribe((value) => console.log(value))
const theme = store.select((state) => state.theme)

const preferences = await createPersistentStore({ storage, key: 'prefs', defaults: { theme: 'light' } })
const recent = createRecentItems({ limit: 10 })

createMainProcess wires a cross-window synced store and recent-files list when you pass state / recentFiles:

createMainProcess({
  config,
  window,
  state: { initial: { theme: 'light' }, persistPath: join(app.getPath('userData'), 'state.json') },
  preferences: { defaults: { locale: 'en', zoom: 1 } },
  recentFiles: { limit: 10 }
})

The renderer uses window.desktop.store, window.desktop.preferences, and window.desktop.recentFiles.

File system

import { readText, writeText, listDirectory, copyPath } from 'crinoid/fs'
import { detectMimeType } from 'crinoid/mime'
import { watchPath } from 'crinoid/watch'

await writeText('/tmp/note.txt', 'hello')
await readText('/tmp/note.txt')
await listDirectory('/tmp')
detectMimeType('/tmp/note.txt')
const watcher = watchPath('/tmp', (event) => console.log(event))

The renderer reaches the same operations through window.desktop.fs (pick, read, write, list, ensureDir, copy, move, remove, mime, watch) and window.desktop.recentFiles.

Networking

import { createApiClient } from 'crinoid/api'
import { createWebSocketClient } from 'crinoid/websocket'
import { createSseClient } from 'crinoid/sse'
import { createTransferManager } from 'crinoid/transfers'
import { applyProxy } from 'crinoid/proxy'

const api = createApiClient('https://api.example.com', fetch, {
  timeoutMs: 15_000,
  retries: 3,
  isOnline: () => navigator.onLine
})

const socket = createWebSocketClient('wss://api.example.com/socket', { onMessage: (data) => console.log(data) })
const stream = createSseClient('https://api.example.com/events', { onEvent: (_name, data) => console.log(data) })

createMainProcess accepts a proxy option and wires a download manager for the renderer:

createMainProcess({
  config,
  window,
  proxy: { mode: 'fixed', url: 'http://proxy.internal:8080' }
})
// renderer
window.desktop.transfers.onProgress((progress) => console.log(progress))
await window.desktop.transfers.download('https://example.com/file.bin')

Authentication and local data

import { createSessionManager, createTokenManager } from 'crinoid/auth'
import { createSqliteDriver } from 'crinoid/sqlite'
import { createDatabase } from 'crinoid/database'
import { createKeyValueStorage, createMemoryStorage } from 'crinoid/storage'

const session = createSessionManager<{ id: string }>({ storage: sessionStorage, authenticate: login })
const tokens = createTokenManager({ provider: { refresh } })

const database = await createDatabase({
  driver: createSqliteDriver({ file: join(app.getPath('userData'), 'app.db') }),
  migrations: [{ id: '001-init', up: 'CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT)' }]
})

const kv = createKeyValueStorage(createMemoryStorage(), 'settings')

createMainProcess accepts an auth bridge to register auth IPC and restore the session on startup:

createMainProcess({
  config,
  window,
  auth: { sessionManager: session, tokens }
})
// renderer
await window.desktop.auth.login({ username, password })
window.desktop.auth.onChanged((session) => console.log(session))

Task system and updates

import { createJobQueue, createScheduler, createUpdateService, resolveChannel } from 'crinoid/tasks'

const queue = createJobQueue({ concurrency: 4 })
await queue.add((signal) => longRunning(signal), { retries: 3, onStart: () => console.log('started') })

const scheduler = createScheduler()
scheduler.schedule('cleanup', { cron: '0 3 * * *' }, () => cleanup())

const updates = createUpdateService({
  adapter: electronUpdaterAdapter,
  currentVersion: app.getVersion(),
  channel: resolveChannel('beta')
})

The renderer drives updates through window.desktop.updates (check/download/install/rollback/channel/progress).

System capabilities

const info = await window.desktop.system.info()
const battery = await window.desktop.power.status()
const online = await window.desktop.network.status()
await window.desktop.notifications.show({ title: 'Done', body: 'Export finished' })
await window.desktop.clipboard.writeText('copied')
await window.desktop.shell.showItemInFolder('/tmp/report.pdf')

Compose the pieces directly in the main process:

import { createClipboardService } from 'crinoid/clipboard'
import { createNotificationService } from 'crinoid/notifications'
import { createShellService } from 'crinoid/shell'
import { collectSystemInfo } from 'crinoid/system'
import { createPowerMonitor } from 'crinoid/power'
import { createNetworkMonitor } from 'crinoid/network'
import { createSecretStore } from 'crinoid/secrets'

Security

createMainProcess installs a restrictive Content Security Policy and keeps every window isolated (contextIsolation, sandbox, no Node in the renderer). Secrets are encrypted with the OS keychain:

import { buildContentSecurityPolicy } from 'crinoid/security'
import { createSecretStore } from 'crinoid/secrets'

const policy = buildContentSecurityPolicy({ apiOrigins: ['https://api.example.com'] })
// renderer: await window.desktop.secrets.set('token', value)

Updating

pnpm update crinoid

Major releases document API and configuration changes in CHANGELOG.md. Consumer source files are never modified automatically.