Reference

SDK Reference

Functions, options, return values, and types for @roughapp/feature v0.9.5.

AI generated The content on this page was written using large language models.

API reference for @roughapp/feature v0.9.5. Signatures are simplified for readability; your editor provides the full TypeScript declarations.

For a first integration, see Getting Started. For design guidance and worked examples, see Capabilities and Feature state.

npm install @roughapp/[email protected] zod@4

Browser-only ESM: import from client-only code, not during server-side rendering. A modern browser and bundler are required; direct script-tag and CDN usage are unsupported. Styles and the Builder font are included.

startRoughClient()

Returns a client immediately. Authentication and Feature metadata synchronization run in the background.

startRoughClient(options: StartRoughClientOptions): RoughClient

type StartRoughClientOptions = {
  projectId: string
  externalUserId: string
  externalAccountId: string
  fetchUserToken: FetchUserTokenFn
  theme?: RoughTheme
  onError?: (error: Error) => void

  // Internal use only: do not set these in general use.
  baseUrl?: string
  mediaBaseUrl?: string
  previewUrl?: string
  experimental?: readonly string[]
}

type FetchUserTokenFn = () => string | Promise<string>
type RoughTheme = 'light' | 'dark'

Options

Option Description
projectId Rough Project ID. Must match the identity token's iss.
externalUserId Your stable user ID. Must match the token's sub.
externalAccountId Your stable account ID. Must match the token's rough.account.id.
fetchUserToken Returns an identity token string from your authenticated backend, not a session object.
theme Builder and status-pill theme. Default: 'light'. Does not theme generated Features.
onError Called when authentication fails, including token identity mismatches.

Keep signing keys on your server. See token rules for backend requirements and identity scoping.

Client methods and lifetime

Method Contract
setTheme(theme: RoughTheme): void Updates the Builder and status pills, not generated Features.
destroy(): Promise<void> Closes client subscriptions, removes the full-screen Builder, and waits for client cleanup. Safe to call more than once.

Use one client per Project, account, and signed-in user; share it across Surfaces. When any part of the identity changes, clean up the old integration and create a new client. Unsubscribe from Feature lists, call unmount() on mounted Features, and unmount Builders from mountRoughBuilder() before destroying their client; destroy() does not remove them. In hooks that cannot await client cleanup, use void client.destroy(); otherwise, await it.

RoughClient is a type, not a constructor. Internal client services are not public API. Each client owns one full-screen Builder; opening another Feature with openRoughBuilder() navigates that same Builder. Builders from mountRoughBuilder() are separate.

Each Project/user/account combination has its own metadata cache. This does not isolate Feature application state.

Errors

Missing or invalid required options throw TypeError synchronously. Authentication failures go to onError. Catch rejected promises from other SDK operations at their call sites; onError is not a global handler.

Example

signedInUser comes from your authentication system. Implement the token endpoint on your backend.

import { startRoughClient } from '@roughapp/feature'

const client = startRoughClient({
  projectId: 'proj_123',
  externalUserId: signedInUser.id,
  externalAccountId: signedInUser.organisationId,
  fetchUserToken: async () => {
    const response = await fetch('/api/rough/user-token', {
      method: 'POST',
      credentials: 'include',
    })
    if (!response.ok) throw new Error('Could not get a Rough token')
    const { token } = (await response.json()) as { token: string }
    return token
  },
  onError: (error) => console.error('Rough authentication failed', error),
})

client.setTheme('dark')

defineRoughSurface()

Defines a Surface and its available capabilities. Returns the same object passed in, without validating, copying, or freezing it.

defineRoughSurface<Key extends string>(
  surface: RoughSurface<Key>,
): RoughSurface<Key>

type RoughSurface<Key extends string = string> = Readonly<{
  key: Key
  name: string
  description: string
  toolList: readonly (Query | Mutation | Subscription)[]
}>
Property Description
key Stable Surface identifier. Changing it selects a different Surface.
name Human-readable name.
description Describes this area of your application to Rough.
toolList Capabilities implemented by your app and available on this Surface.

Keep the object and its capability list unchanged while in use. Use consistent definitions for a given key; changing or removing capabilities can break existing Features. Definitions have no client or Project state and can be shared across clients.

