@innovatorved/code-lab 0.1.7 → 0.1.8

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 CHANGED
@@ -1,6 +1,6 @@
1
- # `@innovatorved/code-lab` Architecture (v0.1.7)
1
+ # `@innovatorved/code-lab` Architecture (v0.1.8)
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.
3
+ `@innovatorved/code-lab` is an embeddable, browser-native Node.js v22 + Bun v1.1 IDE, POSIX shell, PTY terminal, and virtual execution sandbox with self-contained browser bundles (zero runtime dependencies in `dist/*`; Zod schemas available under `@innovatorved/code-lab/schemas`).
4
4
 
5
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
6
 
@@ -11,23 +11,23 @@ It is designed around two strictly decoupled layers that can be used together (`
11
11
  └──────────────────────────────────────┬──────────────────────────────────────┘
12
12
  │
13
13
  ┌──────────────────────────────────────▼──────────────────────────────────────┐
14
- │ UI Layer: CodeLabWorkbench (src/workbench.js) │
14
+ │ UI Layer: CodeLabWorkbench (src/workbench.ts) │
15
15
  │ ┌────────────────────┐ ┌─────────────────────────┐ ┌──────────────────┐ │
16
16
  │ │ Guided Walkthrough │ │ Multi-File Explorer & │ │ Monaco / Native │ │
17
17
  │ │ & Step Verification│ │ Solution Diff Viewer │ │ Code Editor │ │
18
18
  │ └────────────────────┘ └─────────────────────────┘ └──────────────────┘ │
19
19
  │ ┌────────────────────────────────────────────────────────────────────────┐ │
20
- │ │ 5-Tab Bottom Drawer: │ │
21
- │ │ [Test Suite] [Terminal & REPL] [Ports + HTTP Client] [Network] [VFS] │ │
20
+ │ │ 6-Tab Bottom Drawer: │ │
21
+ │ │ [Test Suite] [Terminal] [Ports] [Web Preview] [Network] [VFS] │ │
22
22
  │ └───────────────────┬────────────────────────────────────┬───────────────┘ │
23
23
  └──────────────────────┼────────────────────────────────────┼─────────────────┘
24
24
  │ │
25
25
  ┌──────────────────────▼────────────────┐ ┌────────────────▼─────────────────┐
26
- │ POSIX Shell & PTY (src/shell.js, │ │ Virtual Runtime Engine │
27
- │ src/terminal.js) │ │ (src/runtime.js) │
26
+ │ POSIX Shell & PTY (src/shell.ts, │ │ Virtual Runtime Engine │
27
+ │ src/terminal.ts) │ │ (src/runtime.ts) │
28
28
  │ • Recursive-descent AST parser │ │ • Web Worker pool + preemption │
29
29
  │ • Pipes (|), redirects (>, >>, 2>&1) │ │ • In-memory POSIX VFS (/tmp, …) │
30
- │ • 40+ POSIX coreutils + git + jq │ │ • Node.js v22 (24 built-in mods)│
30
+ │ • 58 POSIX coreutils + git + jq │ │ • Node.js v22 (50 built-in mods)│
31
31
  │ • Interactive PTY ANSI/256-color │ │ • Bun v1.1 (serve, sqlite, test)│
32
32
  │ • Job table (ps, jobs, fg, bg, kill) │ │ • VirtualPortTable (127.0.0.1) │
33
33
  └───────────────────────────────────────┘ └──────────────────────────────────┘
@@ -35,7 +35,7 @@ It is designed around two strictly decoupled layers that can be used together (`
35
35
 
36
36
  ---
37
37
 
38
- ## 1. Virtual Runtime Engine (`src/runtime.js`)
38
+ ## 1. Virtual Runtime Engine (`src/runtime.ts`)
39
39
 
40
40
  `CodeLabRuntime` is a self-contained browser execution engine that requires **zero server infrastructure** and **zero COOP/COEP headers**.
41
41
 
@@ -50,7 +50,7 @@ It is designed around two strictly decoupled layers that can be used together (`
50
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
51
 
52
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`.
53
+ - **50 Built-in Node.js Modules**: `fs`, `fs/promises`, `path`, `crypto`, `events`, `stream`, `stream/promises`, `stream/web`, `stream/consumers`, `http`, `https`, `http2`, `net`, `tls`, `dgram`, `zlib`, `util`, `util/types`, `assert`, `assert/strict`, `buffer`, `url`, `querystring`, `timers`, `timers/promises`, `perf_hooks`, `string_decoder`, `dns`, `dns/promises`, `os`, `child_process`, `worker_threads`, `vm`, `readline`, `readline/promises`, `async_hooks`, `diagnostics_channel`, `v8`, `domain`, `cluster`, `repl`, `inspector`, `trace_events`, `wasi`, `tty`, `constants`, `console`, `module`, `process`, and `node:test`.
54
54
  - **Bun v1.1 API (`Bun`, `'bun'`, `'bun:test'`, `'bun:sqlite'`)**:
55
55
  - `Bun.serve({ port, fetch, error })` binds directly to the shared `VirtualPortTable`.
56
56
  - `Bun.file(path)` and `Bun.write(dest, data)` read and write directly to the POSIX VFS.
@@ -65,20 +65,20 @@ It is designed around two strictly decoupled layers that can be used together (`
65
65
 
66
66
  ---
67
67
 
68
- ## 2. POSIX Shell & Coreutils (`src/shell.js`)
68
+ ## 2. POSIX Shell & Coreutils (`src/shell.ts`)
69
69
 
70
70
  `createPosixShell` implements a complete POSIX shell interpreter inside the browser:
71
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**:
72
+ - **58 Built-in Coreutils**:
73
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
74
  - Text & Data Processing: `grep`, `sed`, `awk`, `sort`, `uniq`, `cut`, `tr`, `tee`, `xargs`, `diff`, `jq`, `xxd`, `hexdump`, `base64`, `md5sum`, `sha256sum`.
75
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`, `pnpm`, `npx`, `bunx`, `tsc`, `git` (`init`, `status`, `add`, `commit`, `log`, `diff`, `branch`, `checkout`).
76
+ - Developer Toolchains: `node`, `bun`, `npm`, `pnpm`, `npx`, `bunx`, `tsc`, `git` (`init`, `status`, `add`, `commit`, `log`, `diff`, `branch`, `checkout`, `clone`).
77
77
  - Web Preview: `serve` (built-in static dev server that transpiles TS/TSX/JSX to browser-native ESM and injects a jsDelivr `+esm` import map for bare specifiers).
78
78
 
79
79
  ---
80
80
 
81
- ## 3. PTY Terminal Engine (`src/terminal.js`)
81
+ ## 3. PTY Terminal Engine (`src/terminal.ts`)
82
82
 
83
83
  `PTYTerminalEngine` provides an interactive terminal UI and ANSI/VT100 escape sequence parser:
84
84
  - 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`).
@@ -86,7 +86,7 @@ It is designed around two strictly decoupled layers that can be used together (`
86
86
 
87
87
  ---
88
88
 
89
- ## 4. IDE Workbench (`src/workbench.js`)
89
+ ## 4. IDE Workbench (`src/workbench.ts`)
90
90
 
91
91
  `CodeLabWorkbench` and `<code-lab>` provide the full visual IDE experience:
92
92
  - **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.
@@ -111,5 +111,23 @@ Running `bun run build` (`bun run tools/bundle.js`) produces:
111
111
  - `dist/terminal.js` & `dist/terminal.esm.js` (standalone PTY terminal engine)
112
112
  - `dist/code-lab.css` (standalone dark/light CSS variables & workbench styles)
113
113
  - `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)
114
- - `dist/code-lab.d.ts` (TypeScript definitions for `CodeLab`, `CodeLabWorkbench`, `CodeLabElement`, `CodeLabRuntime`, `CodeLabShell`, and `CodeLabTerminal`)
114
+ - `dist/code-lab.d.ts` (TypeScript definitions for `CodeLab`, `CodeLabWorkbench`, `CodeLabElement`, `CodeLabRuntime`, `CodeLabShell`, `CodeLabTerminal`, and the strict leaf modules `zip`, `storage`, `search`, `diagnostics`, and `scm`)
115
+
116
+ ---
117
+
118
+ ## 6. Strict Browser-IDE Modules & Competitor Gap Analysis
119
+
120
+ `@innovatorved/code-lab` includes five strict, zero-`@ts-nocheck` leaf modules (`tsconfig.strict.json`) that close key usability gaps compared to **StackBlitz WebContainers**, **CodeSandbox Sandpack**, and **VS Code for the Web (`vscode.dev`)** while preserving zero server dependencies and zero COOP/COEP header requirements:
121
+
122
+ | Capability | StackBlitz / CodeSandbox / VS Code Web | `@innovatorved/code-lab` Implementation |
123
+ | :--- | :--- | :--- |
124
+ | **Project Archive Export / Import** | Download/upload project as `.zip` archive | `src/zip.ts` (`createZip`, `extractZip`, `computeCrc32`, `sanitizeZipPath`) — RFC-compliant PKZIP STORE (`0x04034b50`) encoder/decoder with zip-slip path traversal protection and workbench `exportProjectZip()` / `importProjectZip()` helpers |
125
+ | **Durable Workspace Persistence** | IndexedDB workspace storage with fallback | `src/storage.ts` (`WorkspaceStorage`, `createWorkspaceStorage`) — Cascading 3-tier persistence (`IndexedDB` → `localStorage` → in-memory `Map`) with quota-exceeded self-healing fallback |
126
+ | **Workspace Search & Replace** | Multi-file regex/glob search & replace (`Cmd+Shift+F`) | `src/search.ts` (`searchInFiles`, `replaceInFiles`, `matchesGlob`) — Cross-file search & replace supporting case sensitivity, whole-word matching, regular expressions, and include/exclude globs |
127
+ | **Unified Diagnostics & Problems** | Problems panel aggregating compiler & test markers | `src/diagnostics.ts` (`DiagnosticsStore`, `createDiagnosticsStore`) — Structured diagnostic store (`error`, `warning`, `info`) with stack-trace parser (`parseRuntimeError`) and node:test failure ingestion |
128
+ | **Visual Source Control (SCM)** | Staging, unstaging, diffing, and commit history | `src/scm.ts` (`createGitState`, `computeGitStatus`, `stageFile`, `unstageFile`, `commitChanges`, `computeShortCommitHash`) — Pure TypeScript SCM state machine synced with the POSIX shell `git` command |
129
+ | **Live Preview & Error Overlay** | Hot/debounced reload, console bridge, runtime error overlay | `src/csp.ts` (`buildPreviewShims`) + `src/workbench.ts` — 300ms debounced VFS-synced auto-reload, `codelab:preview-console` forwarding to terminal logs, and `codelab:preview-error` in-frame overlay |
130
+
131
+ All 39 test suites (`bun run test:all` and `node tests/run-all.js`) and the Playwright Chromium E2E suite (`bun run test:browser`) verify these modules and end-to-end workbench flows against the built `dist/*` artifacts.
132
+
115
133
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > **Note:** This project is in active development. APIs and sandbox internals are stable for production use.
4
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.
5
+ Browser-native code IDE workbench, modular guided challenge engine (`@innovatorved/code-lab/extensions/guided-lab`), POSIX shell with 58 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
6
 
7
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
8
  - **Built for**: [System Design In Depth](https://system-design-in-depth.vedgupta.in)
@@ -11,14 +11,14 @@ Browser-native code IDE workbench, modular guided challenge engine (`@innovatorv
11
11
 
12
12
  ## Features
13
13
 
14
- - **Modular Architecture (`v0.1.7`)**: 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`).
14
+ - **Modular Architecture (`v0.1.8`)**: 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
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
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). Clone progress (`remote: Enumerating objects…`, `Receiving objects: n%…`) streams into the terminal in real time as it downloads.
17
17
  - **Interactive IDE Workbench**: Multi-file Monaco editor, collapsible hierarchical file tree with drag-and-drop, a workspace **folder switcher** (breadcrumb dropdown that scopes the explorer to any subfolder), decoupled editor tabs, Command Palette (`Cmd+Shift+P`), Quick Open (`Cmd+P`), breadcrumbs, and line-by-line solution diff viewer.
18
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.).
19
+ - **POSIX Shell & 58 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 58 UNIX commands (`git`, `ls`, `cat`, `grep`, `find`, `sed`, `awk`, `jq`, `tar`, `curl`, `nc`, `lsof`, `tsc`, etc.).
20
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`).
21
+ - **Node.js**: 50 built-in modules (`fs`, `fs/promises`, `http`, `https`, `net`, `stream`, `events`, `crypto`, `zlib`, `vm`, `worker_threads`, `readline`, `module`, `node:test`, `assert`, etc.).
22
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
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/*`). Public URLs (e.g. `https://example.com`) entered in the preview URL bar open in a real browser tab instead of the virtual frame.
24
24
  - **Built-in Preview Server (`serve`) & Toolbar *Run & Preview***: Render a real app in the browser with no bundler — `serve [dir] [--port]`, the toolbar globe button, or `npm run dev` all start a static server that transpiles `.ts` / `.tsx` / `.jsx` to browser-native ESM, resolves extensionless relative imports, and injects a jsDelivr `+esm` **import map** for bare specifiers (`react`, `react-dom/client`, `@angular/core`, …). Vite/`ng`/Astro/Next scripts that need native binaries transparently fall back to it.
@@ -122,8 +122,8 @@ Complete documentation is published on the [GitHub Wiki](https://github.com/inno
122
122
  - **[Quick Start](https://github.com/innovatorved/code-lab/wiki/Quick-Start)**: Setup, CDN, and quick examples.
123
123
  - **[Integration Guide](https://github.com/innovatorved/code-lab/wiki/Integration-Guide)**: Embedding in React, Next.js, Vite, and HTML.
124
124
  - **[Workbench Configuration](https://github.com/innovatorved/code-lab/wiki/Workbench-Configuration)**: Complete reference of options, methods, events, and shortcuts.
125
- - **[POSIX Shell & Coreutils](https://github.com/innovatorved/code-lab/wiki/POSIX-Shell-and-Coreutils)**: Pipelines, redirects, background jobs, and 40+ UNIX commands.
126
- - **[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.
125
+ - **[POSIX Shell & Coreutils](https://github.com/innovatorved/code-lab/wiki/POSIX-Shell-and-Coreutils)**: Pipelines, redirects, background jobs, and 58 UNIX commands.
126
+ - **[Runtime APIs (Node & Bun)](https://github.com/innovatorved/code-lab/wiki/Runtime-APIs)**: 50 Node.js built-ins, Bun APIs, `bun:test`, `bun:sqlite`, and npm install.
127
127
  - **[HTTP Servers & Networking](https://github.com/innovatorved/code-lab/wiki/HTTP-Servers-and-Networking)**: Virtual port table, background servers, `curl`, and Port Preview.
128
128
  - **[Headless Runtime](https://github.com/innovatorved/code-lab/wiki/Headless-Runtime)**: Run code and tests programmatically with zero UI.
129
129
  - **[Authoring Guided Labs](https://github.com/innovatorved/code-lab/wiki/Authoring-Guided-Labs)**: Schema and invariants for creating interactive coding challenges.
@@ -146,11 +146,21 @@ bun run tests/test-all-builds.js # 15/15 builds & 226 unit tests
146
146
  bun run tests/test-runtime-advanced.js # Advanced runtime, VFS, HTTP/TCP
147
147
  bun run tests/test-option1-shell-bun-http.js # Shell AST, Bun runtime, curl, ports, npm/pnpm
148
148
  bun run tests/test-frameworks.js # React/Preact/Vue/Angular support + browser preview server
149
- bun run tests/test-coreutils-adversarial.js # Adversarial stress tests on 40+ coreutils
149
+ bun run tests/test-coreutils-adversarial.js # Adversarial stress tests on 58 coreutils
150
150
  bun run tests/test-stress-shell.js # Deep pipelines, redirections, large stdout
151
151
  bun run tests/test-workbench-ui.js # Workbench tabs, explorer, shortcuts
152
152
  ```
153
153
 
154
+ Individual suites also run under Node 20, 22 and 24 — CI exercises all three:
155
+
156
+ ```bash
157
+ bun run build && node tests/run-all.js # same 39 suites, Node runtime
158
+ ```
159
+
160
+ Suites load the built bundles from `dist/` (never raw TypeScript from `src/`), so
161
+ `dist/` must exist and be newer than `src/`. `tests/run-all.js` exits with code 2
162
+ and a "dist/ is stale" message otherwise; run `bun run build` first.
163
+
154
164
  ---
155
165
 
156
166
  ## License
package/dist/code-lab.css CHANGED
@@ -2300,6 +2300,11 @@ code-lab,
2300
2300
  background: var(--cl-red);
2301
2301
  }
2302
2302
 
2303
+ .codelab-statusbar__save.is-failed {
2304
+ color: var(--cl-amber);
2305
+ font-weight: 500;
2306
+ }
2307
+
2303
2308
  @keyframes clStatusPulse {
2304
2309
  0%, 100% { opacity: 1; transform: scale(1); }
2305
2310
  50% { opacity: 0.45; transform: scale(0.85); }
@@ -4317,6 +4322,27 @@ code-lab,
4317
4322
 
4318
4323
  .codelab-preview-modes { display: flex; gap: 2px; flex: 0 0 auto; }
4319
4324
 
4325
+ /* CSP badge: which remote hosts the current preview may reach. */
4326
+ .codelab-preview-csp {
4327
+ flex: 0 0 auto;
4328
+ max-width: 220px;
4329
+ overflow: hidden;
4330
+ text-overflow: ellipsis;
4331
+ white-space: nowrap;
4332
+ font-size: 11px;
4333
+ line-height: 18px;
4334
+ padding: 0 8px;
4335
+ border-radius: 999px;
4336
+ border: 1px solid var(--cl-border);
4337
+ color: var(--cl-fg-muted);
4338
+ background: var(--cl-bg-elevated);
4339
+ }
4340
+
4341
+ .codelab-preview-csp--blocked {
4342
+ color: var(--cl-red);
4343
+ border-color: var(--cl-red);
4344
+ }
4345
+
4320
4346
  .codelab-preview-viewport {
4321
4347
  flex: 1 1 auto;
4322
4348
  min-height: 180px;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * TypeScript Definitions for @innovatorved/code-lab v0.1.7
2
+ * TypeScript Definitions for @innovatorved/code-lab v0.1.8
3
3
  */
4
4
 
5
5
  export interface CodeLabStep {
@@ -107,6 +107,213 @@ export interface CodeLabCloneOptions {
107
107
  signal?: AbortSignal;
108
108
  }
109
109
 
110
+ /** Per-directive allowlists for the Web Preview Content-Security-Policy. */
111
+ export interface CodeLabPreviewCspSources {
112
+ scriptSrc?: string[];
113
+ styleSrc?: string[];
114
+ imgSrc?: string[];
115
+ fontSrc?: string[];
116
+ connectSrc?: string[];
117
+ mediaSrc?: string[];
118
+ workerSrc?: string[];
119
+ frameSrc?: string[];
120
+ }
121
+
122
+ export interface CodeLabPreviewCsp extends CodeLabPreviewCspSources {
123
+ /**
124
+ * - balanced (default) allows the CDNs the built-in preview server resolves
125
+ * bare imports to (jsDelivr, esm.sh), plus fonts.googleapis.com.
126
+ * - strict blocks every remote host; only same-origin, data: and blob:.
127
+ * - custom uses only the allowlists you provide.
128
+ */
129
+ mode?: 'strict' | 'balanced' | 'custom';
130
+ }
131
+
132
+ /** Payload emitted when a preview document violates its Content-Security-Policy. */
133
+ export interface CodeLabPreviewViolation {
134
+ directive: string;
135
+ blockedURI: string;
136
+ }
137
+
138
+ /**
139
+ * Build, validate and describe Web Preview Content-Security-Policies.
140
+ * Bundled into both the workbench and dist/preview-sw.js.
141
+ */
142
+ export interface CodeLabCspAPI {
143
+ buildPreviewPolicy(options?: {
144
+ mode?: 'strict' | 'balanced' | 'custom';
145
+ hostOrigin?: string;
146
+ frameAncestors?: string;
147
+ } & CodeLabPreviewCspSources): string;
148
+ normalizePreviewCspConfig(raw: unknown): {
149
+ mode: 'strict' | 'balanced' | 'custom';
150
+ allow: CodeLabPreviewCspSources;
151
+ };
152
+ describePreviewNetwork(config: unknown): string[];
153
+ buildPreviewShims(): string;
154
+ normalizeOrigin(raw: unknown): string | null;
155
+ PREVIEW_SHIM_MARKER: string;
156
+ }
157
+
158
+ export declare const CodeLabCsp: CodeLabCspAPI;
159
+
160
+ export type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
161
+
162
+ export type CodeLabErrorCode =
163
+ | 'E_PERSISTENCE'
164
+ | 'E_WORKER_TIMEOUT'
165
+ | 'E_WORKER_CRASH'
166
+ | 'E_WORKER_INIT'
167
+ | 'E_CSP_VIOLATION'
168
+ | 'E_PREVIEW_SW'
169
+ | 'E_PREVIEW_RENDER'
170
+ | 'E_NETWORK_BLOCKED'
171
+ | 'E_VFS'
172
+ | 'E_SHELL'
173
+ | 'E_TERMINAL'
174
+ | 'E_MONACO_LOAD'
175
+ | 'E_PACKAGE_FETCH'
176
+ | 'E_CLONE_FAILED'
177
+ | 'E_EXTENSION';
178
+
179
+ export interface CodeLabErrorOptions {
180
+ cause?: unknown;
181
+ context?: Record<string, unknown>;
182
+ }
183
+
184
+ export declare class CodeLabError extends Error {
185
+ readonly code: CodeLabErrorCode;
186
+ readonly context?: Record<string, unknown>;
187
+ readonly cause?: unknown;
188
+ constructor(code: CodeLabErrorCode, message: string, options?: CodeLabErrorOptions);
189
+ }
190
+
191
+ export interface Logger {
192
+ readonly level: LogLevel;
193
+ error(message: string, meta?: unknown): void;
194
+ warn(message: string, meta?: unknown): void;
195
+ info(message: string, meta?: unknown): void;
196
+ debug(message: string, meta?: unknown): void;
197
+ }
198
+
199
+ export interface CreateLoggerOptions {
200
+ level?: LogLevel;
201
+ scope?: string;
202
+ sink?: Partial<Record<Exclude<LogLevel, 'silent'>, (line: string, meta?: unknown) => void>>;
203
+ }
204
+
205
+ export declare function isCodeLabError(value: unknown): value is CodeLabError;
206
+ export declare function createLogger(input?: LogLevel | CreateLoggerOptions | Logger): Logger;
207
+ export declare const DEFAULT_LOGGER: Logger;
208
+ export declare const LOG_PREFIX = '[code-lab]';
209
+
210
+ export interface SafeHtml {
211
+ readonly __html: string;
212
+ toString(): string;
213
+ }
214
+
215
+ export declare function escapeHtml(value: unknown): string;
216
+ export declare function raw(trustedHtml: string): SafeHtml;
217
+ export declare function isSafeHtml(value: unknown): value is SafeHtml;
218
+ export declare function html(strings: TemplateStringsArray, ...values: unknown[]): SafeHtml;
219
+
220
+ export declare function computeCrc32(data: string | Uint8Array): number;
221
+ export declare function sanitizeZipPath(rawPath: string): string;
222
+ export declare function createZip(files: Record<string, string | Uint8Array>): Uint8Array;
223
+ export declare function extractZip(archive: Uint8Array): Record<string, Uint8Array>;
224
+ export declare const CodeLabZip: {
225
+ computeCrc32: typeof computeCrc32;
226
+ sanitizeZipPath: typeof sanitizeZipPath;
227
+ createZip: typeof createZip;
228
+ extractZip: typeof extractZip;
229
+ };
230
+
231
+ export interface WorkspaceProjectData {
232
+ id: string;
233
+ name?: string;
234
+ files?: Record<string, string>;
235
+ updatedAt?: number;
236
+ [key: string]: unknown;
237
+ }
238
+
239
+ export interface WorkspaceProjectSummary {
240
+ id: string;
241
+ name: string;
242
+ updatedAt: number;
243
+ fileCount: number;
244
+ }
245
+
246
+ export declare class WorkspaceStorage {
247
+ constructor(options?: Record<string, unknown>);
248
+ getBackendType(): 'indexeddb' | 'localstorage' | 'memory';
249
+ saveProject(project: WorkspaceProjectData): Promise<boolean>;
250
+ loadProject(id: string): Promise<WorkspaceProjectData | null>;
251
+ listProjects(): Promise<WorkspaceProjectSummary[]>;
252
+ deleteProject(id: string): Promise<boolean>;
253
+ }
254
+ export declare function createWorkspaceStorage(options?: Record<string, unknown>): WorkspaceStorage;
255
+ export declare const CodeLabStorage: {
256
+ WorkspaceStorage: typeof WorkspaceStorage;
257
+ createWorkspaceStorage: typeof createWorkspaceStorage;
258
+ };
259
+
260
+ export interface SearchOptions {
261
+ query: string;
262
+ caseSensitive?: boolean;
263
+ wholeWord?: boolean;
264
+ regex?: boolean;
265
+ include?: string;
266
+ exclude?: string;
267
+ }
268
+
269
+ export declare function searchInFiles(files: Record<string, string>, options: SearchOptions): any;
270
+ export declare function replaceInFiles(files: Record<string, string>, options: SearchOptions, replacement: string): any;
271
+ export declare function matchesGlob(filePath: string, globPattern?: string): boolean;
272
+ export declare function escapeRegex(literal: string): string;
273
+ export declare function normalizeSearchPath(rawPath: string): string;
274
+ export declare const CodeLabSearch: {
275
+ searchInFiles: typeof searchInFiles;
276
+ replaceInFiles: typeof replaceInFiles;
277
+ matchesGlob: typeof matchesGlob;
278
+ escapeRegex: typeof escapeRegex;
279
+ normalizeSearchPath: typeof normalizeSearchPath;
280
+ };
281
+
282
+ export declare class DiagnosticsStore {
283
+ add(item: any): void;
284
+ remove(id: string): void;
285
+ clear(source?: string): void;
286
+ getAll(filter?: any): any[];
287
+ getByFile(file: string): any[];
288
+ subscribe(listener: (items: any[]) => void): () => void;
289
+ }
290
+ export declare function createDiagnosticsStore(): DiagnosticsStore;
291
+ export declare const CodeLabDiagnostics: {
292
+ DiagnosticsStore: typeof DiagnosticsStore;
293
+ createDiagnosticsStore: typeof createDiagnosticsStore;
294
+ };
295
+
296
+ export declare function createGitState(initialFiles?: Record<string, string>, branch?: string): any;
297
+ export declare function computeGitStatus(vfsFiles: Record<string, string>, repoRoot: string, gitState: any): any;
298
+ export declare function stageFile(path: string, vfsFiles: Record<string, string>, gitState: any): boolean;
299
+ export declare function unstageFile(path: string, gitState: any): boolean;
300
+ export declare function commitChanges(message: string, author: string | undefined, gitState: any): any;
301
+ export declare function computeShortCommitHash(input: string): string;
302
+ export declare const CodeLabScm: {
303
+ createGitState: typeof createGitState;
304
+ computeGitStatus: typeof computeGitStatus;
305
+ stageFile: typeof stageFile;
306
+ unstageFile: typeof unstageFile;
307
+ commitChanges: typeof commitChanges;
308
+ computeShortCommitHash: typeof computeShortCommitHash;
309
+ };
310
+
311
+ export interface CodeLabSaveStateEvent {
312
+ state: 'saved' | 'failed';
313
+ key: string;
314
+ error?: CodeLabError;
315
+ }
316
+
110
317
  export interface CodeLabOptions {
111
318
  /** Unique identifier used for localStorage persistence */
112
319
  id?: string;
@@ -116,6 +323,15 @@ export interface CodeLabOptions {
116
323
  title?: string;
117
324
  /** Subtitle / summary displayed in the guide panel when README.md is absent */
118
325
  summary?: string;
326
+ /** Content-Security-Policy applied to Web Preview documents */
327
+ previewCsp?: CodeLabPreviewCsp | 'strict' | 'balanced' | 'custom';
328
+ /**
329
+ * Origin used to serve previews from a different origin than the IDE.
330
+ * Requires the preview relay (apps/preview-origin), which has not shipped
331
+ * yet: the option is currently ignored with a console warning rather than
332
+ * silently returning 503s.
333
+ */
334
+ previewOrigin?: string;
119
335
  /** Initial workbench mode ('guided' | 'sandbox') */
120
336
  mode?: 'guided' | 'sandbox';
121
337
  /** Initial workspace language ('js' | 'ts') */
@@ -125,6 +341,10 @@ export interface CodeLabOptions {
125
341
  theme?: 'dark' | 'light' | 'auto';
126
342
  /** Set to false to disable localStorage persistence and use in-memory state only */
127
343
  persistState?: boolean;
344
+ /** Structured logger or log level ('silent' | 'error' | 'warn' | 'info' | 'debug', default: 'warn') */
345
+ logger?: LogLevel | CreateLoggerOptions | Logger;
346
+ /** Shortcut for setting logger level */
347
+ logLevel?: LogLevel;
128
348
  /** Public GitHub repository URL or owner/repo shorthand to automatically clone on mount */
129
349
  repo?: string;
130
350
  githubRepo?: string;
@@ -234,12 +454,32 @@ export declare class CodeLabWorkbench {
234
454
  downloadFile(path?: string): { filename: string; content: string } | null;
235
455
  exportWorkspace(options?: { download?: boolean }): Record<string, any>;
236
456
  importWorkspace(snapshotOrJson: string | Record<string, any>): boolean;
457
+ exportZip(options?: { download?: boolean; filename?: string }): Uint8Array | null;
458
+ importZip(archiveBytes: Uint8Array, options?: { merge?: boolean }): number;
459
+ showSearchModal(initialQuery?: string): void;
460
+ showScmModal(): void;
461
+ getDiagnostics(filter?: { file?: string; severity?: 'error' | 'warning' | 'info'; source?: string }): any[];
462
+ showProblemsModal(): void;
463
+ listTerminalSessions(): Array<{ id: string; name: string; active: boolean }>;
464
+ createTerminalSession(name?: string): string;
465
+ switchTerminalSession(id: string): boolean;
466
+ closeTerminalSession(id: string): boolean;
467
+ saveProjectToStorage(projectId?: string): Promise<boolean>;
468
+ loadProjectFromStorage(projectId?: string): Promise<boolean>;
237
469
  getFiles(): Record<string, string>;
238
470
  setFiles(filesMap: Record<string, string>, options?: { merge?: boolean }): this;
239
471
  getFile(path: string): string | null;
240
472
  setFile(path: string, content: string, options?: { open?: boolean }): this;
241
473
  getOpenTabs(): string[];
242
474
  reset(): this;
475
+ previewOrigin: string | null;
476
+ previewCsp: { mode: 'strict' | 'balanced' | 'custom'; allow: CodeLabPreviewCspSources };
477
+ logger: Logger;
478
+ saveStatusState: 'saved' | 'failed';
479
+ lastSaveError: CodeLabError | null;
480
+ on(event: 'preview-violation', handler: (detail: CodeLabPreviewViolation) => void): () => void;
481
+ on(event: 'save-state', handler: (detail: CodeLabSaveStateEvent) => void): () => void;
482
+ on(event: 'error', handler: (detail: CodeLabError) => void): () => void;
243
483
  on(event: string, handler: (detail: any) => void): () => void;
244
484
  off(event: string, handler: (detail: any) => void): this;
245
485
  use(plugin: (workbench: CodeLabWorkbench, options?: any) => any, options?: any): this;
@@ -266,6 +506,16 @@ export declare class CodeLabElement extends HTMLElement {
266
506
  showDiffModal(targetFile?: string, compareTarget?: 'solution' | 'starter'): void;
267
507
  exportWorkspace(options?: { download?: boolean }): Record<string, any> | null;
268
508
  importWorkspace(snapshotOrJson: string | Record<string, any>): boolean;
509
+ exportZip(options?: { download?: boolean; filename?: string }): Uint8Array | null;
510
+ importZip(archiveBytes: Uint8Array, options?: { merge?: boolean }): number;
511
+ showSearchModal(initialQuery?: string): void;
512
+ showScmModal(): void;
513
+ getDiagnostics(filter?: { file?: string; severity?: 'error' | 'warning' | 'info'; source?: string }): any[];
514
+ showProblemsModal(): void;
515
+ listTerminalSessions(): Array<{ id: string; name: string; active: boolean }>;
516
+ createTerminalSession(name?: string): string | null;
517
+ switchTerminalSession(id: string): boolean;
518
+ closeTerminalSession(id: string): boolean;
269
519
  cloneRepo(repoUrlOrSlug: string, options?: CodeLabCloneOptions): Promise<any>;
270
520
  }
271
521
 
@@ -346,6 +596,26 @@ export interface CodeLabStatic {
346
596
  unmount(container: HTMLElement | string): void;
347
597
  cloneRepo(vfsOrWorkbench: any, repoInput: string, options?: CodeLabCloneOptions): Promise<any>;
348
598
  parseGitHubRepoUrl: CodeLabShellAPI['parseGitHubRepoUrl'];
599
+ CodeLabError: typeof CodeLabError;
600
+ isCodeLabError: typeof isCodeLabError;
601
+ createLogger: typeof createLogger;
602
+ Logger: {
603
+ CodeLabError: typeof CodeLabError;
604
+ isCodeLabError: typeof isCodeLabError;
605
+ createLogger: typeof createLogger;
606
+ DEFAULT_LOGGER: Logger;
607
+ LOG_PREFIX: typeof LOG_PREFIX;
608
+ };
609
+ html: typeof html;
610
+ raw: typeof raw;
611
+ isSafeHtml: typeof isSafeHtml;
612
+ escapeHtml: typeof escapeHtml;
613
+ Html: {
614
+ html: typeof html;
615
+ raw: typeof raw;
616
+ isSafeHtml: typeof isSafeHtml;
617
+ escapeHtml: typeof escapeHtml;
618
+ };
349
619
  }
350
620
 
351
621
  export declare const CodeLab: CodeLabStatic;