@innovatorved/code-lab 0.1.6 → 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.
Files changed (51) hide show
  1. package/ARCHITECTURE.md +34 -16
  2. package/README.md +17 -7
  3. package/dist/code-lab.css +26 -0
  4. package/dist/code-lab.d.ts +271 -1
  5. package/dist/code-lab.esm.js +2909 -166
  6. package/dist/code-lab.js +2869 -164
  7. package/dist/csp.d.ts +86 -0
  8. package/dist/diagnostics.d.ts +43 -0
  9. package/dist/extensions/guided-lab.esm.js +66 -0
  10. package/dist/extensions/guided-lab.js +66 -0
  11. package/dist/html.d.ts +24 -0
  12. package/dist/index.d.ts +9 -1
  13. package/dist/logger.d.ts +60 -0
  14. package/dist/preview-sw.js +425 -11
  15. package/dist/runtime.d.ts +6 -27
  16. package/dist/runtime.esm.js +171 -31
  17. package/dist/runtime.js +171 -31
  18. package/dist/schemas.d.ts +366 -25
  19. package/dist/schemas.esm.js +73 -0
  20. package/dist/schemas.js +73 -0
  21. package/dist/scm.d.ts +77 -0
  22. package/dist/search.d.ts +75 -0
  23. package/dist/shell.d.ts +18 -47
  24. package/dist/shell.esm.js +236 -37
  25. package/dist/shell.js +236 -37
  26. package/dist/storage.d.ts +57 -0
  27. package/dist/terminal.d.ts +11 -87
  28. package/dist/terminal.esm.js +124 -7
  29. package/dist/terminal.js +124 -7
  30. package/dist/zip.d.ts +42 -0
  31. package/package.json +11 -3
  32. package/src/code-lab.css +26 -0
  33. package/src/csp.ts +396 -0
  34. package/src/diagnostics.ts +116 -0
  35. package/src/html.ts +88 -0
  36. package/src/index.ts +39 -1
  37. package/src/logger.ts +139 -0
  38. package/src/preview-sw.js +97 -11
  39. package/src/runtime.ts +132 -105
  40. package/src/schemas.ts +94 -1
  41. package/src/scm.ts +268 -0
  42. package/src/search.ts +389 -0
  43. package/src/shell.ts +410 -369
  44. package/src/storage.ts +377 -0
  45. package/src/terminal.ts +898 -918
  46. package/src/workbench.ts +926 -89
  47. package/src/zip.ts +326 -0
  48. package/src/runtime.js +0 -8229
  49. package/src/shell.js +0 -7257
  50. package/src/terminal.js +0 -1046
  51. package/src/workbench.js +0 -7353
package/src/runtime.ts CHANGED
@@ -20,6 +20,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
20
20
  */
21
21
 
22
22
  function __initVirtualRuntime(rootScope) {
23
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
24
+ ? rootScope.CodeLabLogger.createLogger()
25
+ : {
26
+ debug() {},
27
+ info() {},
28
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
29
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
30
+ };
23
31
  // =========================================================================
24
32
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
25
33
  // =========================================================================
@@ -1579,7 +1587,7 @@ function __initVirtualRuntime(rootScope) {
1579
1587
  },
1580
1588
  final(cb) {
1581
1589
  if (fd !== null) {
1582
- try { fsShim.closeSync(fd); } catch (_) {}
1590
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1583
1591
  fd = null;
1584
1592
  }
1585
1593
  cb(null);
@@ -2099,7 +2107,9 @@ function __initVirtualRuntime(rootScope) {
2099
2107
  return pathname + search + hash;
2100
2108
  }
2101
2109
  return resolvedUrl.href;
2102
- } catch (_) {}
2110
+ } catch (err) {
2111
+ _runtimeLogger.debug('url.resolve fallback used', err);
2112
+ }
2103
2113
  }
