@innovatorved/code-lab 0.3.1 → 0.3.2

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 (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
@@ -341,12 +341,16 @@ async function getCachedAsset(key: string): Promise<Uint8Array | null> {
341
341
  const db = await openToolchainIdb();
342
342
  if (!db) return null;
343
343
  return new Promise((resolve) => {
344
+ const closeDb = () => {
345
+ try { db.close(); } catch (err) { void err; }
346
+ };
344
347
  try {
345
348
  const tx = db.transaction(IDB_STORE, 'readonly');
346
349
  const store = tx.objectStore(IDB_STORE);
347
350
  const req = store.get(key);
348
351
  req.onsuccess = () => {
349
352
  const val = req.result;
353
+ closeDb();
350
354
  if (val instanceof Uint8Array) {
351
355
  memoryAssetCache.set(key, val);
352
356
  resolve(val);
@@ -358,8 +362,12 @@ async function getCachedAsset(key: string): Promise<Uint8Array | null> {
358
362
  resolve(null);
359
363
  }
360
364
  };
361
- req.onerror = () => resolve(null);
365
+ req.onerror = () => {
366
+ closeDb();
367
+ resolve(null);
368
+ };
362
369
  } catch (err) {
370
+ closeDb();
363
371
  if (err) resolve(null);
364
372
  }
365
373
  });
@@ -370,13 +378,23 @@ async function setCachedAsset(key: string, data: Uint8Array): Promise<void> {
370
378
  const db = await openToolchainIdb();
371
379
  if (!db) return;
372
380
  return new Promise((resolve) => {
381
+ const closeDb = () => {
382
+ try { db.close(); } catch (err) { void err; }
383
+ };
373
384
  try {
374
385
  const tx = db.transaction(IDB_STORE, 'readwrite');
375
386
  const store = tx.objectStore(IDB_STORE);
376
387
  store.put(data, key);
377
- tx.oncomplete = () => resolve();
378
- tx.onerror = () => resolve();
388
+ tx.oncomplete = () => {
389
+ closeDb();
390
+ resolve();
391
+ };
392
+ tx.onerror = () => {
393
+ closeDb();
394
+ resolve();
395
+ };
379
396
  } catch (err) {
397
+ closeDb();
380
398
  if (err) resolve();
381
399
  }
382
400
  });
@@ -404,17 +422,21 @@ export function extractTarToVfs(tarBytes: Uint8Array, vfs: any, baseDir = '/'):
404
422
  continue;
405
423
  }
406
424
  const sizeOctal = readString(offset + 124, 12);
407
- const size = parseInt(sizeOctal || '0', 8) || 0;
425
+ const size = Math.max(0, parseInt(sizeOctal || '0', 8) || 0);
408
426
  const typeFlag = tarBytes[offset + 156];
409
427
  const prefix = readString(offset + 345, 155);
410
428
  const fullName = prefix ? `${prefix}/${name}` : name;
411
- const cleanRel = fullName.replace(/^\.?\/+/, '');
412
- const targetPath = baseDir === '/' ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, '')}/${cleanRel}`;
429
+ const rawRel = fullName.replace(/^\.?\/+/, '');
430
+ const rawSegments = rawRel.split('/').filter(Boolean);
431
+ const hasDotDot = rawSegments.some((seg) => seg === '..');
432
+ const cleanRel = hasDotDot ? '' : rawSegments.filter((seg) => seg !== '.').join('/');
433
+ const cleanBase = baseDir === '/' ? '' : baseDir.replace(/\/+$/, '');
434
+ const targetPath = `${cleanBase}/${cleanRel}`;
413
435
 
414
436
  const dataStart = offset + 512;
415
- const dataEnd = dataStart + size;
437
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
416
438
 
417
- if (cleanRel) {
439
+ if (cleanRel && !hasDotDot) {
418
440
  if (typeFlag === 53 || fullName.endsWith('/')) {
419
441
  // Directory ('5')
420
442
  if (!vfs.existsSync(targetPath)) {
@@ -951,10 +973,24 @@ export class CppToolchainManager {
951
973
  message: `Compiling ${sourceFiles.map((s) => s.split('/').pop()).join(', ')} with Clang (${std}, ${optLevel})...`
952
974
  });
953
975
 
976
+ const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
977
+ if (!vfs.existsSync(buildDir)) {
978
+ vfs.mkdirSync(buildDir, { recursive: true });
979
+ }
980
+ const cleanupBuildDir = () => {
981
+ try {
982
+ if (typeof vfs.rmSync === 'function') {
983
+ vfs.rmSync(buildDir, { recursive: true, force: true });
984
+ }
985
+ } catch (err) {
986
+ void err;
987
+ }
988
+ };
989
+
954
990
  const objectFiles: string[] = [];
955
991
  for (let i = 0; i < sourceFiles.length; i++) {
956
992
  const srcPath = sourceFiles[i];
957
- const objPath = `/tmp/obj_${i}.o`;
993
+ const objPath = `${buildDir}/obj_${i}.o`;
958
994
  objectFiles.push(objPath);
959
995
 
960
996
  const clangArgs = [
@@ -992,6 +1028,7 @@ export class CppToolchainManager {
992
1028
  });
993
1029
 
994
1030
  if (compileStep.exitCode !== 0) {
1031
+ cleanupBuildDir();
995
1032
  return {
996
1033
  ok: false,
997
1034
  exitCode: compileStep.exitCode,
@@ -1034,6 +1071,7 @@ export class CppToolchainManager {
1034
1071
  onStdout: handleOut,
1035
1072
  onStderr: handleErr
1036
1073
  });
1074
+ cleanupBuildDir();
1037
1075
 
1038
1076
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
1039
1077
  return {
@@ -791,77 +791,82 @@ export class PythonToolchainManager {
791
791
  if (this._loadingPromise) return this._loadingPromise;
792
792
 
793
793
  this._loadingPromise = (async () => {
794
- this._emitProgress({
795
- stage: 'downloading',
796
- percent: 10,
797
- message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
798
- });
799
-
800
- // Browser environment: load pyodide.js from CDN
801
- if (typeof window !== 'undefined') {
802
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
803
- if (!(window as any).loadPyodide) {
804
- await new Promise<void>((resolve, reject) => {
805
- const script = document.createElement('script');
806
- script.src = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
807
- script.onload = () => resolve();
808
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
809
- document.head.appendChild(script);
810
- });
811
- }
812
-
794
+ try {
813
795
  this._emitProgress({
814
- stage: 'extracting',
815
- percent: 50,
816
- message: 'Bootstrapping Python runtime environment...'
796
+ stage: 'downloading',
797
+ percent: 10,
798
+ message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
817
799
  });
818
800
 
819
- const loadPyodideFn = (window as any).loadPyodide;
820
- this.pyodide = await loadPyodideFn({
821
- indexURL: cdn
822
- });
823
- } else {
824
- // Node / Bun headless mock toolchain for hermetic offline test runs
825
- this.pyodide = {
826
- FS: {
827
- files: new Map<string, string>(),
828
- writeFile(p: string, content: any) {
829
- this.files.set(p, typeof content === 'string' ? content : String(content));
830
- },
831
- readFile(p: string, opts?: any) {
832
- return this.files.get(p) || '';
833
- },
834
- unlink(p: string) {
835
- this.files.delete(p);
836
- },
837
- mkdirTree(_p: string) {}
838
- },
839
- runPythonAsync: async (code: string) => {
840
- return `Execution mock: ${code.slice(0, 30)}`;
801
+ // Browser environment: load pyodide.js from CDN
802
+ if (typeof window !== 'undefined') {
803
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
804
+ if (!(window as any).loadPyodide) {
805
+ await new Promise<void>((resolve, reject) => {
806
+ const script = document.createElement('script');
807
+ script.src = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
808
+ script.onload = () => resolve();
809
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
810
+ document.head.appendChild(script);
811
+ });
841
812
  }
842
- };
843
- }
844
813
 
845
- // Preload specified packages if any
846
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
847
- for (const pkg of this.options.preloadPackages) {
848
- try {
849
- if (typeof this.pyodide.loadPackage === 'function') {
850
- await this.pyodide.loadPackage(pkg);
814
+ this._emitProgress({
815
+ stage: 'extracting',
816
+ percent: 50,
817
+ message: 'Bootstrapping Python runtime environment...'
818
+ });
819
+
820
+ const loadPyodideFn = (window as any).loadPyodide;
821
+ this.pyodide = await loadPyodideFn({
822
+ indexURL: cdn
823
+ });
824
+ } else {
825
+ // Node / Bun headless mock toolchain for hermetic offline test runs
826
+ this.pyodide = {
827
+ FS: {
828
+ files: new Map<string, string>(),
829
+ writeFile(p: string, content: any) {
830
+ this.files.set(p, typeof content === 'string' ? content : String(content));
831
+ },
832
+ readFile(p: string, opts?: any) {
833
+ return this.files.get(p) || '';
834
+ },
835
+ unlink(p: string) {
836
+ this.files.delete(p);
837
+ },
838
+ mkdirTree(_p: string) {}
839
+ },
840
+ runPythonAsync: async (code: string) => {
841
+ return `Execution mock: ${code.slice(0, 30)}`;
842
+ }
843
+ };
844
+ }
845
+
846
+ // Preload specified packages if any
847
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
848
+ for (const pkg of this.options.preloadPackages) {
849
+ try {
850
+ if (typeof this.pyodide.loadPackage === 'function') {
851
+ await this.pyodide.loadPackage(pkg);
852
+ }
853
+ } catch (err) {
854
+ void err;
851
855
  }
852
- } catch (err) {
853
- void err;
854
856
  }
855
857
  }
856
- }
857
858
 
858
- this._emitProgress({
859
- stage: 'ready',
860
- percent: 100,
861
- message: 'Python 3.12 WebAssembly Toolchain Ready'
862
- });
859
+ this._emitProgress({
860
+ stage: 'ready',
861
+ percent: 100,
862
+ message: 'Python 3.12 WebAssembly Toolchain Ready'
863
+ });
863
864
 
864
- return this.pyodide;
865
+ return this.pyodide;
866
+ } catch (err) {
867
+ this._loadingPromise = null;
868
+ throw err;
869
+ }
865
870
  })();
866
871
 
867
872
  return this._loadingPromise;
@@ -919,21 +924,38 @@ export class PythonToolchainManager {
919
924
 
920
925
  const pyodide = await this.ensureLoaded();
921
926
 
922
- // 1. Sync VFS files into Pyodide FS
927
+ // 1. Sync VFS files into Pyodide FS (recursively traversing subdirectories)
923
928
  if (req.vfs && pyodide.FS) {
924
- try {
925
- const vfsEntries = req.vfs.readdirSync('/workspace', { recursive: true });
926
- for (const entry of vfsEntries) {
927
- const fullPath = `/workspace/${entry}`;
928
- if (!req.vfs.statSync(fullPath).isDirectory()) {
929
- const content = req.vfs.readFileSync(fullPath, 'utf8');
930
- pyodide.FS.mkdirTree('/workspace');
931
- pyodide.FS.writeFile(fullPath, content);
929
+ const syncVfsDir = (dirPath: string) => {
930
+ try {
931
+ if (typeof pyodide.FS.mkdirTree === 'function') {
932
+ pyodide.FS.mkdirTree(dirPath);
933
+ }
934
+ const entries = req.vfs.readdirSync(dirPath);
935
+ for (const entry of entries) {
936
+ if (!entry || entry === '.' || entry === '..') continue;
937
+ const fullPath = `${dirPath === '/' ? '' : dirPath}/${entry}`;
938
+ try {
939
+ const st = req.vfs.statSync(fullPath);
940
+ if (st && typeof st.isDirectory === 'function' && st.isDirectory()) {
941
+ syncVfsDir(fullPath);
942
+ } else {
943
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf('/')) || '/workspace';
944
+ if (typeof pyodide.FS.mkdirTree === 'function') {
945
+ pyodide.FS.mkdirTree(parentDir);
946
+ }
947
+ const content = req.vfs.readFileSync(fullPath, 'utf8');
948
+ pyodide.FS.writeFile(fullPath, content);
949
+ }
950
+ } catch (err) {
951
+ void err;
952
+ }
932
953
  }
954
+ } catch (err) {
955
+ void err;
933
956
  }
934
- } catch (err) {
935
- void err;
936
- }
957
+ };
958
+ syncVfsDir('/workspace');
937
959
  }
938
960
 
939
961
  // Seed builtin /usr/lib/python modules
@@ -986,47 +1008,19 @@ export class PythonToolchainManager {
986
1008
  });
987
1009
  }
988
1010
 
989
- const rawLines = codeToRun.split('\n');
990
- const futureImports: string[] = [];
991
- const bodyLines: string[] = [];
992
- let inDocstring = false;
993
- let docChar = '';
994
-
995
- for (const l of rawLines) {
996
- const t = l.trim();
997
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
998
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
999
- bodyLines.push(l);
1000
- continue;
1001
- }
1002
- inDocstring = true;
1003
- docChar = t.slice(0, 3);
1004
- bodyLines.push(l);
1005
- continue;
1006
- }
1007
- if (inDocstring) {
1008
- if (t.endsWith(docChar)) inDocstring = false;
1009
- bodyLines.push(l);
1010
- continue;
1011
- }
1012
- if (/^from\s+__future__\s+import\s+/.test(t)) {
1013
- futureImports.push(t);
1014
- } else {
1015
- bodyLines.push(l);
1016
- }
1017
- }
1018
-
1011
+ const fileLabel = JSON.stringify(req.entry || '<exec>');
1012
+ const encodedCode = JSON.stringify(codeToRun);
1019
1013
  const runnerWrapper = `
1020
- ${futureImports.join('\n')}
1021
1014
  import sys, tracemalloc
1022
1015
  if '/usr/lib/python' not in sys.path:
1023
1016
  sys.path.insert(0, '/usr/lib/python')
1024
1017
  if '/workspace' not in sys.path:
1025
1018
  sys.path.insert(0, '/workspace')
1026
1019
 
1020
+ _cl_user_code = ${encodedCode}
1027
1021
  tracemalloc.start()
1028
1022
  try:
1029
- ${bodyLines.map((l) => ' ' + l).join('\n')}
1023
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
1030
1024
  finally:
1031
1025
  _, _peak = tracemalloc.get_traced_memory()
1032
1026
  tracemalloc.stop()
@@ -1069,24 +1063,42 @@ finally:
1069
1063
  }
