@innovatorved/code-lab 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +114 -0
- package/LICENSE +21 -0
- package/README.md +156 -0
- package/dist/code-lab.css +4100 -0
- package/dist/code-lab.d.ts +348 -0
- package/dist/code-lab.esm.js +21954 -0
- package/dist/code-lab.js +21933 -0
- package/dist/extensions/guided-lab.d.ts +13 -0
- package/dist/extensions/guided-lab.esm.js +4218 -0
- package/dist/extensions/guided-lab.js +4236 -0
- package/dist/index.d.ts +11 -0
- package/dist/preview-sw.js +149 -0
- package/dist/runtime.d.ts +48 -0
- package/dist/runtime.esm.js +7510 -0
- package/dist/runtime.js +7491 -0
- package/dist/sample.html +304 -0
- package/dist/schemas.d.ts +514 -0
- package/dist/shell.d.ts +66 -0
- package/dist/shell.esm.js +6405 -0
- package/dist/shell.js +6384 -0
- package/dist/terminal.d.ts +102 -0
- package/dist/terminal.esm.js +1083 -0
- package/dist/terminal.js +1072 -0
- package/dist/workbench.d.ts +1 -0
- package/package.json +98 -0
- package/src/code-lab.css +4100 -0
- package/src/extensions/guided-lab.ts +54 -0
- package/src/index.ts +28 -0
- package/src/preview-sw.js +149 -0
- package/src/runtime.js +7465 -0
- package/src/runtime.ts +7512 -0
- package/src/sample.html +304 -0
- package/src/schemas.ts +177 -0
- package/src/shell.js +6358 -0
- package/src/shell.ts +6456 -0
- package/src/terminal.js +1046 -0
- package/src/terminal.ts +1097 -0
- package/src/workbench.js +6987 -0
- package/src/workbench.ts +6988 -0
package/ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# `@innovatorved/code-lab` Architecture (v1.3.2)
|
|
2
|
+
|
|
3
|
+
`@innovatorved/code-lab` is an embeddable, zero-dependency, browser-native Node.js v22 + Bun v1.1 IDE, POSIX shell, PTY terminal, and virtual execution sandbox.
|
|
4
|
+
|
|
5
|
+
It is designed around two strictly decoupled layers that can be used together (`dist/code-lab.js`) or independently (`dist/runtime.js`, `dist/shell.js`, `dist/terminal.js` for headless or modular execution):
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
9
|
+
│ Host Application / Web Page │
|
|
10
|
+
│ (<code-lab> Web Component | CodeLab.mount() | Plugin API) │
|
|
11
|
+
└──────────────────────────────────────┬──────────────────────────────────────┘
|
|
12
|
+
│
|
|
13
|
+
┌──────────────────────────────────────▼──────────────────────────────────────┐
|
|
14
|
+
│ UI Layer: CodeLabWorkbench (src/workbench.js) │
|
|
15
|
+
│ ┌────────────────────┐ ┌─────────────────────────┐ ┌──────────────────┐ │
|
|
16
|
+
│ │ Guided Walkthrough │ │ Multi-File Explorer & │ │ Monaco / Native │ │
|
|
17
|
+
│ │ & Step Verification│ │ Solution Diff Viewer │ │ Code Editor │ │
|
|
18
|
+
│ └────────────────────┘ └─────────────────────────┘ └──────────────────┘ │
|
|
19
|
+
│ ┌────────────────────────────────────────────────────────────────────────┐ │
|
|
20
|
+
│ │ 5-Tab Bottom Drawer: │ │
|
|
21
|
+
│ │ [Test Suite] [Terminal & REPL] [Ports + HTTP Client] [Network] [VFS] │ │
|
|
22
|
+
│ └───────────────────┬────────────────────────────────────┬───────────────┘ │
|
|
23
|
+
└──────────────────────┼────────────────────────────────────┼─────────────────┘
|
|
24
|
+
│ │
|
|
25
|
+
┌──────────────────────▼────────────────┐ ┌────────────────▼─────────────────┐
|
|
26
|
+
│ POSIX Shell & PTY (src/shell.js, │ │ Virtual Runtime Engine │
|
|
27
|
+
│ src/terminal.js) │ │ (src/runtime.js) │
|
|
28
|
+
│ • Recursive-descent AST parser │ │ • Web Worker pool + preemption │
|
|
29
|
+
│ • Pipes (|), redirects (>, >>, 2>&1) │ │ • In-memory POSIX VFS (/tmp, …) │
|
|
30
|
+
│ • 40+ POSIX coreutils + git + jq │ │ • Node.js v22 (24 built-in mods)│
|
|
31
|
+
│ • Interactive PTY ANSI/256-color │ │ • Bun v1.1 (serve, sqlite, test)│
|
|
32
|
+
│ • Job table (ps, jobs, fg, bg, kill) │ │ • VirtualPortTable (127.0.0.1) │
|
|
33
|
+
└───────────────────────────────────────┘ └──────────────────────────────────┘
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 1. Virtual Runtime Engine (`src/runtime.js`)
|
|
39
|
+
|
|
40
|
+
`CodeLabRuntime` is a self-contained browser execution engine that requires **zero server infrastructure** and **zero COOP/COEP headers**.
|
|
41
|
+
|
|
42
|
+
### 1.1 Web Worker Isolation & Preemption
|
|
43
|
+
- **Warm Worker Pool**: `executeInWorker(options)` maintains a warm `Blob`-backed Web Worker for sub-millisecond cold starts and spawns isolated workers for concurrent runs.
|
|
44
|
+
- **Hard Preemption**: Infinite `while(true)` loops or hung timers are terminated cleanly via `worker.terminate()` after `timeoutMs` (default `15000ms`) or immediately when `cancelWorkerExecution()` is invoked.
|
|
45
|
+
- **Automatic Resource Cleanup**: All timers (`setTimeout`, `setInterval`, `setImmediate`), virtual sockets, and pending test promises are tracked in a `resourceTracker` and cleaned up on exit.
|
|
46
|
+
|
|
47
|
+
### 1.2 In-Memory POSIX Virtual File System (`createVirtualFs`)
|
|
48
|
+
- Hierarchical inode tree pre-populated with `/workspace`, `/tmp`, `/etc`, `/home`, and `/home/user`.
|
|
49
|
+
- Full `node:fs` and `node:fs/promises` APIs: `readFileSync`, `writeFileSync`, `appendFileSync`, `mkdirSync`, `readdirSync`, `statSync`, `unlinkSync`, `renameSync`, `copyFileSync`, `cpSync`, `symlinkSync`, `readlinkSync`, `openSync`, `writeSync`, `readSync`, `fsyncSync`, `closeSync`, `createReadStream`, and `createWriteStream`.
|
|
50
|
+
- Real-time byte size, UTF-8 preview, and 16-byte hex dump snapshots (`vfs.getSnapshot()`) for inspecting binary WAL logs, SSTables, and SQLite tables.
|
|
51
|
+
|
|
52
|
+
### 1.3 Node.js v22 & Bun v1.1 Shims
|
|
53
|
+
- **24 Built-in Node.js Modules**: `fs`, `fs/promises`, `path`, `crypto`, `events`, `stream`, `stream/promises`, `http`, `https`, `net`, `zlib`, `util`, `assert`, `assert/strict`, `buffer`, `url`, `querystring`, `timers`, `timers/promises`, `perf_hooks`, `string_decoder`, `dns`, `os`, `child_process`, `worker_threads`, `vm`, `readline`, `sqlite`, `process`, and `node:test`.
|
|
54
|
+
- **Bun v1.1 API (`Bun`, `'bun'`, `'bun:test'`, `'bun:sqlite'`)**:
|
|
55
|
+
- `Bun.serve({ port, fetch, error })` binds directly to the shared `VirtualPortTable`.
|
|
56
|
+
- `Bun.file(path)` and `Bun.write(dest, data)` read and write directly to the POSIX VFS.
|
|
57
|
+
- `bun:sqlite` (`new Database(':memory:' | '/workspace/app.db')`) provides an in-memory relational SQL engine supporting `CREATE TABLE`, `DROP TABLE`, `INSERT`, `UPDATE`, `DELETE`, `SELECT`, `WHERE`, `GROUP BY`, `ORDER BY`, `LIMIT`, `OFFSET`, `COUNT/SUM/AVG/MIN/MAX`, parameterized queries, and `db.transaction(fn)`.
|
|
58
|
+
- `bun:test` provides Jest-compatible `expect()` matchers (`toBe`, `toEqual`, `toContain`, `toThrow`, `toHaveLength`, etc.) plus `describe`, `test`, `it`, `beforeAll`, `afterAll`, `beforeEach`, `afterEach`, and `mock()`.
|
|
59
|
+
|
|
60
|
+
### 1.4 Virtual Port Table & Loopback Networking (`createVirtualPortTable`)
|
|
61
|
+
- `VirtualPortTable` coordinates active listeners across `http.createServer().listen(port)`, `net.createServer().listen(port)`, and `Bun.serve({ port })`.
|
|
62
|
+
- Loopback requests from `fetch('http://localhost:PORT/...')`, `http.request()`, `curl`, and the Workbench's Mini HTTP Client are routed in-memory with zero network latency and recorded in the HTTP/TCP trace log.
|
|
63
|
+
- Emits `listen` / `close` lifecycle events via `on(event, fn)`, `off(event, fn)`, and `emit(event, ...args)`, letting the Workbench react instantly when a script binds or releases a port.
|
|
64
|
+
- Exposes `unregister(port)` as an alias of `unregisterServer(port)` for the drawer "Stop" control.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 2. POSIX Shell & Coreutils (`src/shell.js`)
|
|
69
|
+
|
|
70
|
+
`createPosixShell` implements a complete POSIX shell interpreter inside the browser:
|
|
71
|
+
- **Lexer & Recursive-Descent AST Parser**: Supports single/double quotes, escape sequences, pipelines (`cmd1 | cmd2 | cmd3`), logical operators (`&&`, `||`, `;`), background execution (`&`), I/O redirection (`>`, `>>`, `<`, `<<<`, `2>`, `2>&1`, `&>`), environment variable expansion (`$VAR`, `${VAR:-default}`, `${VAR:=default}`, `${#VAR}`, `$?`, `$$`), command substitution (`$(...)`), arithmetic expansion (`$((...))`), brace expansion (`{a,b,c}`, `{1..5}`), and globbing (`*`, `?`, `**`).
|
|
72
|
+
- **40+ Built-in Coreutils**:
|
|
73
|
+
- File & Directory: `ls`, `cat`, `head`, `tail`, `wc`, `cp`, `mv`, `rm`, `mkdir`, `rmdir`, `touch`, `ln`, `pwd`, `cd`, `find`, `tree`, `stat`, `file`, `du`, `df`, `chmod`, `chown`, `mktemp`, `basename`, `dirname`, `realpath`.
|
|
74
|
+
- Text & Data Processing: `grep`, `sed`, `awk`, `sort`, `uniq`, `cut`, `tr`, `tee`, `xargs`, `diff`, `jq`, `xxd`, `hexdump`, `base64`, `md5sum`, `sha256sum`.
|
|
75
|
+
- Networking, Process & Archive: `curl`, `nc`, `ping`, `dig`, `nslookup`, `lsof`, `netstat`, `ss`, `ps`, `top`, `kill`, `jobs`, `fg`, `bg`, `tar`, `gzip`, `gunzip`.
|
|
76
|
+
- Developer Toolchains: `node`, `bun`, `npm`, `npx`, `tsc`, `git` (`init`, `status`, `add`, `commit`, `log`, `diff`, `branch`, `checkout`).
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 3. PTY Terminal Engine (`src/terminal.js`)
|
|
81
|
+
|
|
82
|
+
`PTYTerminalEngine` provides an interactive terminal UI and ANSI/VT100 escape sequence parser:
|
|
83
|
+
- Supports SGR 16-color, 256-color (`38;5;n`), and 24-bit TrueColor (`38;2;r;g;b`) foreground/background attributes, bold, dim, italic, underline, and partial SGR resets (`22`, `23`, `24`, `39`, `49`).
|
|
84
|
+
- Supports readline shortcuts (`Ctrl+A`, `Ctrl+E`, `Ctrl+U`, `Ctrl+K`, `Ctrl+L`, `Ctrl+C`, `Ctrl+D`, `Ctrl+R` reverse-i-search), command history (`ArrowUp`/`ArrowDown`), interactive `readLine()` stdin prompts, and context-aware `Tab` autocompletion for commands and VFS file paths.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## 4. IDE Workbench (`src/workbench.js`)
|
|
89
|
+
|
|
90
|
+
`CodeLabWorkbench` and `<code-lab>` provide the full visual IDE experience:
|
|
91
|
+
- **Guided Challenge & Reference Sandbox Modes**: Step-by-step verification (`Verify Step`), AST/symbol jump-to-TODO, hints, and unified/split diff comparison against starter or solution files.
|
|
92
|
+
- **Monaco Editor + Zero-Dependency Fallback**: Automatic TypeScript/JavaScript IntelliSense with full ambient declarations for Node.js v22 and Bun v1.1 (`NODE_AMBIENT_DTS`).
|
|
93
|
+
- **6-Tab Bottom Drawer**:
|
|
94
|
+
1. **Test Suite** (`tests`): Structured pass/fail assertions, duration badges, and failure stack traces.
|
|
95
|
+
2. **Terminal & REPL** (`terminal`): Interactive POSIX shell (`sh`) and Node.js REPL (`node`).
|
|
96
|
+
3. **Ports** (`ports`): Live listener table (`VirtualPortTable`) + interactive **Mini HTTP Client** (Method, URL, Headers, Body, and Preview/Raw/Headers response viewer), with a **Preview** action per listening port.
|
|
97
|
+
4. **Web Preview** (`preview`): Embedded browser chrome (URL bar, back/forward, reload, desktop/tablet/mobile frame modes) rendering virtual HTTP/Bun servers in an iframe, plus a **Pop Out** button that opens `/__preview/:port/*` in a dedicated tab.
|
|
98
|
+
5. **Network** (`network`): HTTP & TCP loopback trace waterfall with status/method/latency breakdown and detail inspector.
|
|
99
|
+
6. **Virtual Disk & HTTP** (`inspector`): In-memory POSIX VFS file/inode browser with UTF-8 and 16-byte hex dump previews.
|
|
100
|
+
- **Port Toast Notifications**: When a virtual server binds a port, a floating toast offers an **Open Web Preview** action (auto-dismissing after 8s).
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 5. Build & Distribution Pipeline (`tools/bundle.js`)
|
|
105
|
+
|
|
106
|
+
Running `bun run build` (`bun run tools/bundle.js`) produces:
|
|
107
|
+
- `dist/code-lab.js` & `dist/code-lab.esm.js` (complete runtime + shell + terminal + workbench bundle)
|
|
108
|
+
- `dist/runtime.js` & `dist/runtime.esm.js` (headless virtual runtime)
|
|
109
|
+
- `dist/shell.js` & `dist/shell.esm.js` (standalone POSIX shell & coreutils)
|
|
110
|
+
- `dist/terminal.js` & `dist/terminal.esm.js` (standalone PTY terminal engine)
|
|
111
|
+
- `dist/code-lab.css` (standalone dark/light CSS variables & workbench styles)
|
|
112
|
+
- `dist/preview-sw.js` (Web Preview virtual-loopback Service Worker for pop-out tabs; also copied to `examples/cloud-ide/public/preview-sw.js` for root scope)
|
|
113
|
+
- `dist/code-lab.d.ts` (TypeScript definitions for `CodeLab`, `CodeLabWorkbench`, `CodeLabElement`, `CodeLabRuntime`, `CodeLabShell`, and `CodeLabTerminal`)
|
|
114
|
+
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 Ved Gupta
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# @innovatorved/code-lab
|
|
2
|
+
|
|
3
|
+
> **Note:** This project is in active development. APIs and sandbox internals are stable for production use.
|
|
4
|
+
|
|
5
|
+
Browser-native code IDE workbench, modular guided challenge engine (`@innovatorved/code-lab/extensions/guided-lab`), POSIX shell with 55+ UNIX coreutils, public GitHub repository cloner (`git clone`), and Web Worker execution runtime for **Node.js** and **Bun** (JavaScript & TypeScript) with Zod type safety and zero backend server dependencies.
|
|
6
|
+
|
|
7
|
+
- **Live Cloud IDE & GitHub Repo Explorer**: **[https://code-lab-3dr.pages.dev](https://code-lab-3dr.pages.dev)** — Enter any public GitHub repository (`owner/repo` or URL) to clone and run it directly in your browser.
|
|
8
|
+
- **Built for**: [System Design In Depth](https://system-design-in-depth.vedgupta.in)
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Features
|
|
13
|
+
|
|
14
|
+
- **Modular Architecture (`v2.0.0`)**: Pure, general-purpose browser IDE (`code-lab`) by default with File Explorer, Monaco Editor, and PTY Terminal. Curriculum features (Guided Steps, Mode Switcher, and JS/TS switcher) are encapsulated in an opt-in modular extension (`@innovatorved/code-lab/extensions/guided-lab`).
|
|
15
|
+
- **End-to-End TypeScript & Zod Type Safety**: Written in TypeScript with strict runtime schemas and inferred types (`z.infer<typeof ...>`) for workbench options, guided labs, runtime execution, and git cloning.
|
|
16
|
+
- **Public GitHub Repository Cloning (`git clone`)**: Clone any public GitHub repository (`git clone https://github.com/owner/repo` or `git clone owner/repo --branch main` in the terminal, or `await lab.cloneRepo('owner/repo')` via the SDK) directly into `/workspace` with zero authentication required (automatic GitHub Trees API + jsDelivr unlimited fallback).
|
|
17
|
+
- **Interactive IDE Workbench**: Multi-file Monaco editor, collapsible hierarchical file tree with drag-and-drop, decoupled editor tabs, Command Palette (`Cmd+Shift+P`), Quick Open (`Cmd+P`), breadcrumbs, and line-by-line solution diff viewer.
|
|
18
|
+
- **Interactive PTY Terminal**: Inline prompt (`codelab:/workspace$ `), cursor navigation, history (`Up`/`Down`), `Ctrl+R` reverse-i-search, `Tab` auto-completion, `Ctrl+C` interrupt, `Ctrl+L` clear, and 256-color / TrueColor ANSI support.
|
|
19
|
+
- **POSIX Shell & 55+ Coreutils**: Full pure-JS AST interpreter supporting pipelines (`|`), redirects (`>`, `>>`, `2>&1`, `<<<`, `<<EOF`), control flow (`if`/`for`/`while`/`case`), functions, arithmetic `$((...))`, brace expansion `{1..5}`, and 55+ UNIX commands (`git`, `ls`, `cat`, `grep`, `find`, `sed`, `awk`, `jq`, `tar`, `curl`, `nc`, `lsof`, `tsc`, etc.).
|
|
20
|
+
- **Dual Runtime Engines (Node.js v22 & Bun v1.1)**:
|
|
21
|
+
- **Node.js**: 28 built-in modules (`fs`, `fs/promises`, `http`, `https`, `net`, `stream`, `events`, `crypto`, `zlib`, `vm`, `worker_threads`, `readline`, `node:sqlite`, `node:test`, `assert`).
|
|
22
|
+
- **Bun**: Native `.ts` transpilation, `Bun.serve()`, `Bun.file()`, `Bun.write()`, `Bun.spawn()`, `Bun.password`, `Bun.hash()`, `bun:test`, and VFS-backed `bun:sqlite`.
|
|
23
|
+
- **Persistent HTTP/TCP Servers & Dual Web Preview**: Start background servers (`node server.js &` or `bun run server.ts &`), query them with `curl http://localhost:3000` or global `fetch()`, and view live responses in the Ports table, an embedded **Web Preview** tab (URL bar, back/forward, device frames), or a popped-out browser tab backed by a virtual-loopback Service Worker (`/__preview/:port/*`).
|
|
24
|
+
- **GitHub-Flavored Markdown Engine**: Zero-dependency GFM renderer (tables with column alignment, `[!NOTE]` / `[!TIP]` / `[!IMPORTANT]` / `[!WARNING]` / `[!CAUTION]` callout alerts, task-list checkboxes, and syntax-highlighted code blocks with one-click copy) powering the Guide tab, hints, and `.md` file previews.
|
|
25
|
+
- **NPM & Bun Package Management**: `npm i <pkg>` and `bun add <pkg>` resolve dependencies from npm / esm.sh into virtual `/workspace/node_modules/<pkg>` and update `package.json`.
|
|
26
|
+
- **Guided Step-by-Step Challenges**: TutorialKit / Codedamn-style curriculum extension with targeted instructions, hints, automated test verification per step, and reference solutions.
|
|
27
|
+
- **Headless Runtime**: Programmatic execution engine (`@innovatorved/code-lab/runtime`) for grading, testing, or automated evaluation with zero UI.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
bun add @innovatorved/code-lab
|
|
35
|
+
# or
|
|
36
|
+
npm install @innovatorved/code-lab
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Or load from a static script tag via CDN:
|
|
40
|
+
|
|
41
|
+
```html
|
|
42
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@innovatorved/code-lab/dist/code-lab.css" />
|
|
43
|
+
<script src="https://cdn.jsdelivr.net/npm/@innovatorved/code-lab/dist/code-lab.js"></script>
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
### 1. Mount Workbench in DOM
|
|
51
|
+
|
|
52
|
+
```js
|
|
53
|
+
import CodeLab from '@innovatorved/code-lab';
|
|
54
|
+
import '@innovatorved/code-lab/code-lab.css';
|
|
55
|
+
|
|
56
|
+
const lab = CodeLab.mount('#editor', {
|
|
57
|
+
id: 'rate-limiter',
|
|
58
|
+
title: 'Token Bucket Rate Limiter',
|
|
59
|
+
mode: 'guided',
|
|
60
|
+
language: 'js',
|
|
61
|
+
entry: 'demo.js',
|
|
62
|
+
testEntry: 'test.js',
|
|
63
|
+
starterFiles: {
|
|
64
|
+
'limiter.js': 'class TokenBucket {\n allow() { return false; }\n}\nmodule.exports = { TokenBucket };\n',
|
|
65
|
+
'demo.js': 'const { TokenBucket } = require("./limiter");\nconsole.log(new TokenBucket().allow());\n',
|
|
66
|
+
'test.js': 'const { test } = require("node:test");\nconst assert = require("node:assert/strict");\nconst { TokenBucket } = require("./limiter");\n\ntest("allows request", () => {\n assert.equal(new TokenBucket().allow(), true);\n});\n'
|
|
67
|
+
},
|
|
68
|
+
steps: [
|
|
69
|
+
{
|
|
70
|
+
id: 'step-1',
|
|
71
|
+
title: 'Allow requests within capacity',
|
|
72
|
+
targetFile: 'limiter.js',
|
|
73
|
+
targetSymbol: 'allow',
|
|
74
|
+
instructions: 'Return `true` when tokens are available.',
|
|
75
|
+
testNames: ['allows request']
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 2. `<code-lab>` Custom Element
|
|
82
|
+
|
|
83
|
+
```html
|
|
84
|
+
<code-lab mode="sandbox" language="ts" style="height: 600px;">
|
|
85
|
+
<script type="application/json">
|
|
86
|
+
{
|
|
87
|
+
"id": "demo-lab",
|
|
88
|
+
"title": "Bun HTTP Demo",
|
|
89
|
+
"entry": "server.ts",
|
|
90
|
+
"files": {
|
|
91
|
+
"server.ts": "Bun.serve({ port: 3000, fetch: () => Response.json({ ok: true }) }); console.log('Listening on :3000');"
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
</script>
|
|
95
|
+
</code-lab>
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### 3. Headless Runtime (No UI)
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
import { executeInWorker } from '@innovatorved/code-lab/runtime';
|
|
102
|
+
|
|
103
|
+
const res = await executeInWorker({
|
|
104
|
+
mode: 'test',
|
|
105
|
+
entry: 'test.js',
|
|
106
|
+
files: {
|
|
107
|
+
'math.js': 'module.exports = { add: (a, b) => a + b };',
|
|
108
|
+
'test.js': 'const { test } = require("node:test");\nconst assert = require("node:assert/strict");\nconst { add } = require("./math");\ntest("adds numbers", () => assert.equal(add(2, 3), 5));'
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
console.log(res.ok, res.testResults);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Documentation
|
|
118
|
+
|
|
119
|
+
Complete documentation is published on the [GitHub Wiki](https://github.com/innovatorved/code-lab/wiki):
|
|
120
|
+
|
|
121
|
+
- **[Quick Start](https://github.com/innovatorved/code-lab/wiki/Quick-Start)**: Setup, CDN, and quick examples.
|
|
122
|
+
- **[Integration Guide](https://github.com/innovatorved/code-lab/wiki/Integration-Guide)**: Embedding in React, Next.js, Vite, and HTML.
|
|
123
|
+
- **[Workbench Configuration](https://github.com/innovatorved/code-lab/wiki/Workbench-Configuration)**: Complete reference of options, methods, events, and shortcuts.
|
|
124
|
+
- **[POSIX Shell & Coreutils](https://github.com/innovatorved/code-lab/wiki/POSIX-Shell-and-Coreutils)**: Pipelines, redirects, background jobs, and 40+ UNIX commands.
|
|
125
|
+
- **[Runtime APIs (Node & Bun)](https://github.com/innovatorved/code-lab/wiki/Runtime-APIs)**: 24 Node.js built-ins, Bun APIs, `bun:test`, `bun:sqlite`, and npm install.
|
|
126
|
+
- **[HTTP Servers & Networking](https://github.com/innovatorved/code-lab/wiki/HTTP-Servers-and-Networking)**: Virtual port table, background servers, `curl`, and Port Preview.
|
|
127
|
+
- **[Headless Runtime](https://github.com/innovatorved/code-lab/wiki/Headless-Runtime)**: Run code and tests programmatically with zero UI.
|
|
128
|
+
- **[Authoring Guided Labs](https://github.com/innovatorved/code-lab/wiki/Authoring-Guided-Labs)**: Schema and invariants for creating interactive coding challenges.
|
|
129
|
+
- **[Plugin System & Custom Extensions](https://github.com/innovatorved/code-lab/wiki/Plugin-System)**: Extend CodeLab with `.use(plugin)` and `.on()` event hooks.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## Local Development & Testing
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
# Install dependencies with Bun
|
|
137
|
+
bun install
|
|
138
|
+
|
|
139
|
+
# Rebuild all distribution bundles
|
|
140
|
+
bun run build
|
|
141
|
+
|
|
142
|
+
# Run the complete test suite
|
|
143
|
+
bun run test:all
|
|
144
|
+
bun run tests/test-all-builds.js # 15/15 builds & 226 unit tests
|
|
145
|
+
bun run tests/test-runtime-advanced.js # Advanced runtime, VFS, HTTP/TCP
|
|
146
|
+
bun run tests/test-option1-shell-bun-http.js # Shell AST, Bun runtime, curl, ports
|
|
147
|
+
bun run tests/test-coreutils-adversarial.js # Adversarial stress tests on 40+ coreutils
|
|
148
|
+
bun run tests/test-stress-shell.js # Deep pipelines, redirections, large stdout
|
|
149
|
+
bun run tests/test-workbench-ui.js # Workbench tabs, explorer, shortcuts
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT © [Ved Gupta](https://vedgupta.in)
|