@innovatorved/code-lab 0.3.2 → 0.4.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.
Files changed (155) hide show
  1. package/ARCHITECTURE.md +5 -3
  2. package/CHANGELOG.md +20 -0
  3. package/README.md +70 -168
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +246 -0
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +34265 -18104
  12. package/dist/code-lab.js +33186 -17053
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/extensions/cpp.esm.js +19478 -3760
  15. package/dist/extensions/cpp.js +19475 -3757
  16. package/dist/extensions/guided-lab.esm.js +19401 -3725
  17. package/dist/extensions/guided-lab.js +19400 -3724
  18. package/dist/extensions/python.d.ts +1 -0
  19. package/dist/extensions/python.esm.js +19576 -3766
  20. package/dist/extensions/python.js +19576 -3766
  21. package/dist/extensions/umbrella.d.ts +5 -0
  22. package/dist/index.d.ts +1 -1
  23. package/dist/modular-kernel.d.ts +11 -0
  24. package/dist/packages/commands/src/index.d.ts +96 -0
  25. package/dist/packages/core/src/di.d.ts +36 -0
  26. package/dist/packages/core/src/disposable.d.ts +27 -0
  27. package/dist/packages/core/src/errors.d.ts +69 -0
  28. package/dist/packages/core/src/events.d.ts +38 -0
  29. package/dist/packages/core/src/index.d.ts +6 -0
  30. package/dist/packages/core/src/path.d.ts +14 -0
  31. package/dist/packages/core/src/registry.d.ts +23 -0
  32. package/dist/packages/editor/src/index.d.ts +118 -0
  33. package/dist/packages/fs/src/backends.d.ts +37 -0
  34. package/dist/packages/fs/src/index.d.ts +3 -0
  35. package/dist/packages/fs/src/types.d.ts +40 -0
  36. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  37. package/dist/packages/preview/src/index.d.ts +34 -0
  38. package/dist/packages/runtime/src/index.d.ts +47 -0
  39. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  40. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  41. package/dist/packages/settings/src/index.d.ts +4 -0
  42. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  43. package/dist/packages/settings/src/schema.d.ts +28 -0
  44. package/dist/packages/sql/src/completions.d.ts +8 -0
  45. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  46. package/dist/packages/sql/src/formatter.d.ts +2 -0
  47. package/dist/packages/sql/src/index.d.ts +7 -0
  48. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  49. package/dist/packages/sql/src/styles.d.ts +2 -0
  50. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  51. package/dist/packages/sql/src/types.d.ts +130 -0
  52. package/dist/packages/terminal/src/index.d.ts +54 -0
  53. package/dist/packages/ui/src/index.d.ts +4 -0
  54. package/dist/packages/ui/src/observability.d.ts +22 -0
  55. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  56. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  57. package/dist/packages/ui/src/themes.d.ts +35 -0
  58. package/dist/preview-sw.js +53 -12
  59. package/dist/runtime.d.ts +3 -3
  60. package/dist/runtime.esm.js +467 -44
  61. package/dist/runtime.js +465 -44
  62. package/dist/schemas.d.ts +234 -814
  63. package/dist/schemas.esm.js +19401 -3725
  64. package/dist/schemas.js +19404 -3728
  65. package/dist/shell.d.ts +1 -1
  66. package/dist/shell.esm.js +364 -39
  67. package/dist/shell.js +364 -39
  68. package/dist/terminal.esm.js +62 -3
  69. package/dist/terminal.js +62 -3
  70. package/dist/workbench/diff-editor.d.ts +1 -0
  71. package/package.json +37 -8
  72. package/packages/commands/README.md +7 -0
  73. package/packages/commands/package.json +16 -0
  74. package/packages/commands/src/index.ts +467 -0
  75. package/packages/commands/tsconfig.json +22 -0
  76. package/packages/core/README.md +12 -0
  77. package/packages/core/package.json +13 -0
  78. package/packages/core/src/di.ts +147 -0
  79. package/packages/core/src/disposable.ts +112 -0
  80. package/packages/core/src/errors.ts +205 -0
  81. package/packages/core/src/events.ts +157 -0
  82. package/packages/core/src/index.ts +49 -0
  83. package/packages/core/src/path.ts +118 -0
  84. package/packages/core/src/registry.ts +61 -0
  85. package/packages/core/tsconfig.json +19 -0
  86. package/packages/editor/README.md +9 -0
  87. package/packages/editor/package.json +18 -0
  88. package/packages/editor/src/index.ts +344 -0
  89. package/packages/editor/tsconfig.json +24 -0
  90. package/packages/fs/README.md +7 -0
  91. package/packages/fs/package.json +16 -0
  92. package/packages/fs/src/backends.ts +301 -0
  93. package/packages/fs/src/index.ts +18 -0
  94. package/packages/fs/src/types.ts +44 -0
  95. package/packages/fs/src/vfs-service.ts +257 -0
  96. package/packages/fs/tsconfig.json +22 -0
  97. package/packages/preview/README.md +3 -0
  98. package/packages/preview/package.json +16 -0
  99. package/packages/preview/src/index.ts +125 -0
  100. package/packages/preview/tsconfig.json +22 -0
  101. package/packages/runtime/README.md +3 -0
  102. package/packages/runtime/package.json +17 -0
  103. package/packages/runtime/src/index.ts +134 -0
  104. package/packages/runtime/tsconfig.json +23 -0
  105. package/packages/settings/README.md +7 -0
  106. package/packages/settings/package.json +16 -0
  107. package/packages/settings/src/builtin-schemas.ts +235 -0
  108. package/packages/settings/src/configuration-service.ts +543 -0
  109. package/packages/settings/src/index.ts +37 -0
  110. package/packages/settings/src/jsonc.ts +189 -0
  111. package/packages/settings/src/schema.ts +164 -0
  112. package/packages/settings/tsconfig.json +22 -0
  113. package/packages/sql/README.md +12 -0
  114. package/packages/sql/package.json +13 -0
  115. package/packages/sql/src/completions.ts +359 -0
  116. package/packages/sql/src/diagnostics.ts +200 -0
  117. package/packages/sql/src/formatter.ts +271 -0
  118. package/packages/sql/src/index.ts +54 -0
  119. package/packages/sql/src/sql-editor.ts +802 -0
  120. package/packages/sql/src/styles.ts +501 -0
  121. package/packages/sql/src/tokenizer.ts +457 -0
  122. package/packages/sql/src/types.ts +148 -0
  123. package/packages/sql/tsconfig.json +19 -0
  124. package/packages/terminal/README.md +3 -0
  125. package/packages/terminal/package.json +16 -0
  126. package/packages/terminal/src/index.ts +183 -0
  127. package/packages/terminal/tsconfig.json +22 -0
  128. package/packages/ui/README.md +8 -0
  129. package/packages/ui/package.json +18 -0
  130. package/packages/ui/src/index.ts +36 -0
  131. package/packages/ui/src/observability.ts +175 -0
  132. package/packages/ui/src/plugin-registry.ts +274 -0
  133. package/packages/ui/src/settings-dialog.ts +293 -0
  134. package/packages/ui/src/themes.ts +174 -0
  135. package/packages/ui/tsconfig.json +24 -0
  136. package/src/code-lab.css +246 -0
  137. package/src/extensions/cpp.ts +58 -15
  138. package/src/extensions/python.ts +156 -24
  139. package/src/extensions/umbrella.ts +5 -0
  140. package/src/index.ts +1 -1
  141. package/src/modular-kernel.ts +11 -0
  142. package/src/preview-sw.js +52 -11
  143. package/src/runtime.ts +466 -46
  144. package/src/schemas.ts +62 -62
  145. package/src/shell.ts +363 -39
  146. package/src/terminal.ts +60 -2
  147. package/src/workbench/diff-editor.ts +66 -6
  148. package/src/workbench/icons.ts +5 -2
  149. package/src/workbench.ts +2410 -220
  150. package/dist/runtime/index.d.ts +0 -4
  151. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  152. package/dist/shell/index.d.ts +0 -4
  153. package/src/runtime/index.ts +0 -5
  154. package/src/shell/coreutils/compilers-cli.ts +0 -103
  155. package/src/shell/index.ts +0 -5
@@ -194,6 +194,13 @@ def ASSERT_NE(actual: Any, expected: Any, msg: str = None):
194
194
  def CODELAB_TEST_EXIT_CODE() -> int:
195
195
  return 0 if _FAILED_COUNT == 0 else 1
196
196
 
197
+ def _reset_codelab_test() -> None:
198
+ global _SUITE_NAME, _PASSED_COUNT, _FAILED_COUNT, _TOTAL_COUNT
199
+ _SUITE_NAME = "Default Test Suite"
200
+ _PASSED_COUNT = 0
201
+ _FAILED_COUNT = 0
202
+ _TOTAL_COUNT = 0
203
+
197
204
  from contextlib import contextmanager
198
205
 
199
206
  @contextmanager
@@ -786,6 +793,8 @@ export class PythonToolchainManager {
786
793
  }
787
794
  }
788
795
 
796
+ private static _scriptPromises = new Map<string, Promise<void>>();
797
+
789
798
  public async ensureLoaded(): Promise<any> {
790
799
  if (this.pyodide) return this.pyodide;
791
800
  if (this._loadingPromise) return this._loadingPromise;
@@ -798,17 +807,34 @@ export class PythonToolchainManager {
798
807
  message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
799
808
  });
800
809
 
801
- // Browser environment: load pyodide.js from CDN
802
- if (typeof window !== 'undefined') {
810
+ // Browser environment: load pyodide.js from CDN (deduplicated across concurrent instances)
811
+ if (typeof window !== 'undefined' && typeof document !== 'undefined' && !(this.options as any).headlessMock) {
803
812
  const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
813
+ const scriptUrl = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
804
814
  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
- });
815
+ let scriptPromise = PythonToolchainManager._scriptPromises.get(scriptUrl);
816
+ if (!scriptPromise) {
817
+ scriptPromise = new Promise<void>((resolve, reject) => {
818
+ const existing = typeof document.querySelector === 'function'
819
+ ? document.querySelector(`script[data-codelab-pyodide="${scriptUrl}"]`) as HTMLScriptElement | null
820
+ : null;
821
+ if (existing && (window as any).loadPyodide) {
822
+ resolve();
823
+ return;
824
+ }
825
+ const script = document.createElement('script');
826
+ script.src = scriptUrl;
827
+ script.setAttribute('data-codelab-pyodide', scriptUrl);
828
+ script.onload = () => resolve();
829
+ script.onerror = () => {
830
+ PythonToolchainManager._scriptPromises.delete(scriptUrl);
831
+ reject(new Error(`Failed to load pyodide.js from ${scriptUrl}`));
832
+ };
833
+ document.head.appendChild(script);
834
+ });
835
+ PythonToolchainManager._scriptPromises.set(scriptUrl, scriptPromise);
836
+ }
837
+ await scriptPromise;
812
838
  }
813
839
 
814
840
  this._emitProgress({
@@ -822,20 +848,73 @@ export class PythonToolchainManager {
822
848
  indexURL: cdn
823
849
  });
824
850
  } else {
825
- // Node / Bun headless mock toolchain for hermetic offline test runs
851
+ // Node / Bun headless mock toolchain for hermetic offline test runs (binary-safe)
852
+ const dirs = new Set<string>(['/', '/workspace', '/usr', '/usr/lib', '/usr/lib/python']);
853
+ const files = new Map<string, Uint8Array>();
854
+ const encoder = new TextEncoder();
855
+ const decoder = new TextDecoder('utf-8', { fatal: false });
856
+ const ensureDirs = (p: string) => {
857
+ const parts = p.split('/').filter(Boolean);
858
+ let cur = '';
859
+ for (const seg of parts) {
860
+ cur += '/' + seg;
861
+ dirs.add(cur);
862
+ }
863
+ };
826
864
  this.pyodide = {
827
865
  FS: {
828
- files: new Map<string, string>(),
866
+ files,
867
+ dirs,
868
+ mkdirTree(p: string) {
869
+ ensureDirs(p);
870
+ },
829
871
  writeFile(p: string, content: any) {
830
- this.files.set(p, typeof content === 'string' ? content : String(content));
872
+ const slashIdx = p.lastIndexOf('/');
873
+ if (slashIdx > 0) ensureDirs(p.slice(0, slashIdx));
874
+ if (content instanceof Uint8Array) {
875
+ files.set(p, content.slice());
876
+ } else if (ArrayBuffer.isView(content)) {
877
+ files.set(p, new Uint8Array(content.buffer, content.byteOffset, content.byteLength).slice());
878
+ } else {
879
+ files.set(p, encoder.encode(typeof content === 'string' ? content : String(content ?? '')));
880
+ }
831
881
  },
832
882
  readFile(p: string, opts?: any) {
833
- return this.files.get(p) || '';
883
+ const raw = files.get(p);
884
+ if (!raw) return opts && opts.encoding === 'utf8' ? '' : new Uint8Array(0);
885
+ if (opts && opts.encoding === 'utf8') {
886
+ return decoder.decode(raw);
887
+ }
888
+ return raw.slice();
834
889
  },
835
890
  unlink(p: string) {
836
- this.files.delete(p);
891
+ files.delete(p);
837
892
  },
838
- mkdirTree(_p: string) {}
893
+ readdir(dirPath: string) {
894
+ const prefix = dirPath === '/' ? '/' : dirPath.replace(/\/+$/, '') + '/';
895
+ const children = new Set<string>(['.', '..']);
896
+ for (const d of dirs) {
897
+ if (d.startsWith(prefix)) {
898
+ const rest = d.slice(prefix.length);
899
+ if (rest && !rest.includes('/')) children.add(rest);
900
+ }
901
+ }
902
+ for (const f of files.keys()) {
903
+ if (f.startsWith(prefix)) {
904
+ const rest = f.slice(prefix.length);
905
+ if (rest && !rest.includes('/')) children.add(rest);
906
+ }
907
+ }
908
+ return Array.from(children);
909
+ },
910
+ stat(p: string) {
911
+ if (dirs.has(p)) return { mode: 0o040755 };
912
+ if (files.has(p)) return { mode: 0o100644 };
913
+ throw new Error(`ENOENT: ${p}`);
914
+ },
915
+ isDir(mode: number) {
916
+ return (mode & 0o170000) === 0o040000;
917
+ }
839
918
  },
840
919
  runPythonAsync: async (code: string) => {
841
920
  return `Execution mock: ${code.slice(0, 30)}`;
@@ -924,7 +1003,8 @@ export class PythonToolchainManager {
924
1003
 
925
1004
  const pyodide = await this.ensureLoaded();
926
1005
 
927
- // 1. Sync VFS files into Pyodide FS (recursively traversing subdirectories)
1006
+ // 1. Sync VFS files into Pyodide FS (binary-safe + prune files deleted in VFS)
1007
+ const vfsSnapshotFiles = new Set<string>();
928
1008
  if (req.vfs && pyodide.FS) {
929
1009
  const syncVfsDir = (dirPath: string) => {
930
1010
  try {
@@ -944,8 +1024,9 @@ export class PythonToolchainManager {
944
1024
  if (typeof pyodide.FS.mkdirTree === 'function') {
945
1025
  pyodide.FS.mkdirTree(parentDir);
946
1026
  }
947
- const content = req.vfs.readFileSync(fullPath, 'utf8');
948
- pyodide.FS.writeFile(fullPath, content);
1027
+ const rawContent = req.vfs.readFileSync(fullPath);
1028
+ pyodide.FS.writeFile(fullPath, rawContent);
1029
+ vfsSnapshotFiles.add(fullPath);
949
1030
  }
950
1031
  } catch (err) {
951
1032
  void err;
@@ -956,6 +1037,39 @@ export class PythonToolchainManager {
956
1037
  }
957
1038
  };
958
1039
  syncVfsDir('/workspace');
1040
+
1041
+ // Prune stale files in Pyodide FS that no longer exist in VFS before execution
1042
+ if (typeof pyodide.FS.readdir === 'function' && typeof pyodide.FS.unlink === 'function') {
1043
+ const pruneStalePyodideFiles = (dirPath: string) => {
1044
+ try {
1045
+ const pyEntries = pyodide.FS.readdir(dirPath);
1046
+ for (const f of pyEntries) {
1047
+ if (!f || f === '.' || f === '..') continue;
1048
+ const p = `${dirPath}/${f}`;
1049
+ let isDir = false;
1050
+ if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1051
+ try {
1052
+ isDir = Boolean(pyodide.FS.isDir(pyodide.FS.stat(p).mode));
1053
+ } catch (err) {
1054
+ void err;
1055
+ }
1056
+ }
1057
+ if (isDir) {
1058
+ pruneStalePyodideFiles(p);
1059
+ } else if (!vfsSnapshotFiles.has(p)) {
1060
+ try {
1061
+ pyodide.FS.unlink(p);
1062
+ } catch (err) {
1063
+ void err;
1064
+ }
1065
+ }
1066
+ }
1067
+ } catch (err) {
1068
+ void err;
1069
+ }
1070
+ };
1071
+ pruneStalePyodideFiles('/workspace');
1072
+ }
959
1073
  }
960
1074
 
961
1075
  // Seed builtin /usr/lib/python modules
@@ -1016,11 +1130,14 @@ if '/usr/lib/python' not in sys.path:
1016
1130
  sys.path.insert(0, '/usr/lib/python')
1017
1131
  if '/workspace' not in sys.path:
1018
1132
  sys.path.insert(0, '/workspace')
1133
+ if 'codelab_test' in sys.modules and hasattr(sys.modules['codelab_test'], '_reset_codelab_test'):
1134
+ sys.modules['codelab_test']._reset_codelab_test()
1019
1135
 
1020
1136
  _cl_user_code = ${encodedCode}
1137
+ _cl_ns = {'__name__': '__main__', '__file__': ${fileLabel}, '__builtins__': __builtins__}
1021
1138
  tracemalloc.start()
1022
1139
  try:
1023
- exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
1140
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), _cl_ns)
1024
1141
  finally:
1025
1142
  _, _peak = tracemalloc.get_traced_memory()
1026
1143
  tracemalloc.stop()
@@ -1063,8 +1180,9 @@ finally:
1063
1180
  }
1064
1181
  }