Creating a Feature or opening its Builder registers the Surface with Rough. Subscribing to or mounting existing Features does not register it.

import { defineRoughSurface } from '@roughapp/feature'

const surface = defineRoughSurface({
  key: 'inbox',
  name: 'Inbox',
  description: 'The signed-in user’s message inbox.',
  toolList: [], // Add your Query, Mutation, and Subscription instances here.
})

See Capabilities for implementations and a populated Surface.

Capabilities

Query, Mutation, and Subscription are exported classes. Use Query for a read, Mutation for a write, and Subscription for ongoing updates.

Constructor options

All three accept the following fields. CapabilityOptions is explanatory, not an exported SDK type. InputSchema and OutputSchema extend z.ZodType.

type CapabilityOptions<
  InputSchema extends z.ZodType,
  OutputSchema extends z.ZodType,
> = {
  id: string
  name: string
  description: string
  inputSchema: InputSchema
  outputSchema: OutputSchema
  outputSample: z.output<OutputSchema>
}

Add an implementation with the appropriate signature:

// Query and Mutation:
implementation: (input: z.output<InputSchema>) => Promise<z.input<OutputSchema>>

// Subscription:
implementation: (
  emit: (output: z.input<OutputSchema>) => void,
  input: z.output<InputSchema>,
) => Promise<() => void>
Field Contract
id Stable capability identifier.
name, description Human-readable metadata describing the operation.
inputSchema Zod 4 schema used to parse arguments before implementation calls.
outputSchema Zod 4 schema used to parse returned or emitted values.
outputSample Representative parsed output for Builder previews.
implementation Host application code. Subscriptions return a function that stops updates.

Construct with new Query(options), new Mutation(options), or new Subscription(options). The corresponding static .create(options) methods are equivalent alternatives. Generic ID and schema types are inferred from the options.

Direct calls

query.call(input: z.input<InputSchema>): Promise<z.output<OutputSchema>>
mutation.call(input: z.input<InputSchema>): Promise<z.output<OutputSchema>>
subscription.subscribe(
  emit: (output: z.output<OutputSchema>) => void,
  input: z.input<InputSchema>,
): Promise<() => void>

Invalid input or output produces an Error. Query and Mutation calls reject on validation or implementation failure. Subscription input/setup failures reject subscribe(); invalid emitted values throw from emit, including later emissions from event handlers.

Schemas are not authorization. Enforce permissions in your application and backend. Rough receives serialized schemas and samples, not implementation code. Builder previews use samples, not live implementations; never include customer data or secrets in samples.

For examples, cleanup patterns, and schema type guidance, see Capabilities.

subscribeToRoughFeatures()

Reports published Features on a Surface and notifies when the list changes.

subscribeToRoughFeatures(options: SubscribeToRoughFeaturesOptions): () => void

type SubscribeToRoughFeaturesOptions = {
  client: RoughClient
  surface: RoughSurface
  onChange: (features: RoughFeature[]) => void
}
  • Returns an unsubscribe function, which returns void and is safe to call more than once. Call it when the owning view is removed.
  • onChange runs synchronously before this function returns, then whenever the list changes. The list is sorted by ID in descending order.
  • Only published Features appear. Unpublishing removes a Feature. Changes to the name, the published build, or its screenshot trigger updates; unrelated build progress does not.
  • The initial local list may be empty while metadata loads. An empty list does not indicate that loading has finished.
  • There is no ready promise or subscription-specific onError. Authentication failures go to the client's onError.
import { subscribeToRoughFeatures } from '@roughapp/feature'

const unsubscribe = subscribeToRoughFeatures({
  client,
  surface,
  onChange(features) {
    // Reconcile mounted Features with this list.
    console.log(features)
  },
})
// Call unsubscribe() from your view's teardown, not immediately.

Screenshots

After a build is published, Rough captures a screenshot of it in the background. Each Feature's screenshot is the published build's RoughFeatureScreenshot, or undefined.

Property Description
url Full-size screenshot: a 1280×960 JPEG.
thumbUrl The same screenshot scaled down to 640 pixels wide (640×480).
  • screenshot is undefined until a capture finishes uploading, and stays undefined if capture fails. Always handle undefined.
  • Screenshots render the Feature with your capabilities' outputSample values, not any user's data. They show what the Feature looks like, not what a given user sees.
  • Both URLs are public CDN URLs on mediaBaseUrl. They are hard to guess but do not expire; anyone with a link can load the image.

