@innovatorved/code-lab 0.1.13 → 0.2.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/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.10
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.2.0
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
@@ -22,8 +22,11 @@ export type GuidedStep = z.infer<typeof GuidedStepSchema>;
22
22
 
23
23
  // ── 2. Language Bundle ──────────────────────────────────────────────────────
24
24
 
25
+ export const LanguageIdSchema = z.enum(['js', 'ts', 'cpp']);
26
+ export type LanguageId = z.infer<typeof LanguageIdSchema>;
27
+
25
28
  export const LanguageBundleSchema = z.object({
26
- language: z.enum(['js', 'ts']).default('js'),
29
+ language: LanguageIdSchema.default('js'),
27
30
  files: z.record(z.string()).default({}),
28
31
  starterFiles: z.record(z.string()).optional(),
29
32
  solutionFiles: z.record(z.string()).optional(),
@@ -39,13 +42,16 @@ export const GuidedLabExtensionOptionsSchema = z.object({
39
42
  steps: z.array(GuidedStepSchema).default([]),
40
43
  stepIndex: z.number().int().nonnegative().default(0),
41
44
  mode: z.enum(['guided', 'sandbox']).default('guided'),
42
- language: z.enum(['js', 'ts']).optional(),
43
- lang: z.enum(['js', 'ts']).optional(),
45
+ language: LanguageIdSchema.optional(),
46
+ lang: LanguageIdSchema.optional(),
44
47
  starterFiles: z.record(z.string()).optional(),
45
48
  solutionFiles: z.record(z.string()).optional(),
46
49
  tsStarterFiles: z.record(z.string()).optional(),
47
50
  tsSolutionFiles: z.record(z.string()).optional(),
48
51
  tsFiles: z.record(z.string()).optional(),
52
+ cppStarterFiles: z.record(z.string()).optional(),
53
+ cppSolutionFiles: z.record(z.string()).optional(),
54
+ cppFiles: z.record(z.string()).optional(),
49
55
  summary: z.string().optional(),
50
56
  onStepComplete: z.function().args(GuidedStepSchema, z.number()).returns(z.void()).optional(),
51
57
  onLabComplete: z.function().args(z.string()).returns(z.void()).optional()
@@ -53,6 +59,39 @@ export const GuidedLabExtensionOptionsSchema = z.object({
53
59
 
54
60
  export type GuidedLabExtensionOptions = z.infer<typeof GuidedLabExtensionOptionsSchema>;
55
61
 
62
+ export const CppToolchainProgressSchema = z.object({
63
+ stage: z.enum(['downloading', 'caching', 'extracting', 'compiling', 'linking', 'ready']),
64
+ loadedBytes: z.number().optional(),
65
+ totalBytes: z.number().optional(),
66
+ percent: z.number().optional(),
67
+ message: z.string().optional()
68
+ });
69
+
70
+ export type CppToolchainProgress = z.infer<typeof CppToolchainProgressSchema>;
71
+
72
+ export const CppExtensionOptionsSchema = z.object({
73
+ toolchainUrl: z.string().optional(),
74
+ clangWasmUrl: z.string().optional(),
75
+ clangUrl: z.string().optional(),
76
+ lldWasmUrl: z.string().optional(),
77
+ lldUrl: z.string().optional(),
78
+ sysrootTarUrl: z.string().optional(),
79
+ sysrootUrl: z.string().optional(),
80
+ cacheInIndexedDB: z.boolean().default(true),
81
+ preload: z.boolean().default(false),
82
+ std: z.enum(['c++17', 'c++20', 'c++23']).default('c++20'),
83
+ optLevel: z.enum(['-O0', '-O1', '-O2', '-O3']).default('-O2'),
84
+ flags: z.array(z.string()).default(['-O2', '-Wall', '-Wextra']),
85
+ headers: z.record(z.string()).optional(),
86
+ extraHeaders: z.record(z.string()).optional(),
87
+ files: z.record(z.string()).optional(),
88
+ starterFiles: z.record(z.string()).optional(),
89
+ solutionFiles: z.record(z.string()).optional(),
90
+ onProgress: z.function().args(z.any()).returns(z.void()).optional()
91
+ });
92
+
93
+ export type CppExtensionOptions = z.infer<typeof CppExtensionOptionsSchema>;
94
+
56
95
  // ── 4. GitHub Clone Options & Progress ──────────────────────────────────────
57
96
 
58
97
  export const CloneProgressPhaseSchema = z.enum([
@@ -127,7 +166,7 @@ export const WorkspaceSnapshotSchema = z.object({
127
166
  openTabs: z.array(z.string()).default([]),
128
167
  activeFile: z.string().nullable().optional(),
129
168
  mode: z.enum(['guided', 'sandbox']).optional(),
130
- lang: z.enum(['js', 'ts']).optional(),
169
+ lang: LanguageIdSchema.optional(),
131
170
  labId: z.string().optional()
132
171
  });
133
172
 
@@ -168,10 +207,13 @@ export const WorkbenchOptionsSchema = z.object({
168
207
  tsFiles: z.record(z.string()).optional(),
169
208
  tsStarterFiles: z.record(z.string()).optional(),
170
209
  tsSolutionFiles: z.record(z.string()).optional(),
210
+ cppFiles: z.record(z.string()).optional(),
211
+ cppStarterFiles: z.record(z.string()).optional(),
212
+ cppSolutionFiles: z.record(z.string()).optional(),
171
213
  guided: z.any().optional(),
172
214
  mode: z.enum(['guided', 'sandbox']).optional(),
173
- language: z.enum(['js', 'ts']).optional(),
174
- lang: z.enum(['js', 'ts']).optional(),
215
+ language: LanguageIdSchema.optional(),
216
+ lang: LanguageIdSchema.optional(),
175
217
  stepIndex: z.number().int().optional(),
176
218
  onStepComplete: z.function().args(z.any(), z.number()).returns(z.void()).optional(),
177
219
  onLabComplete: z.function().args(z.string()).returns(z.void()).optional()
package/src/shell.ts CHANGED
@@ -1682,7 +1682,7 @@
1682
1682
  }
1683
1683
  return Array.from(children).sort();
1684
1684
  },
1685
- readFileSync(p) {
1685
+ readFileSync(p, encoding) {
1686
1686
  const np = norm(p);
1687
1687
  const f = files.get(np);
1688
1688
  if (!f) {
@@ -1690,6 +1690,9 @@
1690
1690
  err.code = 'ENOENT';
1691
1691
  throw err;
1692
1692
  }
1693
+ if (!encoding && f.rawBytes instanceof Uint8Array) {
1694
+ return f.rawBytes;
1695
+ }
1693
1696
  return f.data;
1694
1697
  },
1695
1698
  writeFileSync(p, data) {
@@ -1700,9 +1703,13 @@
1700
1703
  let cur = '';
1701
1704
  for (const pt of parts) { cur += '/' + pt; dirs.add(cur); }
1702
1705
  }
1703
- const str = typeof data === 'string' ? data : (data.toString ? data.toString('utf8') : String(data));
1706
+ const isBinary = data instanceof Uint8Array;
1707
+ const rawBytes = isBinary ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null;
1708
+ const str = isBinary
1709
+ ? new TextDecoder('utf-8').decode(rawBytes)
1710
+ : (typeof data === 'string' ? data : (data && data.toString ? data.toString('utf8') : String(data)));
1704
1711
  const prevMode = files.has(np) ? files.get(np).mode : 0o100644;
1705
- files.set(np, { data: str, mtimeMs: Date.now(), mode: prevMode });
1712
+ files.set(np, { data: str, rawBytes, mtimeMs: Date.now(), mode: prevMode });
1706
1713
  },
1707
1714
  appendFileSync(p, data) {
1708
1715
  const np = norm(p);
@@ -5929,6 +5936,7 @@
5929
5936
  stdout += ' history, ps, jobs, kill Process and job management\n';
5930
5937
  stdout += ' git [status diff log] Built-in version control\n';
5931
5938
  stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
5939
+ stdout += ' g++, clang++, c++ C++20 WebAssembly compiler (via cppExtension)\n';
5932
5940
  stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
5933
5941
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
5934
5942
  stdout += ' hey, ab, wrk Concurrent HTTP load generator & latency percentiles\n';
@@ -6047,6 +6055,125 @@
6047
6055
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6048
6056
  },
6049
6057
 
6058
+ async 'g++'(args, ctx) {
6059
+ if (args.includes('--version') || args.includes('-v')) {
6060
+ return {
6061
+ code: 0,
6062
+ stdout: 'clang version 18.1.8 (Target: wasm32-unknown-wasi)\nTarget: wasm32-unknown-wasi\nThread model: posix\nInstalledDir: /usr/bin\n',
6063
+ stderr: ''
6064
+ };
6065
+ }
6066
+ if (args.includes('--help') || args.includes('-h')) {
6067
+ return {
6068
+ code: 0,
6069
+ stdout:
6070
+ 'Usage: g++ [options] file...\n' +
6071
+ 'Options:\n' +
6072
+ ' -std=<standard> Assume that the input sources are for <standard> (c++17, c++20, c++23)\n' +
6073
+ ' -O0, -O1, -O2, -O3 Optimization level\n' +
6074
+ ' -o <file> Write output to <file> (default: a.out)\n' +
6075
+ ' -I <dir> Add directory to include search path\n',
6076
+ stderr: ''
6077
+ };
6078
+ }
6079
+
6080
+ const sourceFiles = [];
6081
+ const extraFlags = [];
6082
+ let outputPath = PosixPath.join(ctx.cwd, 'a.out');
6083
+ let std = 'c++20';
6084
+ let optLevel = '-O2';
6085
+
6086
+ for (let i = 0; i < args.length; i++) {
6087
+ const arg = args[i];
6088
+ if (arg === '-o' && i + 1 < args.length) {
6089
+ outputPath = ctx.resolvePath(args[++i]);
6090
+ } else if (arg.startsWith('-o') && arg.length > 2) {
6091
+ outputPath = ctx.resolvePath(arg.slice(2));
6092
+ } else if (arg.startsWith('-std=')) {
6093
+ const val = arg.slice(5);
6094
+ if (val === 'c++17' || val === 'gnu++17') std = 'c++17';
6095
+ else if (val === 'c++23' || val === 'c++2b' || val === 'gnu++23') std = 'c++23';
6096
+ else std = 'c++20';
6097
+ } else if (arg === '-O0' || arg === '-O1' || arg === '-O2' || arg === '-O3') {
6098
+ optLevel = arg;
6099
+ } else if (arg.startsWith('-I') || arg.startsWith('-D') || arg.startsWith('-W')) {
6100
+ extraFlags.push(arg);
6101
+ } else if (!arg.startsWith('-')) {
6102
+ sourceFiles.push(ctx.resolvePath(arg));
6103
+ }
6104
+ }
6105
+
6106
+ if (sourceFiles.length === 0) {
6107
+ return { code: 1, stdout: '', stderr: 'g++: fatal error: no input files\ncompilation terminated.\n' };
6108
+ }
6109
+
6110
+ for (const src of sourceFiles) {
6111
+ if (!ctx.vfs.existsSync(src)) {
6112
+ return { code: 1, stdout: '', stderr: `g++: error: ${src}: No such file or directory\n` };
6113
+ }
6114
+ }
6115
+
6116
+ const cppCompiler =
6117
+ (ctx.shell && ctx.shell.options && ctx.shell.options.cppCompiler) ||
6118
+ (typeof globalThis !== 'undefined' && globalThis.__codelabCppCompiler) ||
6119
+ (typeof window !== 'undefined' && window.__codelabCppCompiler);
6120
+
6121
+ if (typeof cppCompiler !== 'function') {
6122
+ return {
6123
+ code: 1,
6124
+ stdout: '',
6125
+ stderr:
6126
+ 'g++: C++ toolchain is not enabled. Enable cppExtension from "@innovatorved/code-lab/extensions/cpp" to compile C++ files.\n'
6127
+ };
6128
+ }
6129
+
6130
+ let outText = '';
6131
+ let errText = '';
6132
+ const compileRes = await cppCompiler({
6133
+ entry: sourceFiles[0],
6134
+ sourceFiles,
6135
+ outputPath,
6136
+ std,
6137
+ optLevel,
6138
+ extraFlags,
6139
+ vfs: ctx.vfs,
6140
+ onStdout: (t) => {
6141
+ outText += t;
6142
+ if (ctx.onStdout) ctx.onStdout(t);
6143
+ },
6144
+ onStderr: (t) => {
6145
+ errText += t;
6146
+ if (ctx.onStderr) ctx.onStderr(t);
6147
+ }
6148
+ });
6149
+
6150
+ if (!compileRes || compileRes.exitCode !== 0) {
6151
+ return {
6152
+ code: (compileRes && compileRes.exitCode) || 1,
6153
+ stdout: outText,
6154
+ stderr: errText || 'g++: error: linker command failed with exit code 1\n'
6155
+ };
6156
+ }
6157
+
6158
+ if (compileRes.wasmBinary) {
6159
+ ctx.vfs.writeFileSync(outputPath, compileRes.wasmBinary);
6160
+ if (typeof ctx.vfs.chmodSync === 'function') {
6161
+ try { ctx.vfs.chmodSync(outputPath, 0o755); } catch (err) { _shellLogger.debug('chmodSync failed on compiled binary', err); }
6162
+ }
6163
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', outputPath);
6164
+ }
6165
+
6166
+ return { code: 0, stdout: outText, stderr: errText };
6167
+ },
6168
+
6169
+ async 'clang++'(args, ctx) {
6170
+ return COREUTILS['g++'](args, ctx);
6171
+ },
6172
+
6173
+ async 'c++'(args, ctx) {
6174
+ return COREUTILS['g++'](args, ctx);
6175
+ },
6176
+
6050
6177
  async bun(args, ctx) {
6051
6178
  if (args.length === 0) {
6052
6179
  return { code: 0, stdout: 'Bun v1.1.20\n', stderr: '' };
@@ -7649,6 +7776,10 @@
7649
7776
  return { code: lastCode, exitCode: lastCode, stdout: combinedStdout, stderr: combinedStderr, ok: lastCode === 0 };
7650
7777
  }
7651
7778
 
7779
+ async executeCommand(commandLine, execOptions = {}) {
7780
+ return this.execute(commandLine, execOptions);
7781
+ }
7782
+
7652
7783
  async _executeWithRedirects(redirects, context, execFn) {
7653
7784
  if (!redirects || redirects.length === 0) {
7654
7785
  return execFn(context);
@@ -8329,6 +8460,48 @@
8329
8460
  Object.assign(context.env, this.env);
8330
8461
  context.cwd = this.cwd;
8331
8462
  }
8463
+ } else if (
8464
+ (cmdName.startsWith('./') || cmdName.startsWith('../') || cmdName.startsWith('/')) &&
8465
+ this.vfs.existsSync(this.resolvePath(cmdName))
8466
+ ) {
8467
+ const absBin = this.resolvePath(cmdName);
8468
+ const st = this.vfs.statSync(absBin);
8469
+ if (st && st.isDirectory()) {
8470
+ res = { code: 126, stdout: '', stderr: `shell: ${cmdName}: Is a directory\n` };
8471
+ } else if (hasVirtualRuntime()) {
8472
+ let rawData = null;
8473
+ try { rawData = this.vfs.readFileSync(absBin); } catch (err) { _shellLogger.debug('Failed to read binary', err); }
8474
+ const isWasmMagic =
8475
+ (rawData instanceof Uint8Array &&
8476
+ rawData.length >= 4 &&
8477
+ rawData[0] === 0x00 &&
8478
+ rawData[1] === 0x61 &&
8479
+ rawData[2] === 0x73 &&
8480
+ rawData[3] === 0x6d) ||
8481
+ (typeof rawData === 'string' && rawData.startsWith('\0asm'));
8482
+ const runRes = await executeInVirtualRuntime({
8483
+ mode: 'run',
8484
+ entry: absBin,
8485
+ wasmBinary: isWasmMagic && rawData instanceof Uint8Array ? rawData : undefined,
8486
+ argv: [cmdName, ...args],
8487
+ stdin: effectiveStdin,
8488
+ env: cmdEnv,
8489
+ vfs: this.vfs,
8490
+ activePortTable: this.portTable,
8491
+ pid: cmdCtx.pid,
8492
+ isBackground: cmdCtx.isBackground,
8493
+ onStdout: cmdCtx.onStdout,
8494
+ onStderr: cmdCtx.onStderr,
8495
+ signal: context.signal
8496
+ });
8497
+ res = {
8498
+ code: runRes.ok ? 0 : (runRes.exitCode || 1),
8499
+ stdout: runRes.stdout || '',
8500
+ stderr: runRes.stderr || ''
8501
+ };
8502
+ } else {
8503
+ res = { code: 126, stdout: '', stderr: `shell: ${cmdName}: cannot execute binary file\n` };
8504
+ }
8332
8505
  } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
8333
8506
  // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
8334
8507
  // this runtime — whether or not it was installed — so route it to the