feat: improve documentation site and playground with real code execution - #736
Conversation
Remove 'needs: build-windows' dependency from build-docs job so it starts immediately and runs in its own concurrency group (pages). The issue was that when multiple commits are pushed to master quickly, the main workflow's cancel-in-progress: true setting would cancel the entire workflow before build-docs could complete. Since build-docs has its own concurrency group with cancel-in-progress: false, removing the dependency allows it to run independently and complete even when the main workflow is cancelled by a newer commit. The docs job builds from source anyway, so it doesn't need build-windows. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add step to remove pre-installed software that's not needed for docs: - Old .NET versions (6.x, 7.x) - Android SDK - GHC (Haskell) - CodeQL - Chromium - PowerShell This frees up ~20GB+ of disk space to prevent "no space left on device" errors during the documentation build. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add Vercel serverless API for real C# code execution via Piston - Expand playground examples from 14 to 31 across 10 categories - Fix homepage by creating root index.md - Add missing tutorials (clustering, audio) - Add example documentation files (TensorBasics, NeuralNetworkTraining, etc.) - Update playground to .NET 10 with wasm-tools optimization - Fix Blazor error handling to show informative messages - Remove unnecessary CSS reference that caused 404 - Add logo.svg and favicon.svg - Update CodeExecutionService to call Vercel API with simulation fallback - Add local testing scripts for documentation Note: Vercel API deployment required for real code execution. Deploy with: cd api && vercel login && vercel deploy --prod Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings. WalkthroughAdds a Vercel serverless C# execution endpoint with TypeScript scaffolding and rate limiting, integrates Playground execution to prefer API-backed runs with a browser simulation fallback, expands documentation/examples and local doc build scripts, upgrades the Playground to .NET 10, and adds deployment and .gitignore updates. Changes
Sequence Diagram(s)sequenceDiagram
actor User as Playground Client
participant UI as Playground UI
participant Service as CodeExecutionService
participant API as /api/execute (Vercel)
participant Piston as Piston API
participant Simulator as Browser Simulator
User->>UI: Submit code
UI->>Service: ExecuteAsync(code)
Service->>Service: Validate & detect APIs
Service->>API: TryExecuteViaApiAsync(code)
alt API reachable & accepted
API->>API: Preprocess, security checks, rate-limit
API->>Piston: POST execution request
Piston-->>API: Execution response
API-->>Service: ExecutionResult
Service-->>UI: Display result
else API unreachable / rate-limited
API-->>Service: Error / Rate limit
Service->>Simulator: ExecuteSimulation(code)
Simulator->>Simulator: Detect AiDotNet usage & synthesize output
Simulator-->>Service: SimulatedResult (notice)
Service-->>UI: Display simulated result
end
UI-->>User: Show output
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR significantly enhances the AiDotNet documentation site and playground, adding real code execution capabilities, expanding examples, and fixing critical homepage issues.
Changes:
- Added Vercel serverless API for real C# code execution via Piston
- Expanded playground examples from 14 to 31 across 10 categories with detailed tutorials
- Fixed broken homepage and navigation by creating missing index files
Reviewed changes
Copilot reviewed 20 out of 24 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| vercel.json | Vercel deployment configuration for serverless API |
| src/AiDotNet.Playground/wwwroot/index.html | Fixed Blazor error handling and removed 404-causing CSS reference |
| src/AiDotNet.Playground/Services/ExampleService.cs | Expanded examples from 14 to 31 across 10 categories |
| src/AiDotNet.Playground/Services/CodeExecutionService.cs | Added real code execution via Piston API with fallback simulation |
| src/AiDotNet.Playground/AiDotNet.Playground.csproj | Updated to .NET 10 preview packages |
| scripts/test-docs-local.sh | Added bash script for local documentation testing |
| scripts/test-docs-local.ps1 | Added PowerShell script for local documentation testing |
| index.md | Created root index page to fix homepage showing raw JSON |
| docs/tutorials/clustering/index.md | Added comprehensive clustering tutorial |
| docs/tutorials/audio/index.md | Added audio processing tutorial with Whisper and TTS |
| docs/images/logo.svg | Added neural network logo graphic |
| docs/images/favicon.svg | Added favicon graphic |
| docs/examples/index.md | Created examples index page to fix broken /examples link |
| docs/examples/TransformerExample.md | Added transformer model usage guide |
| docs/examples/TensorBasics.md | Added tensor operations guide |
| docs/examples/NeuralNetworkTraining.md | Added neural network training guide |
| docs/examples/ClusteringExample.md | Added customer segmentation example |
| docfx.json | Updated target framework and logo paths |
| api/tsconfig.json | TypeScript configuration for Vercel API |
| api/package.json | Node.js dependencies for Vercel API |
| api/execute.ts | Vercel serverless function for C# code execution |
| .gitignore | Added DocFX and Vercel build artifacts |
| .github/workflows/sonarcloud.yml | Fixed docs deployment by removing dependency and adding disk space cleanup |
Files not reviewed (1)
- api/package-lock.json: Language not supported
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 14
🤖 Fix all issues with AI agents
In `@api/execute.ts`:
- Around line 142-150: The runtime-error check currently only triggers when both
result.run.code !== 0 and result.run.stderr exist; change it to treat any
non-zero exit code as an error (i.e., use OR logic: result.run.code !== 0 ||
result.run.stderr) and when reporting the error prefer stderr but fall back to
stdout if stderr is empty so the error field contains whichever output carries
the failure details; update the block around result.run (in api/execute.ts) that
returns { success:false, output, error, executionTime } accordingly.
- Around line 64-69: The current detection uses
!code.includes(usingStatement.replace('using ', '').replace(';', '')) which can
false-positive on any occurrence of the namespace; change the check in the
requiredUsings loop to look specifically for an existing using directive by
matching the full using statement pattern (e.g., a regex that searches for a
line like /^\s*using\s+<namespace>\s*;/m or checks for the exact string "using
<namespace>;"), escaping the namespace from usingStatement as needed; update the
condition that decides whether to prepend usingStatement to processedCode so it
only skips when a real using directive for that namespace already exists (use
the variables requiredUsings, usingStatement, code, processedCode to locate and
modify the logic).
- Around line 242-263: The regex blacklist in dangerousPatterns is useful but
bypassable; update the check to first normalize the incoming code (collapse
simple string literal concatenations and decode common escaped/unicode
sequences) before running pattern.test against the normalized code, and add a
clear comment above dangerousPatterns noting these checks are defense-in-depth
only and the real security boundary is the execution sandbox (Piston/Isolate);
keep the current response behavior (res.status(400)... ) when a pattern matches.
In `@api/package.json`:
- Around line 7-11: The package.json scripts include a "lint" entry that calls
"eslint" but eslint is not listed in devDependencies; either add eslint to
devDependencies (e.g., install and add an appropriate version and peer/config
packages) so the "lint" script works, or remove the "lint" script entirely from
the "scripts" block; update package.json's "devDependencies" to include "eslint"
if you choose to add it, and ensure any required config (ESLint config or
plugins) are present for the project.
- Around line 12-19: Update the `@vercel/node` devDependency from "3.0.0" to the
current 5.x release (e.g. "^5.5.24") in package.json so the project targets
Vercel's modern runtime; after changing the "@vercel/node" version string, run
your package manager (npm/yarn/pnpm) to update node_modules and regenerate the
lockfile (package-lock.json / yarn.lock / pnpm-lock.yaml) and run the test/build
to catch any compatibility issues.
In `@docfx.json`:
- Line 15: Update the TargetFramework value in docfx.json from "net8.0" to
"net10.0" so DocFX extracts APIs matching the project's primary target; confirm
this aligns with AiDotNet.csproj and AiDotNet.Tensors.csproj which target
"net10.0;net471" to avoid missing net10-specific APIs.
In `@docs/examples/TensorBasics.md`:
- Around line 188-189: The example incorrectly constructs a 1D tensor but claims
a 4D shape; update the example to construct a Tensor<float> with explicit shape
[1,3,1,4] so that calling Tensor<T>.Squeeze() yields shape [3,4]; locate the
Tensor<float>(...) usage in the docs example and change it to use the
constructor or factory that accepts both data and shape (or an overload that
accepts a shape parameter) so the initial tensor truly has dimensions [1,3,1,4]
before calling Squeeze().
In `@docs/tutorials/audio/index.md`:
- Around line 96-106: The documentation sample redeclares "var result" three
times in the same scope for the different TranscribeAsync usages
(whisper.TranscribeAsync), which would not compile in C#; update the examples so
each is a standalone snippet or use unique variable names (e.g., resultFile,
resultStream, resultBytes) or show them in separate code blocks to make it clear
these are alternative approaches rather than consecutive lines in the same
scope.
- Around line 517-522: Update the Next Steps links so they point to existing
docs: replace the `/samples/audio/Transcription/` link with
`/samples/audio/SpeechRecognition/`, replace `/samples/audio/TTS/` with
`/samples/audio/TextToSpeech/`, remove the `/samples/audio/Diarization/` entry
(or add a new Diarization sample if you intend to create one), and verify the
`/api/AiDotNet.Audio/` API reference target—either correct it to the actual API
reference path or remove that bullet if no subdirectory exists; make these
changes in the Next Steps block that currently lists the four links.
In `@docs/tutorials/clustering/index.md`:
- Around line 369-374: Replace the absolute links that start with "/" with
relative paths from this document's location so they resolve under the GitHub
Pages baseurl; update "/samples/clustering/KMeans/",
"/samples/clustering/DBSCAN/", "/samples/clustering/CustomerSegmentation/" and
"/api/AiDotNet.Clustering/" to relative equivalents (for this file use
../../samples/clustering/KMeans/, ../../samples/clustering/DBSCAN/,
../../samples/clustering/CustomerSegmentation/, and
../../api/AiDotNet.Clustering/), and apply the same change pattern to other
tutorial files (nlp, audio, computer-vision, deployment, etc.) adjusting the
"../" depth as needed.
In `@index.md`:
- Around line 5-9: Replace the bold tagline line "**The comprehensive .NET
machine learning library**" with a proper markdown heading (for example "## The
comprehensive .NET machine learning library") so it is not formatted as bold
text; keep the main title "# AiDotNet" unchanged and ensure the tagline uses
heading syntax (## or ###) instead of **...** to satisfy MD036 and improve
document structure.
In `@src/AiDotNet.Playground/AiDotNet.Playground.csproj`:
- Around line 4-13: Create a repository-root global.json to pin the .NET SDK to
the exact preview that matches the Playground project package references (the
csproj TargetFramework net10.0 and PackageReference versions
10.0.0-preview.1.25120.3); set the "sdk" "version" to the matching preview SDK
(e.g., 10.0.100-preview.1.25120.3) so CI floating dotnet-version (10.0.x) and
local builds use the identical SDK and avoid mismatched previews.
In `@src/AiDotNet.Playground/Services/CodeExecutionService.cs`:
- Around line 84-90: The catch in CodeExecutionService currently returns an
ExecutionResult with "Falling back to simulation mode." but does not invoke any
fallback; either call and return the actual simulation fallback (e.g., call the
existing simulation helper such as SimulateExecution/SimulateExecutionAsync or
RunSimulation/RunSimulationAsync and return its ExecutionResult instead of the
current object) or remove the misleading "Falling back to simulation mode." text
and only report the exception; update the catch to use the Simulation method
name that exists in this class (or add one) and return its result, referencing
the catch's ex, ExecutionResult object, and the CodeExecutionService class.
In `@vercel.json`:
- Around line 17-26: The CORS headers in the "headers" block conflict because
Access-Control-Allow-Credentials is set to "true" while
Access-Control-Allow-Origin is "*"; either remove the
Access-Control-Allow-Credentials header if no credentials are needed, or replace
the wildcard origin with an explicit origin (or a list/logic to echo the
requesting origin) so that Access-Control-Allow-Origin matches the credentialed
requests; update the Access-Control-Allow-Credentials and
Access-Control-Allow-Origin entries accordingly in the headers array.
🧹 Nitpick comments (3)
src/AiDotNet.Playground/wwwroot/index.html (1)
35-45: Good error handling improvement.The manual Blazor startup with error handling is well-implemented. Using
autostart="false"withBlazor.start().catch()properly captures startup failures and displays actionable feedback to users.One minor defensive consideration: using
innerHTMLwitherror.messagecould pose an XSS risk if error messages ever contain untrusted content. While Blazor runtime errors are unlikely to include user-controlled data, encoding the message would be more defensive:🛡️ Optional: Encode error message for defense-in-depth
Blazor.start().catch(function(error) { console.error('Blazor startup error:', error); var errorUI = document.getElementById('blazor-error-ui'); - errorUI.innerHTML = 'Failed to load the playground. ' + - '<a href="" style="color: white; text-decoration: underline;" onclick="location.reload()">Reload</a>' + - '<br><small style="opacity: 0.7;">Error: ' + (error.message || 'Unknown error') + '</small>'; + var msg = (error.message || 'Unknown error').replace(/[<>&"']/g, function(c) { + return {'<':'<','>':'>','&':'&','"':'"',"'":'''}[c]; + }); + errorUI.innerHTML = 'Failed to load the playground. ' + + '<a href="" style="color: white; text-decoration: underline;" onclick="location.reload()">Reload</a>' + + '<br><small style="opacity: 0.7;">Error: ' + msg + '</small>'; errorUI.style.display = 'block'; });vercel.json (1)
11-15: Redundant rewrite rule.This rewrite maps
/api/:path*to/api/:path*, which doesn't change the path. Unless there's a specific reason (e.g., ensuring the route is processed by Vercel's routing layer), this rule can be removed.🧹 Proposed fix: Remove redundant rewrite
}, - "rewrites": [ - { - "source": "/api/:path*", - "destination": "/api/:path*" - } - ], "headers": [scripts/test-docs-local.sh (1)
149-149: Quote the variable for robustness.The
$PORTvariable should be quoted to prevent word splitting issues if the variable is empty or contains unexpected characters.🔧 Suggested fix
-docfx serve _site -p $PORT +docfx serve _site -p "$PORT"
- Rewrote ExampleService.cs with 17 examples using only AiModelBuilder facade - Updated TransformerExample.md to use ConfigureNlp() instead of internal classes - Updated TensorBasics.md to be a getting started guide with facade pattern - Updated NeuralNetworkTraining.md to use ConfigureNeuralNetwork() - Updated ClusteringExample.md to use ConfigureClustering() All examples now hide internal complexity and expose only: - AiModelBuilder<T, TInput, TOutput> - AiModelResult<T> - Configuration methods (ConfigureRegression, ConfigureClassification, etc.) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Fix all issues with AI agents
In `@docs/examples/ClusteringExample.md`:
- Around line 65-79: The example uses the variable `data` with
`AiModelBuilder<double, double[][], int[]>()` and its `BuildAsync(data)` call
but never defines it; add a minimal placeholder declaration (e.g., a simple
in-memory array or a `Load...` comment) named `data` above the shown snippet so
the sample compiles and readers know what input type is expected for
`AiModelBuilder` and `BuildAsync`; apply the same fix to the other snippet
ranges (lines 97-118) that reference `data`.
- Around line 113-118: The snippet that computes outlierIndices uses LINQ
methods (Select/Where/ToArray) but doesn't include the required namespace; add
"using System.Linq;" at the top of the example so the LINQ extension methods
used on result.ClusterLabels (and the outlierIndices declaration) resolve
correctly when copy/pasted.
In `@docs/examples/NeuralNetworkTraining.md`:
- Around line 35-41: The example calls the extension method probabilities.Max()
but doesn’t import LINQ; add the using directive for System.Linq at the top of
the example so probabilities.Max() resolves (or alternatively fully qualify the
call), ensuring the snippet that contains LoadTestImage(), result.Predict(...),
and result.PredictProbability(...) compiles as-is.
In `@docs/examples/TransformerExample.md`:
- Around line 142-143: The code snippets use LINQ extension methods like Zip and
ToArray (e.g., the line creating inputs: contexts.Zip(questions, (c, q) => $"{c}
[SEP] {q}").ToArray()), but the examples are missing the using directive; add
"using System.Linq;" to the C# example headers/imports so Zip, ToArray and other
LINQ helpers compile correctly (apply the same fix to the other snippet
mentioned that uses Zip/ToArray).
- Around line 210-236: The example calls BuildAsync(texts, labels) but never
defines labels; add a short placeholder declaration for labels (matching the
expected type used by AiModelBuilder, e.g., the string[] label array) near the
top of the snippet so the example is self-contained—locate the example block
around AiModelBuilder<double, string[], double[]> and insert a brief labels
declaration (and optionally a placeholder texts declaration if texts is not
already defined).
🧹 Nitpick comments (1)
src/AiDotNet.Playground/Services/ExampleService.cs (1)
341-341: Unicode minus sign may cause display inconsistency.The string uses a Unicode minus sign (U+2212
−) instead of the ASCII hyphen-minus (U+002D-). While this renders similarly in most fonts, it could cause confusion if users copy-paste or search for-1.Suggested fix
-Console.WriteLine(""Cluster assignments (−1 = noise):""); +Console.WriteLine(""Cluster assignments (-1 = noise):"");
- Fix docfx.json TargetFramework from net8.0 to net10.0 - Fix api/execute.ts using statement detection and runtime error handling - Add defense-in-depth security comment for dangerous patterns - Remove unused lint script from api/package.json - Upgrade @vercel/node from 3.0.0 to 5.5.24 - Fix audio tutorial variable redeclaration and broken links - Fix clustering tutorial absolute links to relative paths - Fix index.md tagline to use proper heading - Add global.json for SDK version pinning - Fix CodeExecutionService.cs to actually invoke simulation fallback - Fix vercel.json CORS configuration conflict - Add data placeholders and System.Linq to example docs Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@api/execute.ts`:
- Around line 72-89: The wrapper for top-level code discards added using
statements because it injects the original code variable instead of using
processedCode; update the !hasClass && !hasMain branch to build the Program.Main
wrapper around processedCode (or extract and prepend the accumulated usings from
processedCode) so any usings added earlier are preserved; reference
processedCode, code, hasClass, and hasMain when making the change.
In `@docs/examples/NeuralNetworkTraining.md`:
- Around line 218-253: The example calls BuildAsync(features, labels) but never
defines or references features/labels, so add a brief placeholder or reference
showing their expected shapes/types; update the NeuralNetworkTraining snippet to
declare or point to variables named features and labels (e.g., as double[][]
features and double[]/double[][] labels matching AiModelBuilder<double,
double[][], double[]> expectations) before calling new
AiModelBuilder...BuildAsync, or add a comment linking to an earlier section that
provides the dataset, ensuring the shapes match InputSize and NumClasses used in
ConfigureNeuralNetwork.
In `@index.md`:
- Around line 1-3: Change the front-matter key `_layout` to `layout` so the
static site generator recognizes the page layout; locate the YAML front-matter
at the top of the file (the block containing --- and the `_layout` key) and
rename `_layout` to `layout`, keeping the rest of the value intact.
♻️ Duplicate comments (1)
docs/tutorials/clustering/index.md (1)
369-374: Verify the relative link paths resolve correctly.The links use relative paths, which is correct for GitHub Pages with a baseurl. However, please verify these paths resolve to existing content after the documentation build, as the
samples/directory structure andapi/reference need to exist at these relative locations.
🧹 Nitpick comments (2)
docs/examples/ClusteringExample.md (1)
138-166: Adddataplaceholder to remaining code snippets for consistency.Several code snippets reference
dataortrainingDatawithout defining them (hierarchical clustering at line 155, GMM at line 185, assigning new data at line 219, cluster evaluation at line 251, feature importance at line 284). For copy-paste friendliness, consider adding minimal placeholder definitions similar to the DBSCAN example.Also applies to: 168-201, 203-234, 236-266, 268-292
src/AiDotNet.Playground/Services/CodeExecutionService.cs (1)
420-451: Consider usingRegexHelperfor consistency with the codebase.The codebase has a
RegexHelperclass (insrc/Helpers/RegexHelper.cs) that provides centralized regex creation with timeout handling. While the current implementation correctly applies timeouts, usingRegexHelper.Match()would maintain consistency with the rest of the codebase.♻️ Optional refactor using RegexHelper
+using AiDotNet.Helpers; + private static List<string> ParseConsoleOutput(string code) { var lines = new List<string>(); try { - // Parse Console.WriteLine statements with timeout to prevent ReDoS - var writeLinePattern = new Regex( - @"Console\.WriteLine\s*\(\s*(?:\$?""([^""]*)""|(\w+))\s*\)", - RegexOptions.Multiline, - RegexTimeout); - - var matches = writeLinePattern.Matches(code); + var pattern = @"Console\.WriteLine\s*\(\s*(?:\$?""([^""]*)""|(\w+))\s*\)"; + var regex = RegexHelper.Create(pattern, RegexOptions.Multiline); + var matches = regex.Matches(code);
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
- Fix using statement preservation in code wrapping (execute.ts) - Add features/labels placeholder in Training Configuration section - Fix _layout typo to layout in index.md frontmatter Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@index.md`:
- Around line 47-60: Update the example to use the correct generic types and
data-loading flow: replace AiModelBuilder<double, double[], double>() with
AiModelBuilder<double, Matrix<double>, Vector<double>> and use
.ConfigureDataLoader(new InMemoryDataLoader<double, Matrix<double>,
Vector<double>>(features, labels)) to supply training data, remove passing
features/labels into BuildAsync() so you call BuildAsync() with no args, and
ensure the Predict call uses the appropriate input type (e.g., a
Matrix/Vector/newSample matching Matrix<double>/Vector<double>) and the
RandomForestClassifier<double>, KFoldCrossValidator<double>,
ConfigurePreprocessing(), ConfigureDataLoader(), and BuildAsync() symbols are
updated accordingly.
🧹 Nitpick comments (4)
api/execute.ts (4)
65-72: Using statement regex has limited pattern coverage.The regex
^using\s+[\w.]+;\s*$won't match:
- Static usings:
using static System.Math;- Alias usings:
using Alias = System.IO;- Usings with trailing comments:
using System; // neededFor a playground, this is likely acceptable, but users might be confused if their static/alias usings are duplicated or lost.
🔧 More comprehensive regex (optional)
- const usingRegex = /^using\s+[\w.]+;\s*$/gm; + // Matches: using X; | using static X; | using Alias = X; + const usingRegex = /^using\s+(?:static\s+)?(?:[\w.]+\s*=\s*)?[\w.]+;\s*(?:\/\/.*)?$/gm;
130-136: Consider adding a fetch timeout.The
fetchcall has no timeout. If Piston becomes unresponsive, the request could hang until Vercel's 30-second function timeout. An explicitAbortControllertimeout ensures faster failure and cleaner error messages.🔧 Add fetch timeout
+ const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 20000); // 20s timeout + const response = await fetch(`${PISTON_API}/execute`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), + signal: controller.signal, }); + + clearTimeout(timeout);You'll also want to handle
AbortErrorin the catch block:} catch (error) { if (error instanceof Error && error.name === 'AbortError') { return { success: false, error: 'Execution timed out. The code took too long to compile or run.', executionTime: Date.now() - startTime, }; } // ... existing handling }
184-204: Rate limit map grows unbounded; consider periodic cleanup.The
rateLimitMapnever removes expired entries. While Vercel functions are ephemeral, a long-running warm instance under sustained traffic could accumulate stale IP records. Also, in-memory rate limiting doesn't persist across function instances, so determined users could bypass limits.For a playground with fallback simulation mode, this is likely acceptable. If stricter enforcement is needed later, consider Vercel KV or Upstash Redis.
🔧 Optional: Add lazy cleanup
function checkRateLimit(ip: string): boolean { const now = Date.now(); const record = rateLimitMap.get(ip); + // Lazy cleanup: remove expired entries occasionally + if (rateLimitMap.size > 1000) { + for (const [key, val] of rateLimitMap) { + if (now > val.resetTime) rateLimitMap.delete(key); + } + } + if (!record || now > record.resetTime) {
241-241: Unusedlanguagevariable.The
languageproperty is destructured from the request body but never used. Either remove it or implement multi-language support if planned.🔧 Remove unused destructuring
- const { code, language } = req.body as ExecuteRequest; + const { code } = req.body as ExecuteRequest;Or keep it if you plan to support multiple languages and validate against
language === 'csharp'.
- Use Matrix<double>/Vector<double> instead of double[] - Add ConfigureDataLoader() for training data - Remove parameters from BuildAsync() call Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
|


Summary
Changes
Playground Improvements
Documentation Fixes
index.mdto fix homepage showing raw JSONdocs/examples/index.mdto fix broken /examples linkReal Code Execution (Vercel API)
api/execute.ts) using Piston API for C# executionPost-Merge Steps
To enable real code execution, deploy the Vercel API:
cd api vercel login vercel deploy --prodIf the deployed URL differs from
aidotnet-playground-api.vercel.app, updateCodeExecutionService.cs.Test plan
🤖 Generated with Claude Code