mountRoughFeature()

Renders a Feature inside an HTML element you own, using a shadow root. MountProps below is explanatory, not an SDK export.

type MountProps = {
  client: RoughClient
  surface: RoughSurface
  featureId: FeatureId
  buildId?: FeatureBuildId
  datastore?: RoughFrameDatastore
  isEditable?: boolean
}

mountRoughFeature(container: HTMLElement, props: MountProps): RoughFeatureMount

type RoughFeatureMount = {
  update: (props: Partial<MountProps>) => void
  unmount: () => void
}
Property Description
client Client for the current identity.
surface Surface the Feature belongs to.
featureId ID returned by creation or a published-Feature subscription.
buildId Optional specific build. Omit to follow the currently published build.
datastore Optional application-state store. Defaults to local storage keyed only by Feature ID.
isEditable Show the edit control. Default: true. Does not enforce authorization.

Mount handle and publication behavior

  • update(partialProps) changes selected props without requiring a remount.
  • unmount() tears down the mounted Feature. Call before removing its container. It is safe to call more than once. Its public type returns void, with no typed cleanup-completion promise.
  • Without buildId, new publications update the mounted Feature automatically. Unpublishing replaces the build with an unpublished status message.
  • A specific buildId remains selected even after unpublishing; its metadata must be available to the client.
  • update({ buildId: undefined }) resumes following the published build.

Default state is not user/account-isolated. Users of the same Feature on the same browser origin share stored application state. For isolation or cross-browser persistence, provide a datastore. See Feature state.

import { mountRoughFeature } from '@roughapp/feature'

const mount = mountRoughFeature(container, {
  client,
  surface,
  featureId: feature.id,
})
mount.update({ isEditable: false })
// Call mount.unmount() from your view's teardown.

RoughFrameDatastore

Custom application-state persistence passed through the mount's datastore option. See Feature state for scoping and implementations.

type RoughFrameDatastore = {
  get: () => JsonValue | undefined
  set: (state: JsonValue) => void | Promise<void>
  addListener: (callback: (state: JsonValue) => void) => () => void
}
Method Contract
get() Return current state synchronously, or undefined if none exists.
set(state) Save state and notify listeners. The SDK does not await a returned promise; handle persistence failures internally.
addListener() Register a callback and return its removal function. Notify for changes from other viewers too.

Keep the datastore object stable while mounted. Use separate state per Feature and, as needed, Project, user, and account. The interface provides no remote storage, authorization, or conflict-resolution implementation.

createRoughFeature()

Creates an unpublished Feature and registers its Surface.

createRoughFeature(options: CreateRoughFeatureOptions): Promise<RoughFeature>

type CreateRoughFeatureOptions = {
  client: RoughClient
  surface: RoughSurface
  name?: string
}

Returns a promise for locally created metadata. name defaults to '', surfaceKey is the Surface's key, and publishedFeatureBuildId and screenshot are undefined.

Resolution does not confirm server persistence. Rough saves the Feature in the background. You can open its Builder as soon as local creation resolves.

Closing the Builder retains the draft. Keep its ID to reopen it: the public SDK has no API to list or delete drafts. Published-Feature subscriptions exclude drafts.

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

const feature = await createRoughFeature({
  client,
  surface,
  name: 'Inbox summary',
})
await openRoughBuilder({ client, surface, featureId: feature.id })

Catch rejected promises at the call site. To edit an existing Feature, open its ID rather than creating another draft.

openRoughBuilder()

Opens the full-screen Builder for an existing draft or published Feature. To show the Builder inside your own layout, use mountRoughBuilder().

openRoughBuilder(options: OpenRoughBuilderOptions): Promise<void>

type OpenRoughBuilderOptions = {
  client: RoughClient
  surface: RoughSurface
  featureId: FeatureId
}

Registers the Surface, navigates the client's existing Builder to the Feature, and opens it. Resolves without a value; it does not wait for editing or publication. There is no returned handle or public close method. Catch rejected promises at the call site.

  • Users close the Builder through its UI. Closing does not delete drafts or cancel builds.
  • While closed, builds in progress have dismissible status pills showing completion or failure. Clicking a pill reopens its Feature.
  • There is no persistent Rough logo launcher. Provide your own button calling openRoughBuilder() to reopen a Feature without a status pill.
  • Set the theme through client startup options or client.setTheme(), not here.
  • Observe publication with subscribeToRoughFeatures(). Publishing updates the local list before server confirmation.
  • Chat and new builds require sufficient Workspace credit. The Builder displays availability and updates as it changes. If only builds are unavailable, users can still chat. These checks do not prevent mounting or subscribing to existing published Features.
import { openRoughBuilder } from '@roughapp/feature'

await openRoughBuilder({ client, surface, featureId: feature.id })

mountRoughBuilder()

Renders the Builder for an existing draft or published Feature inside an HTML element you own, using a shadow root.

mountRoughBuilder(
  container: HTMLElement,
  options: MountRoughBuilderOptions,
): RoughBuilderMount

type MountRoughBuilderOptions = {
  client: RoughClient
  surface: RoughSurface
  featureId: FeatureId
  isSidebarOpen?: boolean
}

type RoughBuilderMount = {
  unmount: () => Promise<void>
}
Option Description
client Client for the current identity.
surface Surface the Feature belongs to.
featureId ID returned by creation or a published-Feature subscription.
isSidebarOpen Whether the Feature list sidebar starts open. Default: true.
  • Returns synchronously. The Surface is registered in the background; a registration failure is logged to the console rather than thrown.
  • The container sets the Builder's size: the Builder fills its height, so give the container a definite height. At 700px wide or narrower, the Builder uses its compact layout.
  • Each mounted Builder navigates independently of the full-screen Builder and of other mounted Builders. Users can switch Features from its sidebar. There is no method to navigate it from code; unmount it and mount again with another featureId.
  • It has no close button and does not take focus when it mounts.
  • It follows the client's theme, including later client.setTheme() calls.
  • unmount() removes the Builder and resolves once cleanup is complete. It is safe to call more than once. Call it before removing the container and before destroying the client; client.destroy() does not remove mounted Builders.
  • Unmounting does not delete drafts or cancel builds.
  • Credit checks and publication behave as in the full-screen Builder.
import { createRoughFeature, mountRoughBuilder } from '@roughapp/feature'

const feature = await createRoughFeature({ client, surface })
const builder = mountRoughBuilder(container, {
  client,
  surface,
  featureId: feature.id,
  isSidebarOpen: false,
})
// Call `await builder.unmount()` from your view's teardown.

Types

Use import type for these exports.

Export Purpose
RoughClient Handle with setTheme() and destroy().
StartRoughClientOptions Client startup options.
FetchUserTokenFn () => string | Promise<string>.
RoughTheme 'light' | 'dark'.
RoughSurface<Key = string> Readonly Surface definition with an optional string key type parameter.
RoughFeature Feature metadata; shape below.
RoughFeatureScreenshot Screenshot URLs; shape below.
FeatureId, FeatureBuildId Branded string IDs.
RoughFeatureMount Handle with update() and unmount().
SubscribeToRoughFeaturesOptions Published-Feature subscription options.
CreateRoughFeatureOptions Feature creation options.
OpenRoughBuilderOptions Full-screen Builder opening options.
MountRoughBuilderOptions Options for mounting the Builder in a container.
RoughBuilderMount Handle with unmount() for a mounted Builder.
RoughFrameDatastore Application-state persistence interface.
JsonValue JSON-compatible state; shape below.
type RoughFeature = {
  id: FeatureId
  name: string
  surfaceKey: string
  publishedFeatureBuildId: FeatureBuildId | undefined
  screenshot: RoughFeatureScreenshot | undefined
}

type RoughFeatureScreenshot = {
  url: string
  thumbUrl: string
}

type JsonValue =
  | null
  | boolean
  | number
  | string
  | JsonValue[]
  | { [key: string]: JsonValue }

IDs returned by SDK calls can be passed directly to other SDK functions. A plain string loaded from storage or a URL needs validation and a cast to FeatureId or FeatureBuildId. Brands are compile-time only: casting does not verify existence or authorization.