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

@roughapp/feature

v0.9.6

Published

Readme

@roughapp/feature

@roughapp/feature is the browser SDK for embedding Rough Features in your product. Your application defines a Surface (a place where Features can appear) and the capabilities available there. The SDK connects to Rough, subscribes to published Features, renders them, and opens the Builder.

Browser-only ESM with TypeScript declarations and styles included. Import and start it from a client-only boundary, not during SSR. A modern browser and bundler are required.

Pre-1.0: minor releases may contain breaking changes. Review the Feature SDK changelog when upgrading.

Prerequisites and installation

Create a project and signing key in Rough's dashboard. Save the Project ID, signing key ID (kid), and private key. Keep the private key on your server; never mint tokens in browser code.

npm install @roughapp/feature zod@4

Use Zod 4 to define your Surface's capability schemas.

1. Set up server-side authentication

The browser SDK calls your endpoint for a Rough identity token whenever it needs to authenticate. Your server must verify the caller's existing app session, then sign a short-lived JWT for that user. The SDK exchanges that JWT with Rough for a session token; your server does not need to call Rough.

For example, install jose on your server (npm install jose) and add this Express-style route after your app's authentication middleware. Adapt request.user and the account fields to your own authentication system:

import { SignJWT, importPKCS8 } from 'jose'

// Server-only environment variables; never expose the private key to the browser.
const projectId = process.env.ROUGH_PROJECT_ID!
const keyId = process.env.ROUGH_SIGNING_KEY_ID!
const privateKeyPem = process.env.ROUGH_SIGNING_PRIVATE_KEY_PEM!

app.post('/api/rough/user-token', async (request, response) => {
  const user = request.user // Set by your authentication middleware.
  if (!user) return response.sendStatus(401)

  const privateKey = await importPKCS8(
    privateKeyPem.replaceAll('\\n', '\n'), // Handles escaped newlines in env vars.
    'RS256',
  )
  const token = await new SignJWT({
    rough: {
      user: { name: user.fullName, email: user.email },
      account: { id: user.organisationId, name: user.organisationName },
    },
  })
    .setProtectedHeader({ alg: 'RS256', typ: 'JWT', kid: keyId })
    .setIssuer(projectId)
    .setSubject(user.id)
    .setAudience('rough:session')
    .setIssuedAt()
    .setExpirationTime('5m')
    .sign(privateKey)

  response.set('Cache-Control', 'no-store').json({ token })
})

Keep these values consistent with the browser client:

| Token claim | Client option | | -------------------------------------- | ------------------- | | iss (Project ID) | projectId | | sub (stable user ID) | externalUserId | | rough.account.id (stable account ID) | externalAccountId |

Use a user ID as the account ID for private Features, or an organisation/workspace ID for shared Features. A constant account ID shares Features across all users. Always derive these IDs from the authenticated session, never the request body.

Tokens require RS256, a matching signing key kid, iat, and an exp within five minutes. rough.user.name is required; email and account name are optional. See the getting started guide for dashboard setup and a longer walkthrough.

2. Define a Surface

A Surface has a stable key and an ordered toolList of capabilities a Feature can use. The implementations run in your application; Rough receives the schemas and samples, not the implementation code.

import { defineRoughSurface, Query } from '@roughapp/feature'
import { z } from 'zod'

const Message = z.object({
  id: z.string(),
  subject: z.string(),
})

export const inboxSurface = defineRoughSurface({
  key: 'inbox',
  name: 'Inbox',
  description: 'The signed-in user’s message inbox.',
  toolList: [
    new Query({
      id: 'listMessages',
      name: 'List messages',
      description: 'Return the newest messages in the inbox.',
      inputSchema: z.object({
        limit: z.number().int().min(1).max(100).default(20),
      }),
      outputSchema: z.array(Message),
      outputSample: [{ id: 'msg_1', subject: 'Welcome' }],
      implementation: async ({ limit }) => {
        const response = await fetch(`/api/messages?limit=${limit}`)
        if (!response.ok) throw new Error('Unable to load messages')
        return response.json()
      },
    }),
  ],
})

Use Query for reads, Mutation for writes, and Subscription for ongoing updates. Inputs and outputs are validated against their Zod schemas at runtime. Builder previews use outputSample, not live implementations; never include real customer data or secrets in samples.

Treat Surface definitions as immutable and use the same definition for a given key across integrations. Changing or removing capabilities may break existing Features.

3. Start a client

Share one client per project, account, and signed-in user. fetchUserToken calls your authenticated backend and returns the identity token string.

import { startRoughClient } from '@roughapp/feature'

const roughClient = startRoughClient({
  projectId: 'proj_123',
  externalUserId: signedInUser.id, // Matches the token's `sub`.
  externalAccountId: signedInUser.organisationId, // Matches `rough.account.id`.
  theme: 'light', // Optional; defaults to 'light'. Also accepts 'dark'.
  fetchUserToken: async () => {
    const response = await fetch('/api/rough/user-token', {
      method: 'POST',
      credentials: 'include',
    })
    if (!response.ok) throw new Error('Unable to authenticate with Rough')
    const { token } = (await response.json()) as { token: string }
    return token
  },
  onError: (error) => console.error('Rough authentication failed', error),
})

The client starts synchronously and authenticates as needed. Handle authentication errors with onError and asynchronous operation failures with catch.

Open the Builder with openRoughBuilder(). When closed, floating status pills let users follow builds and reopen Features.

The client's theme applies to the Builder, not generated Features. Update it with:

roughClient.setTheme('dark')

4. Subscribe and mount published Features

Your application chooses where to show Features. onChange receives an initial list (possibly empty), then updates when the published list changes. Each item has id, name, surfaceKey, publishedFeatureBuildId, and screenshot (see Feature screenshots). Put an element with id="rough-slot" in your page; this example mounts each published Feature in its own container:

import { mountRoughFeature, subscribeToRoughFeatures } from '@roughapp/feature'
import type { RoughFeatureMount } from '@roughapp/feature'

const list = document.querySelector<HTMLElement>('#rough-slot')!
const mounts = new Map<
  string,
  { container: HTMLElement; mount: RoughFeatureMount }
>()

const unsubscribe = subscribeToRoughFeatures({
  client: roughClient,
  surface: inboxSurface,
  onChange(features) {
    const wanted = new Set(features.map((feature) => feature.id))

    for (const [id, { container, mount }] of mounts) {
      if (wanted.has(id)) continue
      mounts.delete(id)
      mount.unmount()
      container.remove()
    }

    for (const feature of features) {
      if (mounts.has(feature.id)) continue
      const container = document.createElement('div')
      list.append(container)
      const mount = mountRoughFeature(container, {
        client: roughClient,
        surface: inboxSurface,
        featureId: feature.id,
      })
      mounts.set(feature.id, { container, mount })
    }
  },
})

// Register this function with the owning view's teardown lifecycle.
// Do not call it immediately after subscribing.
function cleanupFeatures() {
  unsubscribe()
  for (const { container, mount } of mounts.values()) {
    mount.unmount()
    container.remove()
  }
  mounts.clear()
}

In a framework, subscribe when the view mounts and call cleanupFeatures when it unmounts. The initial onChange callback runs synchronously.

Mounted Features follow the published build automatically unless you pass a specific buildId. Use mount.update(partialProps) to change props without remounting. Setting isEditable: false hides the edit control; it is not an authorization boundary.

Feature screenshots

After a build is published, Rough captures a screenshot of it in the background. feature.screenshot is { url, thumbUrl } for the published build, or undefined until the capture has finished uploading. Capture can fail, so always handle undefined. onChange runs again when a screenshot arrives or the published build changes. url is the full 1280x960 JPEG; thumbUrl is a copy scaled down to 640px wide (640x480).

Two things to know before you show it:

  • The screenshot is rendered with the sample data your surface's tools return (outputSample), not with any real user's data. It shows what the Feature looks like, not what a given user would see.
  • Both URLs are public CDN URLs. They are hard to guess but do not expire, so anyone with the link can load the image.

This renders a gallery of the published Features, with a placeholder for any Feature that has no screenshot yet:

import { subscribeToRoughFeatures } from '@roughapp/feature'

const gallery = document.querySelector<HTMLElement>('#rough-gallery')!

const unsubscribeGallery = subscribeToRoughFeatures({
  client: roughClient,
  surface: inboxSurface,
  onChange(features) {
    gallery.replaceChildren(
      ...features.map((feature) => {
        const card = document.createElement('figure')
        if (feature.screenshot) {
          const image = document.createElement('img')
          image.src = feature.screenshot.thumbUrl
          image.alt = feature.name
          image.loading = 'lazy'
          card.append(image)
        } else {
          const placeholder = document.createElement('div')
          placeholder.className = 'placeholder'
          card.append(placeholder)
        }
        const caption = document.createElement('figcaption')
        caption.textContent = feature.name
        card.append(caption)
        return card
      }),
    )
  },
})

Feature state

By default, Feature application state lives in the host browser's local storage, keyed by Feature ID—not user or account. Users opening the same Feature on the same browser origin share that state, even after switching users.

For user/account isolation or persistence across browsers, pass a datastore implementing RoughFrameDatastore to mountRoughFeature(). Keep it stable while mounted and scope its state per Feature and user/account as needed. Implement get, set, and addListener, notifying listeners when state changes. Handle persistence failures internally: the SDK does not await set.

Create and edit Features

Create a Feature, then open it in the Builder:

import { createRoughFeature, openRoughBuilder } from '@roughapp/feature'

const feature = await createRoughFeature({
  client: roughClient,
  surface: inboxSurface,
  name: 'Inbox summary', // Optional; defaults to an empty string.
})
await openRoughBuilder({
  client: roughClient,
  surface: inboxSurface,
  featureId: feature.id,
})

To start the chat for the user, pass initialMessage. It is sent as the first chat message straight away, without opening the Builder. The agent replies in the background and can start a build:

const feature = await createRoughFeature({
  client: roughClient,
  surface: inboxSurface,
  initialMessage: 'Show my unread messages grouped by sender',
})

New Features remain unpublished until the user publishes them in the Builder. Closing the Builder does not delete them or cancel builds. To edit an existing Feature, pass its ID to openRoughBuilder() without creating another.

Mount the Builder in your page

openRoughBuilder() opens the Builder full screen. To show it inside your own layout instead, mount it in a container:

import { createRoughFeature, mountRoughBuilder } from '@roughapp/feature'

const feature = await createRoughFeature({
  client: roughClient,
  surface: inboxSurface,
})
const builder = mountRoughBuilder(container, {
  client: roughClient,
  surface: inboxSurface,
  featureId: feature.id,
  isSidebarOpen: false, // Optional; defaults to true.
})

// Later, when the container goes away:
await builder.unmount()

The container sets the Builder's size; it switches to its compact layout when the container is 700px wide or narrower. The mounted Builder navigates on its own, separately from the full-screen Builder, and does not take focus when it mounts.

Client lifetime

Unsubscribe, unmount Features, and unmount any Builders from mountRoughBuilder() before destroying their client. Destroy the client when its owner goes away or before switching user, account, or project; create a fresh client for the new identity.

await roughClient.destroy()

This closes subscriptions and removes the full-screen Builder; it does not remove Builders you mounted yourself. In framework hooks that cannot await cleanup, use void roughClient.destroy().