feat: support standalone example crates

This commit is contained in:
Yujong Lee 2026-09-10 14:55:46 -07:00
parent e57ce550b8
commit 903e4c216d
14 changed files with 349 additions and 114 deletions

View file

@ -24,7 +24,7 @@
<section class="workspace">
<aside class="docs" aria-label="Markdown document">
<div class="docbar">
<span>GUIDE.md</span>
<span id="guide-path">GUIDE.md</span>
<span class="document-language">Markdown</span>
</div>
<div id="markdown-editor"></div>
@ -38,8 +38,9 @@
<div class="editor-body">
<div id="editors"></div>
<aside class="file-tree" aria-label="Project files">
<p class="tree-title">EXPLORER</p>
<div class="tree-folder">src</div>
<p class="tree-title">EXAMPLES</p>
<nav id="example-nav" class="example-nav" aria-label="Examples"></nav>
<p class="tree-title files-title">FILES</p>
<nav id="file-nav" class="file-nav"></nav>
</aside>
</div>

View file

@ -1,5 +1,5 @@
import { spawn } from 'node:child_process';
import { readFile, writeFile } from 'node:fs/promises';
import { readdir, readFile, writeFile } from 'node:fs/promises';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
@ -10,8 +10,7 @@ import { WebSocketServer } from 'ws';
const playgroundDirectory = path.dirname(fileURLToPath(import.meta.url));
const repositoryDirectory = path.resolve(playgroundDirectory, '..');
const workspaceDirectory = path.join(playgroundDirectory, 'workspace');
const sourcePaths = ['src/main.rs', 'src/proof.rs'];
const cargoManifestPath = path.join(workspaceDirectory, 'Cargo.toml');
const examplesDirectory = path.join(workspaceDirectory, 'examples');
const port = Number(process.env.PORT ?? 5173);
const readRequestBody = request =>
@ -57,6 +56,54 @@ const gitRevision = async () => {
return result.success ? result.output.trim() : 'unknown';
};
const listRustFiles = async (directory, relativeDirectory = 'src') => {
const entries = await readdir(path.join(directory, relativeDirectory), { withFileTypes: true });
const files = await Promise.all(entries.map(async entry => {
const relativePath = path.posix.join(relativeDirectory, entry.name);
if (entry.isDirectory()) {
return listRustFiles(directory, relativePath);
}
return entry.isFile() && entry.name.endsWith('.rs') ? [relativePath] : [];
}));
return files.flat().sort();
};
const titleFromId = id => id
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
const readExamples = async () => {
const entries = await readdir(examplesDirectory, { withFileTypes: true });
const directories = entries.filter(entry => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name));
return Promise.all(directories.map(async entry => {
const id = entry.name;
const directory = path.join(examplesDirectory, id);
const sourcePaths = ['Cargo.toml', ...await listRustFiles(directory)];
const [guideSource, files] = await Promise.all([
readFile(path.join(directory, 'GUIDE.md'), 'utf8'),
Promise.all(sourcePaths.map(async filePath => ({
languageId: filePath.endsWith('.rs') ? 'rust' : 'toml',
path: filePath,
source: await readFile(path.join(directory, filePath), 'utf8'),
target: path.posix.join('examples', id, filePath),
uri: pathToFileURL(path.join(directory, filePath)).href,
}))),
]);
return {
directory,
files,
guide: {
path: 'GUIDE.md',
source: guideSource,
target: path.posix.join('examples', id, 'GUIDE.md'),
},
id,
title: titleFromId(id),
};
}));
};
const vite = await createViteServer({
root: playgroundDirectory,
server: { middlewareMode: true },
@ -65,17 +112,10 @@ const vite = await createViteServer({
const server = http.createServer(async (request, response) => {
if (request.method === 'GET' && request.url === '/api/info') {
const [sources, revision] = await Promise.all([
Promise.all(sourcePaths.map(async filePath => ({
path: filePath,
uri: pathToFileURL(path.join(workspaceDirectory, filePath)).href,
source: await readFile(path.join(workspaceDirectory, filePath), 'utf8'),
}))),
gitRevision(),
]);
const [examples, revision] = await Promise.all([readExamples(), gitRevision()]);
sendJson(response, 200, {
revision,
files: sources,
examples: examples.map(({ directory: _directory, ...example }) => example),
rootUri: pathToFileURL(workspaceDirectory).href,
});
return;
@ -84,19 +124,21 @@ const server = http.createServer(async (request, response) => {
if (request.method === 'POST' && request.url === '/api/run') {
try {
const body = JSON.parse(await readRequestBody(request));
const filesAreValid = body.files && sourcePaths.every(
filePath => typeof body.files[filePath] === 'string',
const examples = await readExamples();
const example = examples.find(candidate => candidate.id === body.exampleId);
const filesAreValid = example && body.files && example.files.every(
file => typeof body.files[file.path] === 'string',
);
if (!filesAreValid) {
sendJson(response, 400, { success: false, output: 'Both Rust source files are required' });
if (!example || !filesAreValid) {
sendJson(response, 400, { success: false, output: 'A valid example and all of its files are required' });
return;
}
await Promise.all(sourcePaths.map(
filePath => writeFile(path.join(workspaceDirectory, filePath), body.files[filePath], 'utf8'),
await Promise.all(example.files.map(
file => writeFile(path.join(example.directory, file.path), body.files[file.path], 'utf8'),
));
const result = await runCommand(
'cargo',
['run', '--quiet', '--locked', '--manifest-path', cargoManifestPath],
['run', '--quiet', '--manifest-path', path.join(example.directory, 'Cargo.toml')],
{ cwd: workspaceDirectory, stdio: ['ignore', 'pipe', 'pipe'] },
);
sendJson(response, 200, result);

View file

@ -16,31 +16,30 @@ import { EditorView, basicSetup } from 'codemirror';
import './style.css';
const STORAGE_KEY = 'litellm-rust-playground-files';
const GUIDE_PATH = 'GUIDE.md';
const DEFAULT_GUIDE = `# Prove the connection
Click [the \`build_proof\` definition](playground://src/proof.rs#L9), or Cmd-click \`build_proof\` in \`src/main.rs\`.
Hover \`litellm_core::Error\` for dependency type information.
## What this uses
- **Editor:** CodeMirror 6
- **Language server:** rust-analyzer over WebSocket
- **Dependency:** in-repo \`litellm-core\` path dependency
- **Proc macro:** Serde \`Serialize\` and \`Deserialize\` derives
> This Markdown and the Rust source are saved in this browser. Reset restores the example.
`;
type PlaygroundFile = {
languageId: 'rust' | 'toml';
path: string;
uri: string;
source: string;
target: string;
uri: string;
};
type PlaygroundGuide = {
path: string;
source: string;
target: string;
};
type PlaygroundExample = {
files: PlaygroundFile[];
guide: PlaygroundGuide;
id: string;
title: string;
};
type PlaygroundInfo = {
files: PlaygroundFile[];
examples: PlaygroundExample[];
rootUri: string;
revision: string;
};
@ -127,8 +126,10 @@ const runStatus = requireElement<HTMLSpanElement>('run-status');
const output = requireElement<HTMLPreElement>('output');
const editorsParent = requireElement<HTMLDivElement>('editors');
const markdownEditorParent = requireElement<HTMLDivElement>('markdown-editor');
const exampleNav = requireElement<HTMLElement>('example-nav');
const fileNav = requireElement<HTMLElement>('file-nav');
const activePath = requireElement<HTMLSpanElement>('active-path');
const guidePath = requireElement<HTMLSpanElement>('guide-path');
const commandClickDefinition = EditorView.domEventHandlers({
mousedown(event, view) {
@ -149,7 +150,7 @@ const commandClickDefinition = EditorView.domEventHandlers({
});
const playgroundLinkMatcher = new MatchDecorator({
regexp: /\[[^\]\n]+\]\(playground:\/\/[^)\s]+\)/g,
regexp: /\[[^\]\n]+\]\([a-z][a-z0-9+.-]*:\/\/[^)\s]+\)/gi,
decoration: Decoration.mark({ class: 'cm-playground-link' }),
});
@ -180,7 +181,7 @@ const markdownFileNavigation = (openTarget: (target: string) => boolean) =>
}
const line = view.state.doc.lineAt(position);
const offset = position - line.from;
const matches = line.text.matchAll(/\[([^\]\n]+)\]\((playground:\/\/[^)\s]+)\)/g);
const matches = line.text.matchAll(/\[([^\]\n]+)\]\(([a-z][a-z0-9+.-]*:\/\/[^)\s]+)\)/gi);
for (const match of matches) {
const start = match.index;
if (offset >= start && offset <= start + match[0].length && openTarget(match[2])) {
@ -228,11 +229,11 @@ const loadInfo = async (): Promise<PlaygroundInfo> => {
return response.json() as Promise<PlaygroundInfo>;
};
const runCode = async (files: StoredFiles): Promise<RunResult> => {
const runCode = async (exampleId: string, files: StoredFiles): Promise<RunResult> => {
const response = await fetch('/api/run', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ files }),
body: JSON.stringify({ exampleId, files }),
});
return response.json() as Promise<RunResult>;
};
@ -252,37 +253,112 @@ const saveStoredFile = (path: string, source: string) => {
const main = async () => {
const info = await loadInfo();
const initialExample = info.examples[0];
if (!initialExample) {
throw new Error('No runnable examples found');
}
const storedFiles = loadStoredFiles();
const allFiles = info.examples.flatMap(example => example.files.map(file => ({ example, file })));
const fileByUri = new Map(allFiles.map(entry => [entry.file.uri, entry]));
const views = new Map<string, EditorView>();
const containers = new Map<string, HTMLDivElement>();
const buttons = new Map<string, HTMLButtonElement>();
let activeUri = info.files[0]?.uri ?? '';
const markdownViews = new Map<string, EditorView>();
const markdownContainers = new Map<string, HTMLDivElement>();
const exampleButtons = new Map<string, HTMLButtonElement>();
const fileButtons = new Map<string, HTMLButtonElement>();
let activeExampleId = initialExample.id;
let activeUri = '';
const renderFileTree = (example: PlaygroundExample) => {
fileNav.replaceChildren();
fileButtons.clear();
const root = document.createElement('div');
root.className = 'tree-folder tree-root';
root.textContent = `${example.id}://`;
fileNav.append(root);
const rootFiles = example.files.filter(file => !file.path.includes('/'));
const sourceFiles = example.files.filter(file => file.path.startsWith('src/'));
const addFileButton = (file: PlaygroundFile, depth: 'root' | 'child') => {
const button = document.createElement('button');
button.className = 'file-tree-item';
button.dataset.active = String(file.uri === activeUri);
button.dataset.depth = depth;
button.dataset.kind = file.languageId === 'rust' ? 'rs' : 'toml';
button.type = 'button';
button.textContent = depth === 'child' ? file.path.replace('src/', '') : file.path;
button.addEventListener('click', () => showFile(file.uri));
fileNav.append(button);
fileButtons.set(file.uri, button);
};
rootFiles.forEach(file => addFileButton(file, 'root'));
if (sourceFiles.length > 0) {
const sourceFolder = document.createElement('div');
sourceFolder.className = 'tree-folder tree-child-folder';
sourceFolder.textContent = 'src';
fileNav.append(sourceFolder);
sourceFiles.forEach(file => addFileButton(file, 'child'));
}
};
const selectExample = (exampleId: string, selectDefaultFile = true) => {
const example = info.examples.find(candidate => candidate.id === exampleId);
if (!example) {
return false;
}
activeExampleId = example.id;
exampleButtons.forEach((button, candidate) => {
button.dataset.active = String(candidate === example.id);
});
markdownContainers.forEach((container, candidate) => {
container.hidden = candidate !== example.id;
});
guidePath.textContent = `${example.id}://${example.guide.path}`;
renderFileTree(example);
if (selectDefaultFile) {
const current = fileByUri.get(activeUri);
const file = current?.example.id === example.id ? current.file : example.files.find(candidate => candidate.path === 'src/main.rs');
if (file) {
showFile(file.uri);
}
}
return true;
};
const showFile = (uri: string) => {
const entry = fileByUri.get(uri);
const view = views.get(uri);
if (!view) {
if (!entry || !view) {
return null;
}
if (entry.example.id !== activeExampleId) {
selectExample(entry.example.id, false);
}
activeUri = uri;
containers.forEach((container, candidate) => {
container.hidden = candidate !== uri;
});
buttons.forEach((button, candidate) => {
fileButtons.forEach((button, candidate) => {
button.dataset.active = String(candidate === uri);
});
activePath.textContent = info.files.find(file => file.uri === uri)?.path ?? uri;
activePath.textContent = `${entry.example.id}://${entry.file.path}`;
view.focus();
return view;
};
const openFileTarget = (target: string) => {
const match = /^playground:\/\/(.+?)(?:#L(\d+))?$/.exec(target);
const file = match ? info.files.find(candidate => candidate.path === match[1]) : undefined;
const match = /^([a-z][a-z0-9+.-]*):\/\/(.+?)(?:#L(\d+))?$/i.exec(target);
const example = match ? info.examples.find(candidate => candidate.id === match[1]) : undefined;
const file = example?.files.find(candidate => candidate.path === match?.[2]);
const view = file ? showFile(file.uri) : null;
if (!view) {
return false;
}
const requestedLine = Number(match?.[2] ?? 1);
const requestedLine = Number(match?.[3] ?? 1);
const line = view.state.doc.line(Math.min(Math.max(requestedLine, 1), view.state.doc.lines));
view.dispatch({
selection: { anchor: line.from },
@ -291,6 +367,17 @@ const main = async () => {
return true;
};
info.examples.forEach(example => {
const button = document.createElement('button');
button.className = 'example-item';
button.dataset.active = String(example.id === activeExampleId);
button.type = 'button';
button.textContent = example.title;
button.addEventListener('click', () => selectExample(example.id));
exampleNav.append(button);
exampleButtons.set(example.id, button);
});
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const transport = await connectTransport(`${protocol}//${location.host}/lsp`);
const client = new LSPClient({
@ -311,35 +398,27 @@ const main = async () => {
await client.initializing;
info.files.forEach(file => {
const button = document.createElement('button');
button.className = 'file-tree-item';
button.type = 'button';
button.textContent = file.path.replace('src/', '');
button.addEventListener('click', () => showFile(file.uri));
fileNav.append(button);
buttons.set(file.uri, button);
allFiles.forEach(({ file }) => {
const container = document.createElement('div');
container.className = 'editor-container';
container.hidden = file.uri !== activeUri;
container.hidden = true;
editorsParent.append(container);
containers.set(file.uri, container);
const languageExtensions = file.languageId === 'rust'
? [rust(), client.plugin(file.uri, 'rust'), commandClickDefinition]
: [];
const view = new EditorView({
doc: storedFiles[file.path] ?? file.source,
doc: storedFiles[file.target] ?? file.source,
extensions: [
basicSetup,
rust(),
oneDark,
client.plugin(file.uri, 'rust'),
commandClickDefinition,
languageExtensions,
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (!update.docChanged) {
return;
if (update.docChanged) {
saveStoredFile(file.target, update.state.doc.toString());
}
saveStoredFile(file.path, update.state.doc.toString());
}),
],
parent: container,
@ -347,41 +426,55 @@ const main = async () => {
views.set(file.uri, view);
});
const markdownView = new EditorView({
doc: storedFiles[GUIDE_PATH] ?? DEFAULT_GUIDE,
extensions: [
basicSetup,
markdown(),
oneDark,
playgroundLinkDecorations,
markdownFileNavigation(openFileTarget),
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (update.docChanged) {
saveStoredFile(GUIDE_PATH, update.state.doc.toString());
}
}),
],
parent: markdownEditorParent,
info.examples.forEach(example => {
const container = document.createElement('div');
container.className = 'markdown-container';
container.hidden = example.id !== activeExampleId;
markdownEditorParent.append(container);
markdownContainers.set(example.id, container);
const view = new EditorView({
doc: storedFiles[example.guide.target] ?? example.guide.source,
extensions: [
basicSetup,
markdown(),
oneDark,
playgroundLinkDecorations,
markdownFileNavigation(openFileTarget),
EditorView.lineWrapping,
EditorView.updateListener.of(update => {
if (update.docChanged) {
saveStoredFile(example.guide.target, update.state.doc.toString());
}
}),
],
parent: container,
});
markdownViews.set(example.id, view);
});
showFile(activeUri);
selectExample(activeExampleId);
lspStatus.textContent = 'rust-analyzer connected';
lspStatus.dataset.state = 'ready';
if (diagnosticStatus.textContent === 'Diagnostics pending') {
diagnosticStatus.textContent = `${info.files.length} files open in LSP`;
const rustFileCount = allFiles.filter(entry => entry.file.languageId === 'rust').length;
diagnosticStatus.textContent = `${rustFileCount} Rust files open in LSP`;
diagnosticStatus.dataset.state = 'ready';
}
revision.textContent = info.revision.slice(0, 8);
runButton.addEventListener('click', async () => {
const example = info.examples.find(candidate => candidate.id === activeExampleId);
if (!example) {
return;
}
runButton.disabled = true;
runStatus.textContent = 'Compiling';
runStatus.textContent = `Running ${example.title}`;
output.textContent = '';
const files = Object.fromEntries(
info.files.map(file => [file.path, views.get(file.uri)?.state.doc.toString() ?? file.source]),
example.files.map(file => [file.path, views.get(file.uri)?.state.doc.toString() ?? file.source]),
);
const result = await runCode(files);
const result = await runCode(example.id, files);
output.textContent = result.output;
runStatus.textContent = result.success ? 'Finished' : 'Failed';
runStatus.dataset.state = result.success ? 'ready' : 'error';
@ -389,13 +482,17 @@ const main = async () => {
});
resetButton.addEventListener('click', () => {
localStorage.removeItem(STORAGE_KEY);
info.files.forEach(file => {
const example = info.examples.find(candidate => candidate.id === activeExampleId);
if (!example) {
return;
}
example.files.forEach(file => {
const view = views.get(file.uri);
view?.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: file.source } });
});
markdownView.dispatch({
changes: { from: 0, to: markdownView.state.doc.length, insert: DEFAULT_GUIDE },
const markdownView = markdownViews.get(example.id);
markdownView?.dispatch({
changes: { from: 0, to: markdownView.state.doc.length, insert: example.guide.source },
});
});
};

View file

@ -179,7 +179,7 @@ h1 {
.editor-body {
display: grid;
grid-template-columns: minmax(0, 1fr) 10.5rem;
grid-template-columns: minmax(0, 1fr) 12.5rem;
min-width: 0;
min-height: 0;
}
@ -204,6 +204,7 @@ h1 {
#editors,
#markdown-editor,
.markdown-container,
.editor-container,
.cm-editor {
height: 100%;
@ -230,6 +231,39 @@ h1 {
letter-spacing: 0.12em;
}
.files-title {
margin-top: 0.55rem;
border-top: 1px solid #292e36;
}
.example-nav,
.file-nav {
display: flex;
flex-direction: column;
}
.example-item {
width: 100%;
padding: 0.48rem 0.75rem;
border: 0;
border-left: 2px solid transparent;
color: #858c97;
background: transparent;
cursor: pointer;
font-family: inherit;
text-align: left;
}
.example-item:hover,
.example-item[data-active='true'] {
color: #eef0f3;
background: #191d23;
}
.example-item[data-active='true'] {
border-left-color: #bd5b2f;
}
.tree-folder {
display: flex;
align-items: center;
@ -239,17 +273,20 @@ h1 {
font-weight: 650;
}
.tree-root {
color: #eef0f3;
}
.tree-child-folder {
padding-left: 1.25rem;
}
.tree-folder::before {
color: #777f8b;
content: '\25BE';
font-size: 0.65rem;
}
.file-nav {
display: flex;
flex-direction: column;
}
.file-tree-item {
position: relative;
width: 100%;
@ -267,10 +304,18 @@ h1 {
position: absolute;
left: 0.85rem;
color: #c96f43;
content: 'rs';
content: attr(data-kind);
font-size: 0.62rem;
}
.file-tree-item[data-depth='child'] {
padding-left: 2.55rem;
}
.file-tree-item[data-depth='child']::before {
left: 1.35rem;
}
.file-tree-item:hover,
.file-tree-item[data-active='true'] {
color: #eef0f3;
@ -340,7 +385,7 @@ h1 {
}
.editor-body {
grid-template-columns: minmax(0, 1fr) 8.5rem;
grid-template-columns: minmax(0, 1fr) 10.5rem;
}
.output-panel {

View file

@ -533,7 +533,14 @@ dependencies = [
]
[[package]]
name = "litellm-playground-example"
name = "litellm-playground-error-type"
version = "0.1.0"
dependencies = [
"litellm-core",
]
[[package]]
name = "litellm-playground-proc-macro"
version = "0.1.0"
dependencies = [
"litellm-core",

View file

@ -1,10 +1,3 @@
[package]
name = "litellm-playground-example"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
litellm-core = { path = "../../litellm-rust/crates/core" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[workspace]
members = ["examples/error-type", "examples/proc-macro"]
resolver = "3"

View file

@ -0,0 +1,8 @@
[package]
name = "litellm-playground-error-type"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
litellm-core = { path = "../../../../litellm-rust/crates/core" }

View file

@ -0,0 +1,9 @@
# In-repo dependency app
This standalone binary package imports a type directly from LiteLLM's Rust crate.
- [Open the main function](error-type://src/main.rs#L3)
- [Open the report module](error-type://src/report.rs#L1)
- [Open its Cargo manifest](error-type://Cargo.toml#L1)
Run the example to print the fully qualified name of `litellm_core::Error`. No model or network request is involved.

View file

@ -0,0 +1,5 @@
mod report;
fn main() {
println!("{}", report::dependency_report());
}

View file

@ -0,0 +1,6 @@
pub fn dependency_report() -> String {
format!(
"LiteLLM Rust error type: {}",
std::any::type_name::<litellm_core::Error>()
)
}

View file

@ -0,0 +1,10 @@
[package]
name = "litellm-playground-proc-macro"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
litellm-core = { path = "../../../../litellm-rust/crates/core" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

View file

@ -0,0 +1,9 @@
# Proc macro app
This example is a standalone binary Cargo package with its own `main` function.
- [Open the entry point](proc-macro://src/main.rs#L1)
- [Open the derived data model](proc-macro://src/proof.rs#L3)
- [Open its Cargo manifest](proc-macro://Cargo.toml#L1)
`CompilerProof` derives Serde's `Serialize` and `Deserialize` procedural macros. The app also references `litellm_core::Error` from the in-repo LiteLLM Rust crate.

View file

@ -6,5 +6,8 @@ fn main() {
let proof = build_proof();
let json = serde_json::to_string_pretty(&proof).unwrap();
println!("{json}");
println!("litellm-core error type: {}", std::any::type_name::<litellm_core::Error>());
println!(
"litellm-core error type: {}",
std::any::type_name::<litellm_core::Error>()
);
}