1065
1182
 
1066
- // 2. Sync back files from Pyodide FS into VFS (recursively traversing subdirectories)
1183
+ // 2. Sync back files from Pyodide FS into VFS (binary-safe + propagate Python deletions)
1067
1184
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === 'function') {
1185
+ const pyFilesAfter = new Set<string>();
1068
1186
  const syncBackPyodideDir = (dirPath: string) => {
1069
1187
  try {
1070
1188
  const entries = pyodide.FS.readdir(dirPath);
@@ -1087,8 +1205,9 @@ finally:
1087
1205
  if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(parentDir)) {
1088
1206
  req.vfs.mkdirSync(parentDir, { recursive: true });
1089
1207
  }
1090
- const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1091
- req.vfs.writeFileSync(p, content);
1208
+ const rawBytes = pyodide.FS.readFile(p);
1209
+ req.vfs.writeFileSync(p, rawBytes);
1210
+ pyFilesAfter.add(p);
1092
1211
  }
1093
1212
  } catch (err) {
1094
1213
  void err;
@@ -1099,6 +1218,18 @@ finally:
1099
1218
  }
1100
1219
  };
1101
1220
  syncBackPyodideDir('/workspace');
1221
+
1222
+ if (typeof req.vfs.unlinkSync === 'function') {
1223
+ for (const existedBefore of vfsSnapshotFiles) {
1224
+ if (!pyFilesAfter.has(existedBefore)) {
1225
+ try {
1226
+ req.vfs.unlinkSync(existedBefore);
1227
+ } catch (err) {
1228
+ void err;
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1102
1233
  }
1103
1234
 
1104
1235
  const durationMs = performance.now() - start;
@@ -1229,8 +1360,9 @@ function installPythonExtension(workbench: any, options: ExtendedPythonExtension
1229
1360
  for (const d of diags) {
1230
1361
  workbench._diagnosticsStore.add(d);
1231
1362
  }
1232
- if (typeof window !== 'undefined' && (window as any).monaco && workbench.editor) {
1233
- const model = workbench.editor.getModel();
1363
+ if (typeof window !== 'undefined' && (window as any).monaco) {
1364
+ const model = (workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file))
1365
+ || (workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
1234
1366
  if (model) {
1235
1367
  const markers = diags.map((d) => ({
1236
1368
  startLineNumber: d.line,
@@ -0,0 +1,5 @@
1
+ export { guidedLabExtension } from './guided-lab';
2
+ export { javascriptExtension } from './javascript';
3
+ export { typescriptExtension } from './typescript';
4
+ export { cppExtension } from './cpp';
5
+ export { pythonExtension } from './python';
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.3.2
2
+ * @innovatorved/code-lab v0.4.0
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
 
@@ -0,0 +1,11 @@
1
+ export * from '../packages/core/src/index';
2
+ export * from '../packages/fs/src/index';
3
+ export * from '../packages/settings/src/index';
4
+ export * from '../packages/commands/src/index';
5
+ export * from '../packages/sql/src/index';
6
+ export * from '../packages/editor/src/index';
7
+ export * from '../packages/runtime/src/index';
8
+ export * from '../packages/terminal/src/index';
9
+ export * from '../packages/preview/src/index';
10
+ export * from '../packages/ui/src/index';
11
+ export * from '../apps/web/src/index';
package/src/preview-sw.js CHANGED
@@ -58,10 +58,17 @@ 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
+ // Reject configuration attempts originating from preview tabs/frames or opaque/blob frames.
62
+ if (event.source && typeof event.source.url === 'string') {
63
+ if (
64
+ /\/__preview\//.test(event.source.url) ||
65
+ /^(?:blob:|data:|about:srcdoc)/i.test(event.source.url)
66
+ ) {
67
+ return;
68
+ }
69
+ }
63
70
  const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
64
- if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
71
+ if (!csp || csp.length > MAX_CONFIG_LENGTH || /[\r\n]/.test(csp)) return;
65
72
  configuredCsp = csp;
66
73
  // Acknowledge so the host can wait for confirmation before loading a frame.
67
74
  try {
@@ -165,7 +172,17 @@ async function proxyVirtualRequest(event, port, targetPath) {
165
172
  }
166
173
 
167
174
  const response = await new Promise((resolve) => {
175
+ const closePort = () => {
176
+ try {
177
+ channel.port1.onmessage = null;
178
+ if (typeof channel.port1.close === 'function') channel.port1.close();
179
+ } catch (err) {
180
+ console.debug('[code-lab] preview-sw: port1.close failed', err);
181
+ }
182
+ };
183
+
168
184
  const timer = setTimeout(() => {
185
+ closePort();
169
186
  resolve({
170
187
  status: 504,
171
188
  statusText: 'Gateway Timeout',
@@ -176,6 +193,7 @@ async function proxyVirtualRequest(event, port, targetPath) {
176
193
 
177
194
  channel.port1.onmessage = (messageEvent) => {
178
195
  clearTimeout(timer);
196
+ closePort();
179
197
  resolve(messageEvent.data);
180
198
  };
181
199
 
@@ -194,10 +212,21 @@ async function proxyVirtualRequest(event, port, targetPath) {
194
212
 
195
213
  let responseBody = response && response.body;
196
214
  const responseHeaders = new Headers((response && response.headers) || {});
197
- const contentType = responseHeaders.get('content-type') || '';
215
+ const contentType = (responseHeaders.get('content-type') || '').trim();
216
+ const isHtmlLike = /\b(?:text\/html|application\/xhtml\+xml)\b/i.test(contentType);
217
+ const isExecutableMarkup =
218
+ isHtmlLike ||
219
+ /\b(?:image\/svg\+xml|application\/xml|text\/xml)\b/i.test(contentType) ||
220
+ !contentType;
198
221
 
199
- // Decode Uint8Array / ArrayBuffer HTML bodies so head injection always applies.
200
- if (/text\/html/i.test(contentType) && responseBody && typeof responseBody !== 'string') {
222
+ if (!contentType) {
223
+ responseHeaders.set('Content-Type', 'text/plain; charset=utf-8');
224
+ }
225
+ // Prevent MIME-sniffing binary/JSON/text responses into executable HTML/SVG on all responses.
226
+ responseHeaders.set('X-Content-Type-Options', 'nosniff');
227
+
228
+ // Decode Uint8Array / ArrayBuffer HTML/XHTML bodies so head injection always applies.
229
+ if (isHtmlLike && responseBody && typeof responseBody !== 'string') {
201
230
  try {
202
231
  if (responseBody instanceof ArrayBuffer || ArrayBuffer.isView(responseBody)) {
203
232
  responseBody = new TextDecoder('utf-8').decode(responseBody);
@@ -207,12 +236,16 @@ async function proxyVirtualRequest(event, port, targetPath) {
207
236
  }
208
237
  }
209
238
 
210
- // Inject the policy and a <base> so relative asset URLs in HTML responses
239
+ // Inject the policy and a <base> so relative asset URLs in HTML/XHTML responses
211
240
  // resolve under the `/__preview/:port/` namespace rather than the host root.
212
- if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
241
+ if (isHtmlLike && typeof responseBody === 'string') {
213
242
  responseBody = injectPreviewHead(responseBody, port);
243
+ }
244
+
245
+ // Attach Content-Security-Policy to every executable document/markup response
246
+ // (HTML, XHTML, SVG, XML, and untyped responses) so inline scripts cannot bypass CSP.
247
+ if (isExecutableMarkup) {
214
248
  responseHeaders.set('Content-Security-Policy', previewPolicy());
215
- responseHeaders.set('X-Content-Type-Options', 'nosniff');
216
249
  }
217
250
 
218
251
  return new Response(responseBody, {
@@ -244,12 +277,20 @@ self.addEventListener('fetch', (event) => {
244
277
 
245
278
  // Secondary route: root-relative sub-resources requested by a preview page
246
279
  // (e.g. `/app.js` referenced from `/__preview/3000/`) are attributed to the
247
- // originating preview tab via the request referrer.
280
+ // originating preview tab via the request referrer. Top-level navigations are
281
+ // redirected back under `/__preview/:port/` so no preview document ever runs
282
+ // at a non-`/__preview/` URL on the host origin.
248
283
  const referrer = event.request.referrer || '';
249
284
  const refMatch = referrer.match(/\/__preview\/(\d+)/);
250
285
  if (refMatch) {
286
+ const refPort = Number(refMatch[1]);
287
+ if (event.request.mode === 'navigate') {
288
+ const redirectUrl = `${url.origin}${PREVIEW_PREFIX}${refPort}${url.pathname}${url.search || ''}`;
289
+ event.respondWith(Response.redirect(redirectUrl, 302));
290
+ return;
291
+ }
251
292
  event.respondWith(
252
- proxyVirtualRequest(event, Number(refMatch[1]), url.pathname + (url.search || ''))
293
+ proxyVirtualRequest(event, refPort, url.pathname + (url.search || ''))
253
294
  );
254
295
  }
255
296
  });