Bolt.new is an AI-powered web development agent that allows you to prompt, run, edit, and deploy full-stack applications directly from your browser. This documentation covers all public APIs, functions, and components available in the codebase.
The main application root component that sets up the application structure, theme, and global styles.
App- Main application componentLayout- Layout wrapper componentHead- Head component for meta tags and stylesheetslinks- Function returning stylesheet links
import { App, Layout, Head, links } from '~/root';
// The App component is automatically used as the default export
// Layout wraps the application with theme and scroll restoration
// Head provides meta tags and stylesheets
// links function provides CSS importsHandles AI chat interactions with streaming support and automatic continuation for long responses.
{
messages: Message[] // Array of chat messages
}Returns a streaming response with AI-generated text.
- Streaming: Real-time text streaming from AI models
- Auto-continuation: Automatically continues long responses that exceed token limits
- Error handling: Graceful error handling with appropriate HTTP status codes
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
{ role: 'user', content: 'Hello, how are you?' }
]
})
});
// Handle streaming response
const reader = response.body?.getReader();
// Process stream...Improves user prompts using AI to make them more specific and effective.
{
message: string // The original prompt to enhance
}Returns a streaming response with the enhanced prompt.
const response = await fetch('/api/enhancer', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'Create a todo app'
})
});
// Handle streaming response for enhanced promptMain chat interface component that handles user interactions and AI responses.
interface ChatProps {
initialMessages: Message[];
storeMessageHistory: (messages: Message[]) => Promise<void>;
}- Message streaming: Real-time display of AI responses
- File modifications: Automatically includes file changes in messages
- Prompt enhancement: Built-in prompt improvement functionality
- Keyboard shortcuts: Global shortcut support
- Toast notifications: User feedback for actions
import { Chat } from '~/components/chat/Chat.client';
<Chat />Base chat component providing the UI structure for the chat interface.
interface BaseChatProps {
textareaRef: RefObject<HTMLTextAreaElement>;
input: string;
showChat: boolean;
chatStarted: boolean;
isStreaming: boolean;
enhancingPrompt: boolean;
promptEnhanced: boolean;
sendMessage: (event: React.UIEvent, messageInput?: string) => void;
messageRef: RefObject<HTMLDivElement>;
scrollRef: RefObject<HTMLDivElement>;
handleInputChange: (event: ChangeEvent<HTMLTextAreaElement>) => void;
handleStop: () => void;
messages: Message[];
enhancePrompt: () => void;
}Component for rendering chat messages with proper formatting.
interface MessagesProps {
messages: Message[];
messageRef: RefObject<HTMLDivElement>;
scrollRef: RefObject<HTMLDivElement>;
}Component for rendering user messages.
Component for rendering AI assistant messages.
Component for rendering code blocks with syntax highlighting.
interface CodeBlockProps {
children: string;
language?: string;
filename?: string;
}Component for rendering markdown content with proper formatting.
interface MarkdownProps {
children: string;
}Component for rendering AI-generated artifacts and actions.
interface ArtifactProps {
id: string;
title: string;
closed: boolean;
children: ReactNode;
}Main workbench component providing the development environment interface.
interface WorkspaceProps {
chatStarted?: boolean;
isStreaming?: boolean;
}- File editing: Integrated code editor
- Preview mode: Live preview of applications
- Terminal integration: Built-in terminal support
- File tree: File system navigation
- View switching: Toggle between code and preview modes
Panel component for the code editor interface.
interface EditorPanelProps {
editorDocument?: EditorDocument;
isStreaming?: boolean;
selectedFile?: string;
files: FileMap;
unsavedFiles: Set<string>;
onFileSelect: (filePath: string | undefined) => void;
onEditorScroll: (position: ScrollPosition) => void;
onEditorChange: (update: EditorUpdate) => void;
onFileSave: () => void;
onFileReset: () => void;
}Component for displaying and navigating the file system.
interface FileTreeProps {
files: FileMap;
selectedFile?: string;
onFileSelect: (filePath: string) => void;
}Component for rendering live previews of applications.
Component for displaying file path breadcrumbs.
interface FileBreadcrumbProps {
filePath: string;
onNavigate: (path: string) => void;
}Modal dialog component with animations and backdrop.
interface DialogProps {
children: ReactNode | ReactNode[];
className?: string;
onBackdrop?: (event: React.UIEvent) => void;
onClose?: (event: React.UIEvent) => void;
}DialogButton: Button component for dialogsinterface DialogButtonProps { type: 'primary' | 'secondary' | 'danger'; children: ReactNode; onClick?: (event: React.UIEvent) => void; }
DialogTitle: Title component for dialogsDialogDescription: Description component for dialogs
Button component with icon support.
interface IconButtonProps {
icon: string;
size?: 'sm' | 'md' | 'lg' | 'xl';
className?: string;
onClick?: (event: React.UIEvent) => void;
disabled?: boolean;
}Slider component for switching between options.
interface SliderOptions<T> {
left: {
value: T;
text: string;
};
right: {
value: T;
text: string;
};
}
interface SliderProps<T> {
selected: T;
options: SliderOptions<T>;
setSelected: (value: T) => void;
}Component for switching between light and dark themes.
Loading animation component with animated dots.
Header component for panels.
Button component for panel headers.
Main store for managing the workbench state and functionality.
class WorkbenchStore {
artifacts: MapStore<Record<string, ArtifactState>>;
showWorkbench: WritableAtom<boolean>;
currentView: WritableAtom<WorkbenchViewType>;
unsavedFiles: WritableAtom<Set<string>>;
modifiedFiles: Set<string>;
artifactIdList: string[];
}// File management
setDocuments(files: FileMap): void;
setSelectedFile(filePath: string | undefined): void;
setCurrentDocumentContent(newContent: string): void;
setCurrentDocumentScrollPosition(position: ScrollPosition): void;
saveFile(filePath: string): Promise<void>;
saveCurrentDocument(): Promise<void>;
saveAllFiles(): Promise<void>;
resetCurrentDocument(): void;
getFileModifcations(): FileModifications | undefined;
resetAllFileModifications(): void;
// Workbench control
setShowWorkbench(show: boolean): void;
toggleTerminal(value?: boolean): void;
attachTerminal(terminal: ITerminal): void;
onTerminalResize(cols: number, rows: number): void;
// Artifact management
addArtifact(data: ArtifactCallbackData): void;
updateArtifact(data: ArtifactCallbackData, state: Partial<ArtifactUpdateState>): void;
addAction(data: ActionCallbackData): Promise<void>;
runAction(data: ActionCallbackData): Promise<void>;
abortAllActions(): void;import { workbenchStore } from '~/lib/stores/workbench';
// Show/hide workbench
workbenchStore.setShowWorkbench(true);
// Select a file
workbenchStore.setSelectedFile('/src/App.tsx');
// Save current document
await workbenchStore.saveCurrentDocument();
// Get file modifications
const modifications = workbenchStore.getFileModifcations();Store for managing file system operations and state.
class FilesStore {
files: MapStore<FileMap>;
filesCount: number;
}getFile(filePath: string): File | undefined;
getFileModifications(): FileModifications | undefined;
resetFileModifications(): void;
saveFile(filePath: string, content: string): Promise<void>;interface File {
type: 'file';
content: string;
isBinary: boolean;
}
interface Folder {
type: 'folder';
}
type Dirent = File | Folder;
type FileMap = Record<string, Dirent | undefined>;Store for managing editor state and document content.
class EditorStore {
documents: MapStore<Record<string, EditorDocument>>;
selectedFile: WritableAtom<string | undefined>;
currentDocument: ReadableAtom<EditorDocument | undefined>;
}setDocuments(files: FileMap): void;
setSelectedFile(filePath: string | undefined): void;
updateFile(filePath: string, content: string): void;
updateScrollPosition(filePath: string, position: ScrollPosition): void;Store for managing chat state.
interface ChatStore {
showChat: WritableAtom<boolean>;
started: WritableAtom<boolean>;
aborted: WritableAtom<boolean>;
}Store for managing application theme.
interface ThemeStore {
theme: WritableAtom<'light' | 'dark'>;
}Store for managing application settings.
interface SettingsStore {
shortcuts: WritableAtom<Shortcuts>;
}Store for managing terminal state.
class TerminalStore {
showTerminal: WritableAtom<boolean>;
}toggleTerminal(value?: boolean): void;
attachTerminal(terminal: ITerminal): void;
onTerminalResize(cols: number, rows: number): void;Store for managing application previews.
class PreviewsStore {
previews: MapStore<Preview[]>;
}Hook for handling global keyboard shortcuts.
void - Sets up global keyboard event listeners
import { useShortcuts } from '~/lib/hooks/useShortcuts';
function MyComponent() {
useShortcuts();
// Component will now respond to configured shortcuts
}Hook for enhancing user prompts using AI.
{
enhancingPrompt: boolean;
promptEnhanced: boolean;
enhancePrompt: (input: string, setInput: (value: string) => void) => Promise<void>;
resetEnhancer: () => void;
}import { usePromptEnhancer } from '~/lib/hooks/usePromptEnhancer';
function MyComponent() {
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
const handleEnhance = () => {
enhancePrompt(input, setInput);
};
}Hook for parsing and processing chat messages.
{
parsedMessages: string[];
parseMessages: (messages: Message[], isLoading: boolean) => void;
}import { useMessageParser } from '~/lib/hooks/useMessageParser';
function MyComponent() {
const { parsedMessages, parseMessages } = useMessageParser();
useEffect(() => {
parseMessages(messages, isLoading);
}, [messages, isLoading]);
}Hook for implementing snap scrolling behavior.
[messageRef: RefObject<HTMLDivElement>, scrollRef: RefObject<HTMLDivElement>]import { useSnapScroll } from '~/lib/hooks/useSnapScroll';
function MyComponent() {
const [messageRef, scrollRef] = useSnapScroll();
return (
<div ref={scrollRef}>
<div ref={messageRef}>
{/* Messages */}
</div>
</div>
);
}Utilities for cryptographic operations.
function generateKey(): Promise<CryptoKey>;
function encrypt(data: string, key: CryptoKey): Promise<string>;
function decrypt(encryptedData: string, key: CryptoKey): Promise<string>;Enhanced fetch utilities with error handling.
function fetchWithTimeout(url: string, options?: RequestInit & { timeout?: number }): Promise<Response>;Utilities for handling recursive patterns in data structures.
function findRecursivePattern<T>(items: T[], pattern: (item: T) => boolean): T[];Logging utilities for debugging and monitoring.
function createScopedLogger(scope: string): Logger;
const renderLogger: Logger;import { createScopedLogger } from '~/utils/logger';
const logger = createScopedLogger('MyComponent');
logger.info('Component mounted');
logger.error('An error occurred', error);Utility for conditionally joining CSS class names.
function classNames(...classes: (string | boolean | undefined | null)[]): string;import { classNames } from '~/utils/classNames';
const className = classNames(
'base-class',
isActive && 'active',
isDisabled && 'disabled'
);Easing functions for animations.
function cubicEasingFn(t: number): number;Utility for removing common indentation from template literals.
function stripIndents(strings: TemplateStringsArray, ...values: any[]): string;import { stripIndents } from '~/utils/stripIndent';
const code = stripIndents`
function hello() {
console.log('Hello, world!');
}
`;Utilities for computing and displaying file differences.
function computeFileModifications(files: FileMap, modifiedFiles: Map<string, string>): FileModifications | undefined;
function fileModificationsToHTML(modifications: FileModifications): string;Application constants.
const WORK_DIR: string;
const MAX_TOKENS: number;
const MAX_RESPONSE_SEGMENTS: number;interface Message {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
createdAt?: Date;
}interface EditorDocument {
filePath: string;
value: string;
scrollPosition?: ScrollPosition;
}
interface ScrollPosition {
top: number;
left: number;
}
interface EditorUpdate {
content: string;
// Additional editor-specific properties
}interface File {
type: 'file';
content: string;
isBinary: boolean;
}
interface Folder {
type: 'folder';
}
type Dirent = File | Folder;
type FileMap = Record<string, Dirent | undefined>;interface ITerminal {
write(data: string): void;
resize(cols: number, rows: number): void;
// Additional terminal methods
}interface ArtifactState {
id: string;
title: string;
closed: boolean;
runner: ActionRunner;
}
interface ArtifactCallbackData {
messageId: string;
title: string;
id: string;
}
interface ActionCallbackData {
messageId: string;
actionId: string;
// Additional action-specific properties
}interface Shortcuts {
[key: string]: {
key: string;
ctrlKey?: boolean;
metaKey?: boolean;
shiftKey?: boolean;
altKey?: boolean;
ctrlOrMetaKey?: boolean;
action: () => void;
};
}- Clone the repository
- Install dependencies:
pnpm install - Set up environment variables
- Run development server:
pnpm dev
import { Chat } from '~/components/chat/Chat.client';
import { Workbench } from '~/components/workbench/Workbench.client';
function App() {
return (
<div>
<Chat />
<Workbench chatStarted={true} />
</div>
);
}The application can be configured through various stores and environment variables. Key configuration options include:
- Theme: Light/dark mode via
themeStore - Shortcuts: Keyboard shortcuts via
settingsStore - API Endpoints: Configured in environment variables
- WebContainer: Development environment settings
For information on contributing to the Bolt.new codebase, see the CONTRIBUTING.md file.
This project is licensed under the MIT License - see the LICENSE file for details.