2104
2114
  if (toStr.startsWith('/')) {
2105
2115
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2538,10 +2548,10 @@ function __initVirtualRuntime(rootScope) {
2538
2548
  for (const [port, entry] of Array.from(table.entries())) {
2539
2549
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2540
2550
  if (entry.server && typeof entry.server.close === 'function') {
2541
- try { entry.server.close(); } catch (_) {}
2551
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2542
2552
  }
2543
2553
  if (typeof entry.stop === 'function') {
2544
- try { entry.stop(); } catch (_) {}
2554
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2545
2555
  }
2546
2556
  // Avoid a double 'close' emission when entry.server.close() already
2547
2557
  // unregistered the port through unregisterServer().
@@ -3178,7 +3188,7 @@ function __initVirtualRuntime(rootScope) {
3178
3188
  },
3179
3189
  closeAllServers() {
3180
3190
  for (const s of Array.from(activeServers.values())) {
3181
- try { s.close(); } catch (_) {}
3191
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3182
3192
  }
3183
3193
  activeServers.clear();
3184
3194
  }
@@ -4004,7 +4014,7 @@ function __initVirtualRuntime(rootScope) {
4004
4014
 
4005
4015
  function closeAllServers() {
4006
4016
  for (const srv of servers.values()) {
4007
- try { srv.close(); } catch (_) {}
4017
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4008
4018
  }
4009
4019
  servers.clear();
4010
4020
  }
@@ -4898,8 +4908,8 @@ function __initVirtualRuntime(rootScope) {
4898
4908
 
4899
4909
  if ((hasESM || isTS) && !keepEsm) {
4900
4910
  // Convert ES module imports (including multi-line `{ ... }`)
4901
- code = code.replace(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = require($2);');
4902
- code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4911
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4912
+ code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4903
4913
  const cleaned = specifiers
4904
4914
  .split(',')
4905
4915
  .map((s) => s.trim())
@@ -4910,7 +4920,7 @@ function __initVirtualRuntime(rootScope) {
4910
4920
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4911
4921
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4912
4922
  });
4913
- code = code.replace(/\bimport\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4923
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4914
4924
  const cleaned = specifiers
4915
4925
  .split(',')
4916
4926
  .map((s) => s.trim())
@@ -4933,11 +4943,11 @@ function __initVirtualRuntime(rootScope) {
4933
4943
  let defaultExportName = null;
4934
4944
  let hasEsmExport = false;
4935
4945
 
4936
- code = code.replace(/\bexport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4946
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4937
4947
  hasEsmExport = true;
4938
4948
  return `exports.${ns} = require(${mod.trim()});`;
4939
4949
  });
4940
- code = code.replace(/\bexport\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4950
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4941
4951
  hasEsmExport = true;
4942
4952
  return `Object.assign(exports, require(${mod.trim()}));`;
4943
4953
  });
@@ -4960,7 +4970,7 @@ function __initVirtualRuntime(rootScope) {
4960
4970
  exportedNames.push(name);
4961
4971
  return `${kw} ${name}`;
4962
4972
  });
4963
- code = code.replace(/\bexport\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4973
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4964
4974
  hasEsmExport = true;
4965
4975
  const mTrim = mod.trim();
4966
4976
  return list.split(',').map((item) => {
@@ -4972,7 +4982,7 @@ function __initVirtualRuntime(rootScope) {
4972
4982
  return `exports.${exported} = require(${mTrim}).${local};`;
4973
4983
  }).join(' ');
4974
4984
  });
4975
- code = code.replace(/\bexport\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4985
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4976
4986
  hasEsmExport = true;
4977
4987
  return list.split(',').map((item) => {
4978
4988
  const trimmed = item.trim();
@@ -5047,9 +5057,9 @@ function __initVirtualRuntime(rootScope) {
5047
5057
  // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
5048
5058
  // preloadNpmPackages(files, existingCache) // package-text cache (Map)
5049
5059
  // preloadNpmPackages(files, existingCache, onProgress)
5050
- const isCacheLike = (v: any) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
5051
- let onProgress: any = null;
5052
- let existingCache: any = _npmPackageCache;
5060
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
5061
+ let onProgress = null;
5062
+ let existingCache = _npmPackageCache;
5053
5063
  if (typeof secondArg === 'function') onProgress = secondArg;
5054
5064
  else if (isCacheLike(secondArg)) existingCache = secondArg;
5055
5065
  if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
@@ -5084,7 +5094,9 @@ function __initVirtualRuntime(rootScope) {
5084
5094
  try {
5085
5095
  const pkgJson = JSON.parse(content);
5086
5096
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5087
- } catch (_) {}
5097
+ } catch (err) {
5098
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
5099
+ }
5088
5100
  continue;
5089
5101
  }
5090
5102
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5099,21 +5111,23 @@ function __initVirtualRuntime(rootScope) {
5099
5111
  if (typeof fetch === 'function') {
5100
5112
  let pass = 0;
5101
5113
  while (pass < 6) {
5102
- const pending: string[] = [];
5114
+ const pending = [];
5103
5115
  for (const pkg of specs) {
5104
- if (!_npmMetadataCache.has(pkg)) pending.push(pkg as string);
5116
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
5105
5117
  }
5106
5118
  if (pending.length === 0) break;
5107
5119
  pass++;
5108
5120
  await Promise.all(pending.map(async (pkg) => {
5109
- let deps: string[] = [];
5121
+ let deps = [];
5110
5122
  try {
5111
5123
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
5112
5124
  if (res && res.ok) {
5113
5125
  const meta = await res.json();
5114
5126
  deps = Object.keys((meta && meta.dependencies) || {});
5115
5127
  }
5116
- } catch (_) {}
5128
+ } catch (err) {
5129
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
5130
+ }
5117
5131
  _npmMetadataCache.set(pkg, deps);
5118
5132
  }));
5119
5133
  for (const pkg of pending) {
@@ -5131,7 +5145,7 @@ function __initVirtualRuntime(rootScope) {
5131
5145
  continue;
5132
5146
  }
5133
5147
  if (typeof onProgress === 'function') {
5134
- try { onProgress(pkg); } catch (_) {}
5148
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5135
5149
  }
5136
5150
  if (typeof fetch === 'function') {
5137
5151
  try {
@@ -5141,7 +5155,9 @@ function __initVirtualRuntime(rootScope) {
5141
5155
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5142
5156
  loaded[pkg] = text;
5143
5157
  }
5144
- } catch (_) {}
5158
+ } catch (err) {
5159
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
5160
+ }
5145
5161
  }
5146
5162
  }
5147
5163
  return loaded;
@@ -5333,7 +5349,9 @@ function __initVirtualRuntime(rootScope) {
5333
5349
  const dir = VirtualPath.dirname(abs);
5334
5350
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5335
5351
  vfs.writeFileSync(abs, content);
5336
- } catch (_) {}
5352
+ } catch (err) {
5353
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
5354
+ }
5337
5355
  }
5338
5356
  }
5339
5357
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5778,7 +5796,7 @@ function __initVirtualRuntime(rootScope) {
5778
5796
  exitCode = Number(code) || 0;
5779
5797
  if (!hasExited) {
5780
5798
  hasExited = true;
5781
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
5799
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5782
5800
  }
5783
5801
  if (syncExecDepth > 0) {
5784
5802
  throw new ProcessExitSignal(exitCode);
@@ -5811,8 +5829,8 @@ function __initVirtualRuntime(rootScope) {
5811
5829
  resourceTracker.inFlightHttp.clear();
5812
5830
 
5813
5831
  if (!isBackground) {
5814
- try { vhttp.closeAllServers(); } catch (_) {}
5815
- try { vnet.closeAllServers(); } catch (_) {}
5832
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
5833
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5816
5834
  }
5817
5835
  };
5818
5836
 
@@ -5922,10 +5940,10 @@ function __initVirtualRuntime(rootScope) {
5922
5940
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5923
5941
  } finally {
5924
5942
  for (const ae of hooksSnapshot.afterEachList) {
5925
- try { await ae(); } catch (_) {}
5943
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5926
5944
  }
5927
5945
  for (const af of hooksSnapshot.afterToRun) {
5928
- try { await af(); } catch (_) {}
5946
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5929
5947
  }
5930
5948
  hooksSnapshot.afterToRun.length = 0;
5931
5949
  }
@@ -5973,7 +5991,7 @@ function __initVirtualRuntime(rootScope) {
5973
5991
  const afters = [...suiteCtx.afterCallbacks];
5974
5992
  const cleanupTask = nodeTestChain.then(async () => {
5975
5993
  for (const af of afters) {
5976
- try { await af(); } catch (_) {}
5994
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5977
5995
  }
5978
5996
  });
5979
5997
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6019,7 +6037,7 @@ function __initVirtualRuntime(rootScope) {
6019
6037
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6020
6038
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6021
6039
  };
6022
- try { obs._cb(list, obs); } catch (_) {}
6040
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6023
6041
  }
6024
6042
  }
6025
6043
  }
@@ -6124,7 +6142,7 @@ function __initVirtualRuntime(rootScope) {
6124
6142
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6125
6143
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6126
6144
  };
6127
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
6145
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6128
6146
  }
6129
6147
  }
6130
6148
  }
@@ -7395,7 +7413,9 @@ function __initVirtualRuntime(rootScope) {
7395
7413
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7396
7414
  if (resolvedEntry) return resolvedEntry;
7397
7415
  }
7398
- } catch (_) {}
7416
+ } catch (err) {
7417
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
7418
+ }
7399
7419
  }
7400
7420
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7401
7421
  for (const idx of indexCandidates) {
@@ -7465,7 +7485,9 @@ function __initVirtualRuntime(rootScope) {
7465
7485
  if (found) return found;
7466
7486
  }
7467
7487
  }
7468
- } catch (_) {}
7488
+ } catch (err) {
7489
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
7490
+ }
7469
7491
  }
7470
7492
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7471
7493
  if (foundSub) return foundSub;
@@ -7507,7 +7529,9 @@ function __initVirtualRuntime(rootScope) {
7507
7529
  if (isLocal && activePortTable) {
7508
7530
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7509
7531
  }
7510
- } catch (_) {}
7532
+ } catch (err) {
7533
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
7534
+ }
7511
7535
 
7512
7536
  if (typeof globalThis.fetch === 'function') {
7513
7537
  return await globalThis.fetch(urlOrReq, init);
@@ -7674,7 +7698,9 @@ function __initVirtualRuntime(rootScope) {
7674
7698
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7675
7699
  try {
7676
7700
  return new AsyncFunction(...argNames, body);
7677
- } catch (_) {}
7701
+ } catch (asyncErr) {
7702
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
7703
+ }
7678
7704
  }
7679
7705
  if (
7680
7706
  err &&
@@ -7702,20 +7728,20 @@ function __initVirtualRuntime(rootScope) {
7702
7728
  }
7703
7729
  }
7704
7730
 
7705
- function raceWithAbort<T = any>(promise: Promise<T>): Promise<T | undefined> {
7706
- if (!promise || typeof (promise as any).then !== 'function') {
7707
- return Promise.resolve(promise as any);
7731
+ function raceWithAbort(promise) {
7732
+ if (!promise || typeof promise.then !== 'function') {
7733
+ return Promise.resolve(promise);
7708
7734
  }
7709
7735
  if (hasExited || isSigintAborted || Boolean(signal && signal.aborted)) {
7710
7736
  if (!hasExited) handleSigint();
7711
- return Promise.resolve(undefined);
7737
+ return Promise.resolve();
7712
7738
  }
7713
7739
 
7714
7740
  // Absorb late rejections after abort to avoid unhandled promise rejection warnings
7715
- (promise as any).catch(() => {});
7741
+ promise.catch(() => {});
7716
7742
 
7717
- return new Promise<T | undefined>((resolve, reject) => {
7718
- let timer: any = null;
7743
+ return new Promise((resolve, reject) => {
7744
+ let timer = null;
7719
7745
  let settled = false;
7720
7746
 
7721
7747
  const cleanup = () => {
@@ -7728,14 +7754,16 @@ function __initVirtualRuntime(rootScope) {
7728
7754
  if (signal && onAbort) {
7729
7755
  try {
7730
7756
  signal.removeEventListener('abort', onAbort);
7731
- } catch (_) {}
7757
+ } catch (err) {
7758
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
7759
+ }
7732
7760
  }
7733
7761
  };
7734
7762
 
7735
7763
  const onAbort = () => {
7736
7764
  cleanup();
7737
7765
  handleSigint();
7738
- resolve(undefined);
7766
+ resolve();
7739
7767
  };
7740
7768
 
7741
7769
  if (signal) {
@@ -7750,7 +7778,7 @@ function __initVirtualRuntime(rootScope) {
7750
7778
  if (remainingMs > 0 && Number.isFinite(remainingMs)) {
7751
7779
  timer = setTimeout(() => {
7752
7780
  cleanup();
7753
- resolve(undefined);
7781
+ resolve();
7754
7782
  }, remainingMs);
7755
7783
  if (timer && typeof timer.unref === 'function') {
7756
7784
  timer.unref();
@@ -7758,11 +7786,11 @@ function __initVirtualRuntime(rootScope) {
7758
7786
  }
7759
7787
 
7760
7788
  promise.then(
7761
- (val: any) => {
7789
+ (val) => {
7762
7790
  cleanup();
7763
7791
  resolve(val);
7764
7792
  },
7765
- (err: any) => {
7793
+ (err) => {
7766
7794
  cleanup();
7767
7795
  reject(err);
7768
7796
  }
@@ -7887,11 +7915,11 @@ function __initVirtualRuntime(rootScope) {
7887
7915
  }
7888
7916
  } finally {
7889
7917
  if (signal && signalListener) {
7890
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
7918
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7891
7919
  }
7892
7920
  if (!hasExited) {
7893
7921
  hasExited = true;
7894
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7922
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7895
7923
  }
7896
7924
  for (const rawId of resourceTracker.allTimers) {
7897
7925
  clearTimeout(rawId);
@@ -7995,11 +8023,21 @@ function __workerMessageLoop(workerScope) {
7995
8023
  };
7996
8024
  }
7997
8025
 
7998
- const _hostRuntime: any = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
7999
-
8000
- _hostRuntime.createWorkerRuntimeSource = function createWorkerRuntimeSource() {
8026
+ function createWorkerRuntimeSource() {
8001
8027
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8002
- };
8028
+ }
8029
+
8030
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
8031
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
8032
+ ? _hostScope.CodeLabLogger.createLogger()
8033
+ : {
8034
+ debug() {},
8035
+ info() {},
8036
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
8037
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
8038
+ };
8039
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8040
+ _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8003
8041
 
8004
8042
  let _cachedWorkerUrl = null;
8005
8043
  let _warmWorker = null;
@@ -8008,7 +8046,7 @@ const _activeWorkerJobs = new Map();
8008
8046
 
8009
8047
  function _ensureWorkerUrl() {
8010
8048
  if (!_cachedWorkerUrl) {
8011
- const blob = new Blob([_hostRuntime.createWorkerRuntimeSource()], { type: 'application/javascript' });
8049
+ const blob = new Blob([createWorkerRuntimeSource()], { type: 'application/javascript' });
8012
8050
  _cachedWorkerUrl = URL.createObjectURL(blob);
8013
8051
  }
8014
8052
  return _cachedWorkerUrl;
@@ -8022,7 +8060,7 @@ function _ensureWarmWorker() {
8022
8060
 
8023
8061
  function _destroyWarmWorker() {
8024
8062
  if (_warmWorker) {
8025
- try { _warmWorker.terminate(); } catch (_) {}
8063
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8026
8064
  _warmWorker = null;
8027
8065
  }
8028
8066
  _warmWorkerBusy = false;
@@ -8077,7 +8115,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8077
8115
 
8078
8116
  function releaseWorker(terminateWorker) {
8079
8117
  if (options.signal && abortListener) {
8080
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
8118
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8081
8119
  abortListener = null;
8082
8120
  }
8083
8121
  _activeWorkerJobs.delete(requestId);
@@ -8092,7 +8130,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8092
8130
  }
8093
8131
  }
8094
8132
  } else {
8095
- try { worker.terminate(); } catch (_) {}
8133
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8096
8134
  }
8097
8135
  }
8098
8136
 
@@ -8228,54 +8266,43 @@ if (typeof module !== 'undefined' && module.exports) {
8228
8266
  }
8229
8267
 
8230
8268
 
8231
- export interface RuntimeExecutionResult {
8232
- ok: boolean;
8233
- exitCode: number;
8234
- durationMs: number;
8235
- stdout: string;
8236
- stderr: string;
8237
- testResults: any[];
8238
- fsSnapshot: any[];
8239
- httpTrace: any[];
8240
- error?: { message: string; stack?: string };
8241
- outputTruncated?: boolean;
8242
- replValue?: any;
8243
- cancelled?: boolean;
8244
- testSummary?: {
8245
- total: number;
8246
- passed: number;
8247
- failed: number;
8248
- };
8249
- }
8250
-
8251
- export const VirtualBuffer: any = _hostRuntime.VirtualBuffer;
8252
- export const VirtualCrypto: any = _hostRuntime.VirtualCrypto;
8253
- export const VirtualZlib: any = _hostRuntime.VirtualZlib;
8254
- export const VirtualPath: any = _hostRuntime.VirtualPath;
8255
- export const VirtualOs: any = _hostRuntime.VirtualOs;
8256
- export const VirtualAssert: any = _hostRuntime.VirtualAssert;
8257
- export const EventEmitter: any = _hostRuntime.EventEmitter;
8258
- export const VirtualUtil: any = _hostRuntime.VirtualUtil;
8259
- export const VirtualUrl: any = _hostRuntime.VirtualUrl;
8260
- export const VirtualQuerystring: any = _hostRuntime.VirtualQuerystring;
8261
- export const VirtualStream: any = _hostRuntime.VirtualStream;
8262
- export const VirtualStreamPromises: any = _hostRuntime.VirtualStreamPromises;
8263
- export const VirtualStringDecoder: any = _hostRuntime.VirtualStringDecoder;
8264
- export const VirtualDns: any = _hostRuntime.VirtualDns;
8265
- export const createVirtualFs: (options?: any) => any = _hostRuntime.createVirtualFs;
8266
- export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _hostRuntime.createVirtualHttp;
8267
- export const createVirtualNet: (portTable?: any) => any = _hostRuntime.createVirtualNet;
8268
- export const transpileTS: (code: string, filename?: string) => string = _hostRuntime.transpileTS;
8269
- export const transpileForBrowser: (source: string, filename?: string) => string = _hostRuntime.transpileForBrowser;
8269
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
8270
+ // The implementation above is a UMD script that attaches itself to the global
8271
+ // object. These aliases give TypeScript consumers named exports without
8272
+ // duplicating the implementation. tools/bundle.js removes this footer before
8273
+ // concatenating the script into the browser bundle.
8274
+ const _runtimeApi: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabRuntime : undefined)
8275
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
8276
+
8277
+ export const VirtualBuffer: any = _runtimeApi.VirtualBuffer;
8278
+ export const VirtualCrypto: any = _runtimeApi.VirtualCrypto;
8279
+ export const VirtualZlib: any = _runtimeApi.VirtualZlib;
8280
+ export const VirtualPath: any = _runtimeApi.VirtualPath;
8281
+ export const VirtualOs: any = _runtimeApi.VirtualOs;
8282
+ export const VirtualAssert: any = _runtimeApi.VirtualAssert;
8283
+ export const EventEmitter: any = _runtimeApi.EventEmitter;
8284
+ export const VirtualUtil: any = _runtimeApi.VirtualUtil;
8285
+ export const VirtualUrl: any = _runtimeApi.VirtualUrl;
8286
+ export const VirtualQuerystring: any = _runtimeApi.VirtualQuerystring;
8287
+ export const VirtualStream: any = _runtimeApi.VirtualStream;
8288
+ export const VirtualStreamPromises: any = _runtimeApi.VirtualStreamPromises;
8289
+ export const VirtualStringDecoder: any = _runtimeApi.VirtualStringDecoder;
8290
+ export const VirtualDns: any = _runtimeApi.VirtualDns;
8291
+ export const createVirtualFs: (options?: any) => any = _runtimeApi.createVirtualFs;
8292
+ export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _runtimeApi.createVirtualHttp;
8293
+ export const createVirtualNet: (portTable?: any) => any = _runtimeApi.createVirtualNet;
8294
+ export const transpileTS: (code: string, filename?: string) => string = _runtimeApi.transpileTS;
8295
+ export const transpileForBrowser: (source: string, filename?: string) => string = _runtimeApi.transpileForBrowser;
8270
8296
  export const preloadNpmPackages: (
8271
8297
  files?: Record<string, any>,
8272
8298
  onProgressOrCache?: ((pkg: string) => void) | Map<string, string>,
8273
8299
  onProgress?: (pkg: string) => void
8274
- ) => Promise<Record<string, string>> = _hostRuntime.preloadNpmPackages;
8275
- export const createVirtualPortTable: () => any = _hostRuntime.createVirtualPortTable;
8276
- export const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInVirtualRuntime;
8277
- export const createWorkerRuntimeSource: () => string = _hostRuntime.createWorkerRuntimeSource;
8278
- export const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean = _hostRuntime.cancelWorkerExecution;
8279
- export const executeInWorker: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInWorker;
8280
-
8281
- export default _hostRuntime;
8300
+ ) => Promise<Record<string, string>> = _runtimeApi.preloadNpmPackages;
8301
+ export const createVirtualPortTable: () => any = _runtimeApi.createVirtualPortTable;
8302
+ export const executeInVirtualRuntime: (options?: any) => Promise<any> = _runtimeApi.executeInVirtualRuntime;
8303
+ const createWorkerRuntimeSourceExport: () => string = _runtimeApi.createWorkerRuntimeSource;
8304
+ export { createWorkerRuntimeSourceExport as createWorkerRuntimeSource };
8305
+ export const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean = _runtimeApi.cancelWorkerExecution;
8306
+ export const executeInWorker: (options?: any) => Promise<any> = _runtimeApi.executeInWorker;
8307
+
8308
+ export default _runtimeApi;
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 v2.0.0
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.8
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
@@ -152,6 +152,9 @@ export const WorkbenchOptionsSchema = z.object({
152
152
  testFile: z.string().optional(),
153
153
  backLabel: z.string().default('Back'),
154
154
  monacoUrl: z.string().optional(),
155
+ previewOrigin: z.string().optional(),
156
+ logger: z.any().optional(),
157
+ debug: z.boolean().optional(),
155
158
  onClose: z.function().returns(z.void()).optional(),
156
159
  onRun: z.function().args(z.any()).returns(z.void()).optional(),
157
160
  onTestResult: z.function().args(z.any()).returns(z.void()).optional(),
@@ -175,3 +178,93 @@ export const WorkbenchOptionsSchema = z.object({
175
178
  });
176
179
 
177
180
  export type WorkbenchOptions = z.infer<typeof WorkbenchOptionsSchema>;
181
+
182
+ // ── 8. Search Options & Match Results ────────────────────────────────────────
183
+
184
+ export const SearchOptionsSchema = z.object({
185
+ query: z.string().default(''),
186
+ caseSensitive: z.boolean().optional().default(false),
187
+ wholeWord: z.boolean().optional().default(false),
188
+ regex: z.boolean().optional().default(false),
189
+ isRegex: z.boolean().optional().default(false),
190
+ include: z.string().optional(),
191
+ includeGlob: z.string().optional(),
192
+ includePattern: z.union([z.string(), z.array(z.string())]).optional(),
193
+ exclude: z.string().optional(),
194
+ excludeGlob: z.string().optional(),
195
+ excludePattern: z.union([z.string(), z.array(z.string())]).optional(),
196
+ maxMatches: z.number().int().positive().optional(),
197
+ maxMatchesPerFile: z.number().int().positive().optional()
198
+ });
199
+
200
+ export type SearchOptions = z.infer<typeof SearchOptionsSchema>;
201
+
202
+ // ── 9. Diagnostic Item & Problems ───────────────────────────────────────────
203
+
204
+ export const DiagnosticSeveritySchema = z.enum(['error', 'warning', 'info', 'hint']);
205
+ export type DiagnosticSeverity = z.infer<typeof DiagnosticSeveritySchema>;
206
+
207
+ export const DiagnosticItemSchema = z.object({
208
+ id: z.string(),
209
+ file: z.string(),
210
+ line: z.number().int(),
211
+ col: z.number().int().optional(),
212
+ column: z.number().int().optional(),
213
+ endLine: z.number().int().optional(),
214
+ endCol: z.number().int().optional(),
215
+ endColumn: z.number().int().optional(),
216
+ message: z.string(),
217
+ severity: DiagnosticSeveritySchema,
218
+ source: z.string().optional(),
219
+ code: z.union([z.string(), z.number()]).optional(),
220
+ tags: z.array(z.string()).optional()
221
+ });
222
+
223
+ export type DiagnosticItem = z.infer<typeof DiagnosticItemSchema>;
224
+
225
+ // ── 10. Stored Project ──────────────────────────────────────────────────────
226
+
227
+ export const StoredProjectSchema = z.object({
228
+ id: z.string(),
229
+ name: z.string(),
230
+ files: z.record(z.string()),
231
+ updatedAt: z.number(),
232
+ createdAt: z.number().optional(),
233
+ entry: z.string().optional(),
234
+ testEntry: z.string().optional(),
235
+ version: z.number().optional()
236
+ });
237
+
238
+ export type StoredProject = z.infer<typeof StoredProjectSchema>;
239
+
240
+ // ── 11. Git File Status & SCM Summary ───────────────────────────────────────
241
+
242
+ export const GitFileChangeTypeSchema = z.enum(['modified', 'added', 'deleted', 'untracked']);
243
+ export type GitFileChangeType = z.infer<typeof GitFileChangeTypeSchema>;
244
+
245
+ export const GitFileStatusSchema = z.object({
246
+ path: z.string(),
247
+ status: GitFileChangeTypeSchema,
248
+ staged: z.boolean(),
249
+ oldContent: z.string().optional(),
250
+ newContent: z.string().optional()
251
+ });
252
+
253
+ export type GitFileStatus = z.infer<typeof GitFileStatusSchema>;
254
+
255
+ export const GitStateSummarySchema = z.object({
256
+ branch: z.string().default('main'),
257
+ headCommit: z.string().optional(),
258
+ branches: z.array(z.string()).default(['main']),
259
+ staged: z.array(GitFileStatusSchema).default([]),
260
+ unstaged: z.array(GitFileStatusSchema).default([]),
261
+ untracked: z.array(GitFileStatusSchema).default([]),
262
+ modified: z.array(GitFileStatusSchema).optional(),
263
+ deleted: z.array(GitFileStatusSchema).optional(),
264
+ hasChanges: z.boolean().default(false),
265
+ isClean: z.boolean().default(true),
266
+ ahead: z.number().int().default(0),
267
+ behind: z.number().int().default(0)
268
+ });
269
+
270
+ export type GitStateSummary = z.infer<typeof GitStateSummarySchema>;