1070
1064
  }
1071
1065
 
1072
- // 2. Sync back files from Pyodide FS into VFS
1066
+ // 2. Sync back files from Pyodide FS into VFS (recursively traversing subdirectories)
1073
1067
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === 'function') {
1074
- try {
1075
- const files = pyodide.FS.readdir('/workspace');
1076
- for (const f of files) {
1077
- if (f !== '.' && f !== '..') {
1078
- const p = `/workspace/${f}`;
1068
+ const syncBackPyodideDir = (dirPath: string) => {
1069
+ try {
1070
+ const entries = pyodide.FS.readdir(dirPath);
1071
+ for (const f of entries) {
1072
+ if (!f || f === '.' || f === '..') continue;
1073
+ const p = `${dirPath}/${f}`;
1079
1074
  try {
1080
- const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1081
- req.vfs.writeFileSync(p, content);
1075
+ let isDir = false;
1076
+ if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1077
+ const st = pyodide.FS.stat(p);
1078
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
1079
+ }
1080
+ if (isDir) {
1081
+ if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(p)) {
1082
+ req.vfs.mkdirSync(p, { recursive: true });
1083
+ }
1084
+ syncBackPyodideDir(p);
1085
+ } else {
1086
+ const parentDir = p.slice(0, p.lastIndexOf('/')) || '/workspace';
1087
+ if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(parentDir)) {
1088
+ req.vfs.mkdirSync(parentDir, { recursive: true });
1089
+ }
1090
+ const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1091
+ req.vfs.writeFileSync(p, content);
1092
+ }
1082
1093
  } catch (err) {
1083
1094
  void err;
1084
1095
  }
1085
1096
  }
1097
+ } catch (err) {
1098
+ void err;
1086
1099
  }
1087
- } catch (err) {
1088
- void err;
1089
- }
1100
+ };
1101
+ syncBackPyodideDir('/workspace');
1090
1102
  }
1091
1103
 
1092
1104
  const durationMs = performance.now() - start;
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.3.1
2
+ * @innovatorved/code-lab v0.3.2
3
3
  * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, WASI C++20 Toolchain, Python 3.12 WebAssembly, and Git Engine.
4
4
  */
5
5
 
package/src/preview-sw.js CHANGED
@@ -58,6 +58,8 @@ self.addEventListener('activate', (event) => {
58
58
  self.addEventListener('message', (event) => {
59
59
  const data = event && event.data;
60
60
  if (!data || data.type !== 'codelab:config') return;
61
+ // Reject configuration attempts originating from preview tabs/frames themselves.
62
+ if (event.source && event.source.url && /\/__preview\//.test(event.source.url)) return;
61
63
  const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
62
64
  if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
63
65
  configuredCsp = csp;
@@ -80,10 +82,15 @@ function parsePreviewPath(pathname) {
80
82
  return { port: Number(match[1]), path: match[2] || '/' };
81
83
  }
82
84
 
85
+ function escapeMetaAttr(val) {
86
+ return String(val || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
87
+ }
88
+
83
89
  function previewErrorResponse(status, title, message) {
84
90
  const csp = previewPolicy();
91
+ const safeCsp = escapeMetaAttr(csp);
85
92
  const body = `<!doctype html><meta charset="utf-8">` +
86
- `<meta http-equiv="Content-Security-Policy" content="${csp}">` +
93
+ `<meta http-equiv="Content-Security-Policy" content="${safeCsp}">` +
87
94
  `<title>${title}</title>` +
88
95
  `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
89
96
  `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
@@ -100,14 +107,15 @@ function previewErrorResponse(status, title, message) {
100
107
  /** Inject the policy, a base URL and the sandbox shims into an HTML response. */
101
108
  function injectPreviewHead(html, port) {
102
109
  const csp = previewPolicy();
110
+ const safeCsp = escapeMetaAttr(csp);
103
111
  const shims = previewShims();
104
112
  const tags = [];
105
113
  const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
106
114
  const hasBase = /<base\b/i.test(html);
107
115
  const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
108
116
 
109
- if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
110
- if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
117
+ if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${safeCsp}">`);
118
+ if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${Number(port) || 3000}/">`);
111
119
  if (!hasShims && shims) tags.push(shims);
112
120
  if (tags.length === 0) return html;
113
121
 
@@ -123,7 +131,8 @@ function injectPreviewHead(html, port) {
123
131
 
124
132
  async function proxyVirtualRequest(event, port, targetPath) {
125
133
  const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
126
- if (!clients || !clients.length) {
134
+ const workbenchClients = (clients || []).filter((c) => !c.url || !/\/__preview\//.test(c.url));
135
+ if (!workbenchClients.length) {
127
136
  return previewErrorResponse(
128
137
  503,
129
138
  'No active CodeLab workbench',
@@ -131,7 +140,7 @@ async function proxyVirtualRequest(event, port, targetPath) {
131
140
  );
132
141
  }
133
142
 
134
- const client = clients[0];
143
+ const client = workbenchClients[0];
135
144
  const channel = new MessageChannel();
136
145
  const request = event.request;
137
146
  const method = request.method || 'GET';
@@ -187,6 +196,17 @@ async function proxyVirtualRequest(event, port, targetPath) {
187
196
  const responseHeaders = new Headers((response && response.headers) || {});
188
197
  const contentType = responseHeaders.get('content-type') || '';
189
198
 
199
+ // Decode Uint8Array / ArrayBuffer HTML bodies so head injection always applies.
200
+ if (/text\/html/i.test(contentType) && responseBody && typeof responseBody !== 'string') {
201
+ try {
202
+ if (responseBody instanceof ArrayBuffer || ArrayBuffer.isView(responseBody)) {
203
+ responseBody = new TextDecoder('utf-8').decode(responseBody);
204
+ }
205
+ } catch (err) {
206
+ console.warn('[code-lab] preview-sw: failed to decode HTML buffer', err);
207
+ }
208
+ }
209
+
190
210
  // Inject the policy and a <base> so relative asset URLs in HTML responses
191
211
  // resolve under the `/__preview/:port/` namespace rather than the host root.
192
212
  if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {