@innovatorved/code-lab 0.1.7 → 0.1.9

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/workbench.ts CHANGED
@@ -7,13 +7,26 @@
7
7
  (function (root) {
8
8
  'use strict';
9
9
 
10
- let terminalModule = null;
11
- let shellModule = null;
12
- let runtimeModule = null;
10
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
11
+ (root && root.CodeLabLogger) ||
12
+ null;
13
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
14
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
15
+ : () => {};
16
+
17
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18
+ let shellModule = (root && root.CodeLabShell) || null;
19
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
13
20
  if (typeof require === 'function') {
14
- try { terminalModule = require('./terminal.js'); } catch (_) {}
15
- try { shellModule = require('./shell.js'); } catch (_) {}
16
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
21
+ if (!terminalModule) {
22
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
23
+ }
24
+ if (!shellModule) {
25
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
26
+ }
27
+ if (!runtimeModule) {
28
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
29
+ }
17
30
  }
18
31
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
19
32
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -44,7 +57,7 @@
44
57
 
45
58
  // The bundler rewrites this literal from package.json at build time. Keeping
46
59
  // the fallback in sync lets tests require src/workbench.js directly.
47
- const CODELAB_VERSION = '0.1.7';
60
+ const CODELAB_VERSION = '0.1.9';
48
61
 
49
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
50
63
  const NODE_AMBIENT_DTS = `
@@ -372,7 +385,14 @@ declare module 'bun:sqlite' {
372
385
  }
373
386
  `;
374
387
 
388
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
389
+ (root && root.CodeLabHtml) ||
390
+ null;
391
+
375
392
  function escapeHtml(str) {
393
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
394
+ return _sharedHtmlMod.escapeHtml(str);
395
+ }
376
396
  if (str == null) return '';
377
397
  return String(str)
378
398
  .replace(/&/g, '&')
@@ -382,6 +402,18 @@ declare module 'bun:sqlite' {
382
402
  .replace(/'/g, ''');
383
403
  }
384
404
 
405
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
406
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
407
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
408
+ let out = strings[0] || '';
409
+ for (let i = 0; i < values.length; i++) {
410
+ const val = values[i];
411
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
412
+ out += strings[i + 1] || '';
413
+ }
414
+ return raw(out);
415
+ });
416
+
385
417
  // Schemes that may appear in a rendered href. Everything else
386
418
  // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
387
419
  const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
@@ -600,11 +632,11 @@ declare module 'bun:sqlite' {
600
632
  if (!str) return '';
601
633
  let text = String(str);
602
634
 
603
- // Markdown Links: [label](url "title") or [label](url)
604
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
635
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
636
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
605
637
  const cleanUrl = sanitizeUrl(url);
606
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
607
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
638
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
639
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
608
640
  });
609
641
 
610
642
  // Strikethrough: ~~del~~
@@ -1131,23 +1163,24 @@ declare module 'bun:sqlite' {
1131
1163
  let _workbenchInstanceCounter = 0;
1132
1164
  const _fallbackStorage = new Map();
1133
1165
 
1134
- // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
1135
- // in src/preview-sw.js — keep both copies in sync.
1136
- const PREVIEW_CSP = [
1137
- "default-src 'self' data: blob:",
1138
- "base-uri 'self'",
1139
- "object-src 'none'",
1140
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
1141
- "style-src 'self' 'unsafe-inline'",
1142
- "img-src 'self' data: blob:",
1143
- "font-src 'self' data:",
1144
- "connect-src 'self' data: blob:",
1145
- "media-src 'self' data: blob:",
1146
- "worker-src 'self' blob:",
1147
- "frame-src 'self' data: blob:",
1148
- "form-action 'self'",
1149
- "frame-ancestors 'self'"
1150
- ].join('; ');
1166
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
1167
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
1168
+ // there is exactly one policy implementation shared by both sides.
1169
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
1170
+ (root && root.CodeLabCsp) ||
1171
+ null;
1172
+
1173
+ function normalizePreviewCspOption(raw) {
1174
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
1175
+ return PreviewCsp.normalizePreviewCspConfig(raw);
1176
+ }
1177
+ return { mode: 'balanced', allow: {} };
1178
+ }
1179
+
1180
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
1181
+ // that ships, using it would silently *pretend* to isolate previews while the
1182
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
1183
+ const PREVIEW_RELAY_AVAILABLE = false;
1151
1184
 
1152
1185
  function normalizePreviewOrigin(raw) {
1153
1186
  if (raw === null || raw === undefined || raw === '') return null;
@@ -1160,12 +1193,26 @@ declare module 'bun:sqlite' {
1160
1193
  }
1161
1194
  }
1162
1195
 
1163
- const LOG_PREFIX = '[code-lab]';
1196
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
1197
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
1198
+ constructor(code, message, options = {}) {
1199
+ super(message);
1200
+ this.name = 'CodeLabError';
1201
+ this.code = code || 'E_CODELAB';
1202
+ this.module = options.module || 'workbench';
1203
+ this.context = options.context || {};
1204
+ if (options.cause !== undefined) this.cause = options.cause;
1205
+ }
1206
+ };
1207
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
1164
1208
 
1165
1209
  // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
1166
1210
  // into their own telemetry; `options.debug` enables verbose output. Errors
1167
1211
  // are never silently discarded.
1168
1212
  function createLogger(options = {}) {
1213
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
1214
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
1215
+ }
1169
1216
  const sink = options.logger;
1170
1217
  const debugEnabled = options.debug === true;
1171
1218
 
@@ -1175,8 +1222,9 @@ declare module 'bun:sqlite' {
1175
1222
  try {
1176
1223
  sink[level](...args);
1177
1224
  return;
1178
- } catch (_) {
1179
- // A broken host logger must not break the IDE; fall through.
1225
+ } catch (sinkErr) {
1226
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
1227
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
1180
1228
  }
1181
1229
  }
1182
1230
  const fn = typeof console !== 'undefined' ? console[level] : null;
@@ -1208,7 +1256,7 @@ declare module 'bun:sqlite' {
1208
1256
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
1209
1257
  }
1210
1258
 
1211
- function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
1259
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
1212
1260
  const str = String(value);
1213
1261
  try {
1214
1262
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
@@ -1216,6 +1264,9 @@ declare module 'bun:sqlite' {
1216
1264
  return true;
1217
1265
  }
1218
1266
  } catch (err) {
1267
+ if (typeof onError === 'function') {
1268
+ onError(err);
1269
+ }
1219
1270
  if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
1220
1271
  if (!safeStorageSet._warnedKeys.has(key)) {
1221
1272
  safeStorageSet._warnedKeys.add(key);
@@ -1239,6 +1290,8 @@ declare module 'bun:sqlite' {
1239
1290
  this.options = options || {};
1240
1291
  this.logger = createLogger({ logger: options.logger, debug: options.debug });
1241
1292
  this._persistenceFailureReported = false;
1293
+ this.saveStatusState = 'saved';
1294
+ this.saveStatusError = null;
1242
1295
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
1243
1296
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
1244
1297
  this.title = options.title || this.labId;
@@ -1246,6 +1299,7 @@ declare module 'bun:sqlite' {
1246
1299
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
1247
1300
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
1248
1301
  this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
1302
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
1249
1303
  this._previewIsolationWarned = false;
1250
1304
  if (options.previewOrigin && !this.previewOrigin) {
1251
1305
  this.logger.warn(
@@ -1322,14 +1376,22 @@ declare module 'bun:sqlite' {
1322
1376
  path: '/',
1323
1377
  url: '',
1324
1378
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
1379
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
1380
+ maximized: false,
1381
+ consoleOpen: false,
1382
+ consoleLogs: [],
1325
1383
  loading: false,
1326
1384
  error: null,
1327
- srcdoc: ''
1385
+ srcdoc: '',
1386
+ violations: []
1328
1387
  };
1329
1388
  this.previewHistory = [];
1330
1389
  this.previewHistoryIdx = -1;
1331
1390
  this._previewSwReady = false;
1332
1391
  this._previewSwRegistration = null;
1392
+ this._previewViolationHandler = null;
1393
+ this._swMessageHandler = null;
1394
+ this._beforeUnloadHandler = null;
1333
1395
  this._portToasts = new Map();
1334
1396
  this.isFullscreen = false;
1335
1397
  this.isRunning = false;
@@ -1429,7 +1491,9 @@ declare module 'bun:sqlite' {
1429
1491
  onCommand: (cmd) => this._handleReplCommand(cmd),
1430
1492
  onInterrupt: () => this._handleInterrupt()
1431
1493
  });
1432
- } catch (_) {}
1494
+ } catch (err) {
1495
+ this.logger.debug('PTY engine initialization skipped.', err);
1496
+ }
1433
1497
  }
1434
1498
 
1435
1499
  this.shell = null;
@@ -1455,7 +1519,7 @@ declare module 'bun:sqlite' {
1455
1519
  intoRoot: options.cloneIntoRoot !== false,
1456
1520
  branch: options.branch || undefined,
1457
1521
  fetchImpl: options.fetchImpl || undefined
1458
- }).catch(() => {});
1522
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
1459
1523
  }
1460
1524
  }
1461
1525
 
@@ -1480,7 +1544,9 @@ declare module 'bun:sqlite' {
1480
1544
  }
1481
1545
  });
1482
1546
  this._syncFilesToShellVfs();
1483
- } catch (_) {}
1547
+ } catch (err) {
1548
+ this.logger.debug('POSIX shell initialization skipped.', err);
1549
+ }
1484
1550
  }
1485
1551
  }
1486
1552
 
@@ -1506,7 +1572,9 @@ declare module 'bun:sqlite' {
1506
1572
  const u = new URL(fullUrl);
1507
1573
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
1508
1574
  reqPath = u.pathname + (u.search || '');
1509
- } catch (_) {}
1575
+ } catch (err) {
1576
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
1577
+ }
1510
1578
  const method = String((init && init.method) || 'GET').toUpperCase();
1511
1579
  try {
1512
1580
  const res = await origDispatch(url, init);
@@ -1518,7 +1586,9 @@ declare module 'bun:sqlite' {
1518
1586
  } else if (res && res.body !== undefined) {
1519
1587
  bodyText = String(res.body);
1520
1588
  }
1521
- } catch (_) {}
1589
+ } catch (err) {
1590
+ this.logger.debug('Could not read response body for HTTP trace.', err);
1591
+ }
1522
1592
  const responseHeaders = {};
1523
1593
  if (res && res.headers) {
1524
1594
  if (typeof res.headers.forEach === 'function') {
@@ -1530,7 +1600,9 @@ declare module 'bun:sqlite' {
1530
1600
  let formattedBody = bodyText;
1531
1601
  try {
1532
1602
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
1533
- } catch (_) {}
1603
+ } catch (err) {
1604
+ void err;
1605
+ }
1534
1606
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
1535
1607
  this.lastHttpTrace.push({
1536
1608
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -1579,7 +1651,9 @@ declare module 'bun:sqlite' {
1579
1651
  vfs.writeFileSync(absPath, String(content ?? ''));
1580
1652
  }
1581
1653
  }
1582
- } catch (_) {}
1654
+ } catch (err) {
1655
+ this.logger.debug('Could not sync files to shell VFS.', err);
1656
+ }
1583
1657
  }
1584
1658
 
1585
1659
  _emitEvent(name, detail) {
@@ -1601,7 +1675,9 @@ declare module 'bun:sqlite' {
1601
1675
  if (shortName !== fullName) {
1602
1676
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
1603
1677
  }
1604
- } catch (_) {}
1678
+ } catch (err) {
1679
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
1680
+ }
1605
1681
  }
1606
1682
 
1607
1683
  _resolvedTheme() {
@@ -1635,13 +1711,26 @@ declare module 'bun:sqlite' {
1635
1711
  }
1636
1712
  }
1637
1713
 
1638
- _reportPersistenceFailure() {
1639
- if (this._persistenceFailureReported) return;
1714
+ _reportPersistenceFailure(cause) {
1715
+ const error = isCodeLabError(cause)
1716
+ ? cause
1717
+ : new CodeLabError(
1718
+ 'E_SAVE',
1719
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
1720
+ { cause, recoverable: true, details: { labId: this.labId } }
1721
+ );
1722
+ this.saveStatusState = 'failed';
1723
+ this.saveStatusError = error;
1724
+ this._updateStatusBar();
1725
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
1726
+ if (this._persistenceFailureReported) return error;
1640
1727
  this._persistenceFailureReported = true;
1641
1728
  this.logger.warn(
1642
1729
  'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
1643
1730
  );
1644
- this._emitEvent('persistence-error', { labId: this.labId });
1731
+ this._emitEvent('persistence-error', { labId: this.labId, error });
1732
+ this._emitEvent('error', error);
1733
+ return error;
1645
1734
  }
1646
1735
 
1647
1736
  _saveState() {
@@ -1649,6 +1738,11 @@ declare module 'bun:sqlite' {
1649
1738
  const key = `${this.mode}:${this.lang}`;
1650
1739
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
1651
1740
  customFiles[key] = { ...this.files };
1741
+ const hasSnapshot = Object.assign(
1742
+ {},
1743
+ (this.savedState && this.savedState.hasSnapshot) || {},
1744
+ { [key]: true }
1745
+ );
1652
1746
  const completedArr = Array.from(this.completedSteps);
1653
1747
  const state = {
1654
1748
  mode: this.mode,
@@ -1656,6 +1750,7 @@ declare module 'bun:sqlite' {
1656
1750
  activeStepIndex: this.activeStepIndex,
1657
1751
  completedSteps: completedArr,
1658
1752
  customFiles,
1753
+ hasSnapshot,
1659
1754
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
1660
1755
  activeFile: this.activeFile,
1661
1756
  folders: Array.from(this.folders || []),
@@ -1665,22 +1760,49 @@ declare module 'bun:sqlite' {
1665
1760
  };
1666
1761
  this.savedState = state;
1667
1762
  if (this.options && this.options.persistState === false) {
1763
+ this.saveStatusState = 'saved';
1764
+ this.saveStatusError = null;
1765
+ this._updateStatusBar();
1668
1766
  return;
1669
1767
  }
1768
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
1670
1769
  const serialized = JSON.stringify(state);
1770
+ safeStorageSet._lastError = null;
1771
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
1671
1772
  const persisted = [
1672
- safeStorageSet(this._storageKey(), serialized, this.logger),
1773
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
1673
1774
  // Sync with host app sidebar & build overview progress trackers
1674
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
1675
- safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
1775
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
1776
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
1676
1777
  ];
1677
- if (persisted.includes(false)) this._reportPersistenceFailure();
1778
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
1779
+ try {
1780
+ if (!this._idbStorage) {
1781
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
1782
+ }
1783
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
1784
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
1785
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
1786
+ });
1787
+ }
1788
+ } catch (err) {
1789
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
1790
+ }
1791
+ }
1792
+ if (persisted.includes(false)) {
1793
+ this._reportPersistenceFailure(safeStorageSet._lastError);
1794
+ } else {
1795
+ this.saveStatusState = 'saved';
1796
+ this.saveStatusError = null;
1797
+ this._updateStatusBar();
1798
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
1799
+ }
1678
1800
  } catch (err) {
1679
1801
  this.logger.error(
1680
1802
  'Failed to save workbench state.',
1681
1803
  err && err.message ? err.message : err
1682
1804
  );
1683
- this._reportPersistenceFailure();
1805
+ this._reportPersistenceFailure(err);
1684
1806
  }
1685
1807
  }
1686
1808
 
@@ -1703,7 +1825,9 @@ declare module 'bun:sqlite' {
1703
1825
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
1704
1826
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
1705
1827
  }
1706
- } catch (_) {}
1828
+ } catch (err) {
1829
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
1830
+ }
1707
1831
  }
1708
1832
 
1709
1833
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -1750,6 +1874,7 @@ declare module 'bun:sqlite' {
1750
1874
  const dotEl = this.container.querySelector('#cl-status-dot');
1751
1875
  const textEl = this.container.querySelector('#cl-status-text');
1752
1876
  const fileEl = this.container.querySelector('#cl-status-file');
1877
+ const saveEl = this.container.querySelector('#cl-status-save');
1753
1878
  const durEl = this.container.querySelector('#cl-status-duration');
1754
1879
  const curEl = this.container.querySelector('#cl-status-cursor');
1755
1880
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -1761,6 +1886,24 @@ declare module 'bun:sqlite' {
1761
1886
  }
1762
1887
  if (textEl) textEl.textContent = this.runtimeStatusText;
1763
1888
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
1889
+ if (saveEl) {
1890
+ if (this.saveStatusState === 'failed') {
1891
+ saveEl.style.display = 'inline-flex';
1892
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
1893
+ saveEl.textContent = '⚠ Save failed (session-only)';
1894
+ const reason = this.saveStatusError && this.saveStatusError.message
1895
+ ? this.saveStatusError.message
1896
+ : 'localStorage is unavailable or quota exceeded';
1897
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
1898
+ saveEl.setAttribute('data-save-state', 'failed');
1899
+ } else {
1900
+ saveEl.style.display = 'none';
1901
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
1902
+ saveEl.textContent = '';
1903
+ saveEl.removeAttribute('title');
1904
+ saveEl.setAttribute('data-save-state', 'saved');
1905
+ }
1906
+ }
1764
1907
  if (durEl) {
1765
1908
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
1766
1909
  durEl.style.display = 'inline-flex';
@@ -1798,6 +1941,9 @@ declare module 'bun:sqlite' {
1798
1941
  const key = `${this.mode}:${this.lang}`;
1799
1942
  const saved = this.savedState.customFiles?.[key];
1800
1943
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
1944
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
1945
+ return { ...saved };
1946
+ }
1801
1947
  if (saved && Object.keys(saved).length > 0) {
1802
1948
  return { ...base, ...saved };
1803
1949
  }
@@ -2010,6 +2156,10 @@ declare module 'bun:sqlite' {
2010
2156
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
2011
2157
  </div>
2012
2158
  </div>
2159
+
2160
+ <!-- Right-Hand Split Web Preview Pane -->
2161
+ <div class="codelab-splitter-preview" id="cl-splitter-preview" role="separator" aria-orientation="vertical" title="Drag to resize web preview (double-click to reset)" style="display:none"></div>
2162
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
2013
2163
  </div>
2014
2164
 
2015
2165
  <!-- Interactive Horizontal Splitter -->
@@ -2068,6 +2218,7 @@ declare module 'bun:sqlite' {
2068
2218
  </span>
2069
2219
  <span class="codelab-statusbar__sep">·</span>
2070
2220
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
2221
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
2071
2222
  </div>
2072
2223
  <div class="codelab-statusbar__right">
2073
2224
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -3322,7 +3473,9 @@ declare module 'bun:sqlite' {
3322
3473
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
3323
3474
  try {
3324
3475
  this.ptyEngine.writeStreamChunk(rawText, type);
3325
- } catch (_) {}
3476
+ } catch (err) {
3477
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
3478
+ }
3326
3479
  }
3327
3480
 
3328
3481
  this._activeStreamType = type;
@@ -3454,14 +3607,18 @@ declare module 'bun:sqlite' {
3454
3607
  if (this._activeCommandAbortController) {
3455
3608
  try {
3456
3609
  this._activeCommandAbortController.abort('SIGINT');
3457
- } catch (_) {}
3610
+ } catch (err) {
3611
+ this.logger.debug('AbortController.abort failed.', err);
3612
+ }
3458
3613
  this._activeCommandAbortController = null;
3459
3614
  }
3460
3615
 
3461
3616
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
3462
3617
  try {
3463
3618
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
3464
- } catch (_) {}
3619
+ } catch (err) {
3620
+ this.logger.debug('cancelWorkerExecution failed.', err);
3621
+ }
3465
3622
  }
3466
3623
 
3467
3624
  this.isRunning = false;
@@ -4030,7 +4187,9 @@ declare module 'bun:sqlite' {
4030
4187
  try {
4031
4188
  const parsed = JSON.parse(responseBody);
4032
4189
  formattedBody = JSON.stringify(parsed, null, 2);
4033
- } catch (_) {}
4190
+ } catch (_) {
4191
+ formattedBody = responseBody;
4192
+ }
4034
4193
 
4035
4194
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
4036
4195
  const traceItem = {
@@ -4103,7 +4262,9 @@ declare module 'bun:sqlite' {
4103
4262
  if (this.drawerTab === 'ports') this._renderDrawerBody();
4104
4263
  this._dismissPortToast(port);
4105
4264
  }));
4106
- } catch (_) {}
4265
+ } catch (err) {
4266
+ this.logger.warn('Failed to attach portTable event listeners.', err);
4267
+ }
4107
4268
  }
4108
4269
 
4109
4270
  _updatePortsPill() {
@@ -4177,16 +4338,55 @@ declare module 'bun:sqlite' {
4177
4338
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
4178
4339
  try {
4179
4340
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
4341
+ this._swMessageHandler = onMessage;
4180
4342
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
4181
4343
  navigator.serviceWorker.addEventListener('message', onMessage);
4182
4344
  } else {
4183
4345
  navigator.serviceWorker.onmessage = onMessage;
4184
4346
  }
4185
4347
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
4186
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
4187
- .catch(() => { this._previewSwReady = false; });
4188
- } catch (_) {
4348
+ .then((reg) => {
4349
+ this._previewSwRegistration = reg;
4350
+ this._previewSwReady = true;
4351
+ this._pushPreviewCsp(reg);
4352
+ })
4353
+ .catch((err) => {
4354
+ this._previewSwReady = false;
4355
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
4356
+ });
4357
+ } catch (err) {
4189
4358
  this._previewSwReady = false;
4359
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
4360
+ }
4361
+ }
4362
+
4363
+ /**
4364
+ * The service worker cannot read workbench options, so the resolved policy
4365
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
4366
+ * the srcdoc fallback and silently not the served previews.
4367
+ */
4368
+ _pushPreviewCsp(registration) {
4369
+ const policy = this._previewPolicy();
4370
+ const send = (worker) => {
4371
+ if (!worker || typeof worker.postMessage !== 'function') return;
4372
+ try {
4373
+ worker.postMessage({ type: 'codelab:config', csp: policy });
4374
+ } catch (err) {
4375
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
4376
+ }
4377
+ };
4378
+
4379
+ if (registration) {
4380
+ send(registration.active);
4381
+ send(registration.installing);
4382
+ send(registration.waiting);
4383
+ }
4384
+
4385
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
4386
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
4387
+ sw.ready
4388
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
4389
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
4190
4390
  }
4191
4391
  }
4192
4392
 
@@ -4219,11 +4419,15 @@ declare module 'bun:sqlite' {
4219
4419
  } else if (res && res.headers) {
4220
4420
  Object.assign(outHeaders, res.headers);
4221
4421
  }
4222
- } catch (_) {}
4422
+ } catch (err) {
4423
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
4424
+ }
4223
4425
  let bodyText = '';
4224
4426
  try {
4225
4427
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
4226
- } catch (_) {}
4428
+ } catch (err) {
4429
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
4430
+ }
4227
4431
  return {
4228
4432
  status: (res && res.status) || 200,
4229
4433
  statusText: (res && res.statusText) || 'OK',
@@ -4250,48 +4454,240 @@ declare module 'bun:sqlite' {
4250
4454
  const p = Number(port) || 3000;
4251
4455
  const rawPath = pathAndQuery || '/';
4252
4456
  const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
4253
- const base = this.previewOrigin || '';
4457
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
4458
+ // relay exists on that origin; pretending otherwise yields a 503.
4459
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
4254
4460
  return `${base}/__preview/${p}${path}`;
4255
4461
  }
4256
4462
 
4463
+ /** Resolved CSP for preview documents served by this workbench. */
4464
+ _previewPolicy() {
4465
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
4466
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
4467
+ return "default-src 'self'; object-src 'none'";
4468
+ }
4469
+ return PreviewCsp.buildPreviewPolicy(
4470
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
4471
+ );
4472
+ }
4473
+
4474
+ /** Remote origins the current policy allows, for the preview toolbar. */
4475
+ _previewNetworkHosts() {
4476
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
4477
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
4478
+ }
4479
+
4257
4480
  _warnPreviewIsolation() {
4258
- if (this.previewOrigin || this._previewIsolationWarned) return;
4481
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
4259
4482
  this._previewIsolationWarned = true;
4260
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
4261
- console.warn(
4262
- '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
4263
- 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
4264
- );
4265
- }
4483
+ if (PREVIEW_RELAY_AVAILABLE) return;
4484
+ this.logger.warn(
4485
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
4486
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
4487
+ 'the host origin: no host DOM, no host storage.'
4488
+ );
4266
4489
  }
4267
4490
 
4268
4491
  _injectPreviewCsp(html, port) {
4269
4492
  if (typeof html !== 'string' || !html) return html;
4270
- if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
4271
4493
 
4272
- const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
4273
- (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
4494
+ const tags = [];
4495
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
4496
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
4497
+ }
4498
+ if (!/<base\b/i.test(html)) {
4499
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
4500
+ }
4501
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
4502
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
4503
+ tags.push(PreviewCsp.buildPreviewShims());
4504
+ }
4505
+ if (tags.length === 0) return html;
4274
4506
 
4507
+ const injection = tags.join('');
4275
4508
  if (/<head\b[^>]*>/i.test(html)) {
4276
- return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
4509
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
4277
4510
  }
4278
4511
  if (/<html\b[^>]*>/i.test(html)) {
4279
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
4512
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
4513
+ }
4514
+ return `<head>${injection}</head>${html}`;
4515
+ }
4516
+
4517
+ /**
4518
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
4519
+ * string `"null"` and cannot be used to authenticate the sender. Match the
4520
+ * message source against the preview frame instead.
4521
+ */
4522
+ _installPreviewViolationListener() {
4523
+ if (this._previewViolationHandler) return;
4524
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
4525
+
4526
+ this._previewViolationHandler = (event) => {
4527
+ const data = event && event.data;
4528
+ if (!data || typeof data.type !== 'string') return;
4529
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
4530
+ if (!iframe) return;
4531
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
4532
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
4533
+
4534
+ if (data.type === 'codelab:preview-violation') {
4535
+ this._reportPreviewViolation(data);
4536
+ } else if (data.type === 'codelab:preview-console') {
4537
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
4538
+ const args = Array.isArray(data.args) ? data.args : [data.args];
4539
+ const text = args.map((a) => String(a ?? '')).join(' ');
4540
+ this.terminalLogs.push({
4541
+ type: level === 'error' ? 'stderr' : 'stdout',
4542
+ text: `[Preview ${level.toUpperCase()}] ${text}`
4543
+ });
4544
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
4545
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
4546
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
4547
+ this._updatePreviewConsoleUI();
4548
+ this._emitEvent('preview-console', { level, text, args });
4549
+ } else if (data.type === 'codelab:preview-error') {
4550
+ const msg = String(data.message || 'Uncaught runtime error');
4551
+ this.previewState.runtimeError = {
4552
+ message: msg,
4553
+ file: data.file ? String(data.file) : null,
4554
+ line: typeof data.line === 'number' ? data.line : null,
4555
+ col: typeof data.col === 'number' ? data.col : null,
4556
+ stack: data.stack ? String(data.stack) : null
4557
+ };
4558
+ this.terminalLogs.push({
4559
+ type: 'stderr',
4560
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
4561
+ });
4562
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
4563
+ this.previewState.consoleLogs.push({
4564
+ level: 'error',
4565
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
4566
+ timestamp: new Date().toLocaleTimeString()
4567
+ });
4568
+ this._updatePreviewConsoleUI();
4569
+ this._emitEvent('preview-error', this.previewState.runtimeError);
4570
+ } else if (data.type === 'codelab:preview-error-clear') {
4571
+ this.previewState.runtimeError = null;
4572
+ } else if (data.type === 'codelab:preview-fetch') {
4573
+ const reqId = data.reqId || data.id;
4574
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
4575
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
4576
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
4577
+ this._dispatchPreviewRequest({
4578
+ port: targetPort,
4579
+ url: targetUrl,
4580
+ method: data.method || 'GET',
4581
+ headers: data.headers || {},
4582
+ body: data.body !== undefined ? data.body : null
4583
+ })
4584
+ .then((res) => {
4585
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
4586
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
4587
+ if (this.drawerTab === 'network') this._renderDrawerBody();
4588
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
4589
+ iframe.contentWindow.postMessage({
4590
+ type: 'codelab:preview-fetch-res',
4591
+ reqId,
4592
+ id: reqId,
4593
+ status: res.status || 200,
4594
+ statusText: res.statusText || 'OK',
4595
+ headers: res.headers || {},
4596
+ body: res.body || ''
4597
+ }, '*');
4598
+ }
4599
+ })
4600
+ .catch((err) => {
4601
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
4602
+ iframe.contentWindow.postMessage({
4603
+ type: 'codelab:preview-fetch-res',
4604
+ reqId,
4605
+ id: reqId,
4606
+ error: String((err && err.message) || err)
4607
+ }, '*');
4608
+ }
4609
+ });
4610
+ } else if (data.type === 'codelab:preview-navigate') {
4611
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
4612
+ if (navHref) {
4613
+ this._previewGo(String(navHref));
4614
+ }
4615
+ } else if (data.type === 'codelab:preview-url-change') {
4616
+ if (data.path && typeof data.path === 'string') {
4617
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
4618
+ this.previewState.url = this._previewUrl();
4619
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
4620
+ if (input) input.value = this.previewState.url;
4621
+ }
4622
+ }
4623
+ };
4624
+ window.addEventListener('message', this._previewViolationHandler);
4625
+ }
4626
+
4627
+ _reportPreviewViolation(violation) {
4628
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
4629
+ const directive = String((violation && violation.directive) || '');
4630
+ const key = `${directive}|${blockedURI}`;
4631
+ const state = this.previewState;
4632
+ state.violations = state.violations || [];
4633
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
4634
+ state.violations.push({ key, directive, blockedURI });
4635
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
4636
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
4637
+ }
4638
+ this._updatePreviewCspStatus();
4639
+ }
4640
+
4641
+ _shortPreviewUrl(raw) {
4642
+ const value = String(raw || '');
4643
+ try {
4644
+ const parsed = new URL(value);
4645
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
4646
+ return `${parsed.host}${path === '/' ? '' : path}`;
4647
+ } catch (_) {
4648
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
4649
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
4650
+ }
4651
+ }
4652
+
4653
+ /** Update (or create) the CSP status chip in the preview toolbar. */
4654
+ _updatePreviewCspStatus() {
4655
+ if (!this.container) return;
4656
+ const chip = this.container.querySelector('#cl-preview-csp-status');
4657
+ if (!chip) return;
4658
+ const violations = (this.previewState && this.previewState.violations) || [];
4659
+ if (!violations.length) {
4660
+ chip.hidden = true;
4661
+ chip.textContent = '';
4662
+ chip.removeAttribute('title');
4663
+ return;
4280
4664
  }
4281
- return `<head>${tags}</head>${html}`;
4665
+ const last = violations[violations.length - 1];
4666
+ chip.hidden = false;
4667
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
4668
+ chip.title = violations
4669
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
4670
+ .join('\n');
4282
4671
  }
4283
4672
 
4284
4673
  _openWebPreview(port, path = '/') {
4285
4674
  const p = Number(port) || this._firstListeningPort() || 3000;
4286
4675
  this._warnPreviewIsolation();
4676
+ this._installPreviewViolationListener();
4287
4677
  this.previewState.port = p;
4288
4678
  this.previewState.path = path || '/';
4289
4679
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
4290
4680
  this.previewState.error = null;
4681
+ this.previewState.violations = [];
4291
4682
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
4292
4683
  this.previewHistory.push(this.previewState.url);
4293
4684
  this.previewHistoryIdx = this.previewHistory.length - 1;
4294
- this.switchDrawerTab('preview');
4685
+ if (this.previewState.dockMode === 'split') {
4686
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4687
+ if (splitHost) this._renderWebPreview(splitHost);
4688
+ } else {
4689
+ this.switchDrawerTab('preview');
4690
+ }
4295
4691
  return this._previewLoadPromise || Promise.resolve();
4296
4692
  }
4297
4693
 
@@ -4378,7 +4774,7 @@ declare module 'bun:sqlite' {
4378
4774
  try {
4379
4775
  const win = window.open(url, '_blank');
4380
4776
  if (win) {
4381
- try { win.opener = null; } catch (_) {}
4777
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
4382
4778
  opened = true;
4383
4779
  }
4384
4780
  } catch (_) { opened = false; }
@@ -4400,7 +4796,9 @@ declare module 'bun:sqlite' {
4400
4796
  const u = new URL(url);
4401
4797
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
4402
4798
  path = u.pathname + (u.search || '') + (u.hash || '');
4403
- } catch (_) {}
4799
+ } catch (err) {
4800
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
4801
+ }
4404
4802
  this.previewState.port = port;
4405
4803
  this.previewState.path = path;
4406
4804
  this.previewState.url = url;
@@ -4408,7 +4806,12 @@ declare module 'bun:sqlite' {
4408
4806
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
4409
4807
  this.previewHistory.push(url);
4410
4808
  this.previewHistoryIdx = this.previewHistory.length - 1;
4411
- this.switchDrawerTab('preview');
4809
+ if (this.previewState.dockMode === 'split') {
4810
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4811
+ if (splitHost) this._renderWebPreview(splitHost);
4812
+ } else {
4813
+ this.switchDrawerTab('preview');
4814
+ }
4412
4815
  return this._previewLoadPromise || Promise.resolve();
4413
4816
  }
4414
4817
 
@@ -4432,7 +4835,9 @@ declare module 'bun:sqlite' {
4432
4835
  const u = new URL(url);
4433
4836
  this.previewState.port = Number(u.port || 80);
4434
4837
  this.previewState.path = u.pathname + (u.search || '');
4435
- } catch (_) {}
4838
+ } catch (err) {
4839
+ this.logger.debug('Failed to parse preview history URL.', err);
4840
+ }
4436
4841
  const input = this.container.querySelector('#cl-preview-url-input');
4437
4842
  if (input) input.value = url;
4438
4843
  this._renderWebPreviewControls();
@@ -4447,6 +4852,94 @@ declare module 'bun:sqlite' {
4447
4852
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
4448
4853
  this.previewState.frameMode = mode;
4449
4854
  this._renderDrawerBody();
4855
+ if (this.previewState.dockMode === 'split') {
4856
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4857
+ if (splitHost) this._renderWebPreview(splitHost);
4858
+ }
4859
+ }
4860
+
4861
+ _togglePreviewDock() {
4862
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
4863
+ this._previewRenderKey = null;
4864
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4865
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
4866
+ if (this.previewState.dockMode === 'split') {
4867
+ if (splitBar) splitBar.style.display = 'block';
4868
+ if (splitHost) {
4869
+ splitHost.style.display = 'flex';
4870
+ this._renderWebPreview(splitHost);
4871
+ }
4872
+ if (this.drawerTab === 'preview') {
4873
+ this.switchDrawerTab('terminal');
4874
+ } else {
4875
+ this._renderDrawerBody();
4876
+ }
4877
+ } else {
4878
+ if (splitBar) splitBar.style.display = 'none';
4879
+ if (splitHost) {
4880
+ splitHost.style.display = 'none';
4881
+ splitHost.innerHTML = '';
4882
+ }
4883
+ this.switchDrawerTab('preview');
4884
+ }
4885
+ if (this.editor && typeof this.editor.layout === 'function') {
4886
+ setTimeout(() => {
4887
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
4888
+ }, 30);
4889
+ }
4890
+ }
4891
+
4892
+ _togglePreviewMaximize() {
4893
+ this.previewState.maximized = !this.previewState.maximized;
4894
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
4895
+ if (previewEl) {
4896
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
4897
+ }
4898
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
4899
+ if (maxBtn) {
4900
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
4901
+ }
4902
+ }
4903
+
4904
+ _togglePreviewConsole() {
4905
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
4906
+ this._updatePreviewConsoleUI();
4907
+ }
4908
+
4909
+ _clearPreviewConsole() {
4910
+ this.previewState.consoleLogs = [];
4911
+ this._updatePreviewConsoleUI();
4912
+ }
4913
+
4914
+ _updatePreviewConsoleUI() {
4915
+ if (!this.container) return;
4916
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
4917
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
4918
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
4919
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
4920
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
4921
+ if (consolePill) {
4922
+ consolePill.textContent = String(logs.length);
4923
+ }
4924
+ if (consoleBtn) {
4925
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
4926
+ }
4927
+ if (consoleDrawer) {
4928
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
4929
+ }
4930
+ if (consoleBody) {
4931
+ if (logs.length === 0) {
4932
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
4933
+ } else {
4934
+ consoleBody.innerHTML = logs.map((entry) => `
4935
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
4936
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
4937
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
4938
+ </div>
4939
+ `).join('');
4940
+ consoleBody.scrollTop = consoleBody.scrollHeight;
4941
+ }
4942
+ }
4450
4943
  }
4451
4944
 
4452
4945
  _renderWebPreviewControls() {
@@ -4458,6 +4951,7 @@ declare module 'bun:sqlite' {
4458
4951
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
4459
4952
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
4460
4953
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
4954
+ this._updatePreviewConsoleUI();
4461
4955
  }
4462
4956
 
4463
4957
  _popoutPreview() {
@@ -4466,9 +4960,11 @@ declare module 'bun:sqlite' {
4466
4960
  try {
4467
4961
  const u = new URL(url);
4468
4962
  popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
4469
- } catch (_) {}
4963
+ } catch (err) {
4964
+ this.logger.debug('Failed to parse popout preview URL.', err);
4965
+ }
4470
4966
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
4471
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
4967
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
4472
4968
  }
4473
4969
  return popout;
4474
4970
  }
@@ -4476,8 +4972,32 @@ declare module 'bun:sqlite' {
4476
4972
  _renderWebPreview(bodyEl) {
4477
4973
  if (!bodyEl) return;
4478
4974
  this._warnPreviewIsolation();
4479
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
4480
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
4975
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4976
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
4977
+
4978
+ let targetHost = bodyEl;
4979
+ if (this.previewState.dockMode === 'split' && splitHost) {
4980
+ if (splitBar) splitBar.style.display = 'block';
4981
+ splitHost.style.display = 'flex';
4982
+ if (bodyEl !== splitHost) {
4983
+ bodyEl.innerHTML = `
4984
+ <div class="codelab-preview-split-notice">
4985
+ <span>Web Preview is docked to the right split pane.</span>
4986
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
4987
+ </div>
4988
+ `;
4989
+ }
4990
+ targetHost = splitHost;
4991
+ } else {
4992
+ if (splitBar) splitBar.style.display = 'none';
4993
+ if (splitHost && bodyEl !== splitHost) {
4994
+ splitHost.style.display = 'none';
4995
+ splitHost.innerHTML = '';
4996
+ }
4997
+ }
4998
+
4999
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
5000
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
4481
5001
  this._renderWebPreviewControls();
4482
5002
  return;
4483
5003
  }
@@ -4495,8 +5015,24 @@ declare module 'bun:sqlite' {
4495
5015
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
4496
5016
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
4497
5017
 
4498
- bodyEl.innerHTML = `
4499
- <div class="codelab-preview">
5018
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
5019
+ const cspHosts = this._previewNetworkHosts();
5020
+ const cspBadge = cspMode === 'strict'
5021
+ ? 'CSP: strict'
5022
+ : !cspHosts.length
5023
+ ? 'CSP: custom'
5024
+ : cspHosts.length === 1
5025
+ ? `CSP: ${cspHosts[0]}`
5026
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
5027
+ const cspBadgeTitle = cspMode === 'strict'
5028
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
5029
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
5030
+
5031
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
5032
+ const isSplit = this.previewState.dockMode === 'split';
5033
+
5034
+ targetHost.innerHTML = `
5035
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
4500
5036
  <div class="codelab-preview-chrome">
4501
5037
  <div class="codelab-preview-nav">
4502
5038
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -4510,10 +5046,31 @@ declare module 'bun:sqlite' {
4510
5046
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'tablet' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="tablet" title="Tablet">${CL_ICONS.tablet || '▢'}</button>
4511
5047
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'mobile' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="mobile" title="Mobile">${CL_ICONS.smartphone || '▯'}</button>
4512
5048
  </div>
5049
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
5050
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
5051
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
5052
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
5053
+ </button>
5054
+ <button type="button" class="codelab-preview-btn ${isSplit ? 'active' : ''}" data-cl-action="preview-dock-toggle" title="${isSplit ? 'Dock Preview to Bottom Drawer' : 'Dock Preview to Right Split Pane'}">
5055
+ ${CL_ICONS.layout || '◫'}
5056
+ </button>
5057
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
5058
+ ${CL_ICONS.maximize || '⛶'}
5059
+ </button>
4513
5060
  <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-popout" title="Open in a new browser tab">${CL_ICONS.externalLink || '↗'} <span>Pop Out</span></button>
4514
5061
  </div>
4515
5062
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
4516
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="same-origin" title="Web Preview"></iframe>
5063
+ <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="no-referrer-when-downgrade" title="Web Preview"></iframe>
5064
+ </div>
5065
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
5066
+ <div class="codelab-preview-console__bar">
5067
+ <span>Preview Console</span>
5068
+ <div style="display:flex;align-items:center;gap:6px;">
5069
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
5070
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
5071
+ </div>
5072
+ </div>
5073
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
4517
5074
  </div>
4518
5075
  ${servers.length
4519
5076
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -4526,6 +5083,8 @@ declare module 'bun:sqlite' {
4526
5083
  </div>`}
4527
5084
  </div>
4528
5085
  `;
5086
+ this._updatePreviewCspStatus();
5087
+ this._updatePreviewConsoleUI();
4529
5088
  this._loadPreviewFrame();
4530
5089
  }
4531
5090
 
@@ -4542,22 +5101,25 @@ declare module 'bun:sqlite' {
4542
5101
  this.previewState.error = 'No port selected';
4543
5102
  return Promise.resolve();
4544
5103
  }
5104
+ this._syncFilesToShellVfs();
4545
5105
  const fullUrl = this._previewUrl();
4546
5106
  this.previewState.loading = true;
4547
5107
  this.previewState.error = null;
4548
5108
 
4549
- if (this._previewSwReady) {
5109
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
4550
5110
  try {
4551
5111
  const u = new URL(fullUrl);
4552
5112
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
4553
5113
  iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
4554
5114
  this.previewState.loading = false;
4555
5115
  return Promise.resolve();
4556
- } catch (_) {}
5116
+ } catch (err) {
5117
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
5118
+ }
4557
5119
  }
4558
5120
 
4559
- // Fallback (no Service Worker): dispatch via the virtual port table and
4560
- // inline the response with an injected <base> for relative asset URLs.
5121
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
5122
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
4561
5123
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
4562
5124
  .then((res) => {
4563
5125
  let body = res.body || '';
@@ -4619,7 +5181,7 @@ declare module 'bun:sqlite' {
4619
5181
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
4620
5182
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
4621
5183
  let isDir = false;
4622
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
5184
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
4623
5185
  if (isDir) {
4624
5186
  shellWorkspaceFolders.add(rel);
4625
5187
  walk(full, rel);
@@ -4627,7 +5189,9 @@ declare module 'bun:sqlite' {
4627
5189
  try {
4628
5190
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
4629
5191
  shellWorkspaceFiles.set(rel, content);
4630
- } catch (_) {}
5192
+ } catch (err) {
5193
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
5194
+ }
4631
5195
  }
4632
5196
  }
4633
5197
  };
@@ -4929,6 +5493,27 @@ declare module 'bun:sqlite' {
4929
5493
  }
4930
5494
 
4931
5495
  _notifyCodeChange(filename, code) {
5496
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
5497
+ try {
5498
+ const clean = String(filename).replace(/^\/+/, '');
5499
+ const parts = clean.split('/');
5500
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
5501
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
5502
+ }
5503
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
5504
+ } catch (err) {
5505
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
5506
+ }
5507
+ }
5508
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
5509
+ if (this._previewReloadTimer) {
5510
+ clearTimeout(this._previewReloadTimer);
5511
+ }
5512
+ this._previewReloadTimer = setTimeout(() => {
5513
+ this._previewReloadTimer = null;
5514
+ this._previewReload();
5515
+ }, 300);
5516
+ }
4932
5517
  if (this.onCodeChange) {
4933
5518
  try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
4934
5519
  }
@@ -4986,7 +5571,7 @@ declare module 'bun:sqlite' {
4986
5571
  if (fallbackWrap) fallbackWrap.style.display = 'none';
4987
5572
  if (mdPreview) mdPreview.style.display = 'none';
4988
5573
  if (this.editor) {
4989
- try { this.editor.setModel(null); } catch (_) {}
5574
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
4990
5575
  }
4991
5576
  if (emptyEl) {
4992
5577
  emptyEl.style.display = 'flex';
@@ -5096,6 +5681,16 @@ declare module 'bun:sqlite' {
5096
5681
  };
5097
5682
  if (typeof document !== 'undefined') {
5098
5683
  document.addEventListener('keydown', this._escHandler);
5684
+ this._beforeUnloadHandler = () => {
5685
+ if (document.visibilityState === 'hidden') {
5686
+ try {
5687
+ this._saveState();
5688
+ } catch (err) {
5689
+ void err;
5690
+ }
5691
+ }
5692
+ };
5693
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
5099
5694
  }
5100
5695
 
5101
5696
  this.container.addEventListener('keydown', e => {
@@ -5298,7 +5893,9 @@ declare module 'bun:sqlite' {
5298
5893
  textarea.select();
5299
5894
  document.execCommand('copy');
5300
5895
  document.body.removeChild(textarea);
5301
- } catch (_) {}
5896
+ } catch (err) {
5897
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
5898
+ }
5302
5899
  };
5303
5900
 
5304
5901
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -5540,15 +6137,29 @@ declare module 'bun:sqlite' {
5540
6137
  this._previewSetFrameMode(actionBtn.dataset.mode);
5541
6138
  } else if (action === 'preview-popout') {
5542
6139
  this._popoutPreview();
6140
+ } else if (action === 'preview-dock-toggle') {
6141
+ this._togglePreviewDock();
6142
+ } else if (action === 'preview-maximize') {
6143
+ this._togglePreviewMaximize();
6144
+ } else if (action === 'preview-console-toggle') {
6145
+ this._togglePreviewConsole();
6146
+ } else if (action === 'preview-console-clear') {
6147
+ this._clearPreviewConsole();
5543
6148
  } else if (action === 'open-port-client') {
5544
- const port = actionBtn.dataset.port;
6149
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
5545
6150
  if (port) {
5546
6151
  this.httpClientUrl = `http://localhost:${port}/`;
6152
+ if (this.httpClientState) {
6153
+ this.httpClientState.url = `http://localhost:${port}/`;
6154
+ }
5547
6155
  this._renderDrawerBody();
5548
6156
  }
5549
6157
  } else if (action === 'stop-port') {
5550
- const port = Number(actionBtn.dataset.port);
6158
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
5551
6159
  if (port) {
6160
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
6161
+ this.portTable.closeServer(port);
6162
+ }
5552
6163
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
5553
6164
  this.shell.portTable.unregister(port);
5554
6165
  }
@@ -5558,18 +6169,32 @@ declare module 'bun:sqlite' {
5558
6169
  } else if (action === 'http-send') {
5559
6170
  this._sendHttpClientRequest();
5560
6171
  } else if (action === 'http-tab') {
5561
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
6172
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
6173
+ this.httpActiveTab = nextTab;
6174
+ if (this.httpClientState) {
6175
+ this.httpClientState.activeResponseTab = nextTab;
6176
+ }
5562
6177
  this._renderDrawerBody();
5563
6178
  } else if (action === 'clear-net-traces') {
5564
6179
  this.lastHttpTrace = [];
5565
6180
  this.selectedNetTraceIdx = null;
6181
+ if (this.networkFilter) {
6182
+ this.networkFilter.selectedTraceId = null;
6183
+ }
5566
6184
  this._renderDrawerBody();
5567
6185
  } else if (action === 'select-net-trace') {
6186
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
5568
6187
  const idx = Number(actionBtn.dataset.traceIdx);
5569
6188
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
6189
+ if (this.networkFilter) {
6190
+ this.networkFilter.selectedTraceId = traceId;
6191
+ }
5570
6192
  this._renderDrawerBody();
5571
6193
  } else if (action === 'close-net-detail') {
5572
6194
  this.selectedNetTraceIdx = null;
6195
+ if (this.networkFilter) {
6196
+ this.networkFilter.selectedTraceId = null;
6197
+ }
5573
6198
  this._renderDrawerBody();
5574
6199
  }
5575
6200
  return;
@@ -5656,6 +6281,7 @@ declare module 'bun:sqlite' {
5656
6281
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
5657
6282
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
5658
6283
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
6284
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
5659
6285
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
5660
6286
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
5661
6287
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -5666,6 +6292,9 @@ declare module 'bun:sqlite' {
5666
6292
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
5667
6293
  } },
5668
6294
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
6295
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
6296
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
6297
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
5669
6298
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
5670
6299
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
5671
6300
  ];
@@ -5698,7 +6327,9 @@ declare module 'bun:sqlite' {
5698
6327
  input.focus();
5699
6328
  try {
5700
6329
  input.setSelectionRange(initialVal.length, initialVal.length);
5701
- } catch (_) {}
6330
+ } catch (err) {
6331
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
6332
+ }
5702
6333
 
5703
6334
  input.addEventListener('input', () => {
5704
6335
  this.paletteSelectedIndex = 0;
@@ -5971,7 +6602,7 @@ declare module 'bun:sqlite' {
5971
6602
  const onUp = ev => {
5972
6603
  vSplitter.classList.remove('is-dragging');
5973
6604
  shell.classList.remove('is-resizing');
5974
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6605
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
5975
6606
  vSplitter.removeEventListener('pointermove', onMove);
5976
6607
  vSplitter.removeEventListener('pointerup', onUp);
5977
6608
  };
@@ -6012,7 +6643,7 @@ declare module 'bun:sqlite' {
6012
6643
  const onUp = ev => {
6013
6644
  hSplitter.classList.remove('is-dragging');
6014
6645
  shell.classList.remove('is-resizing-row');
6015
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6646
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
6016
6647
  hSplitter.removeEventListener('pointermove', onMove);
6017
6648
  hSplitter.removeEventListener('pointerup', onUp);
6018
6649
  };
@@ -6039,7 +6670,7 @@ declare module 'bun:sqlite' {
6039
6670
  e.preventDefault();
6040
6671
  fSplitter.classList.add('is-dragging');
6041
6672
  shell.classList.add('is-resizing');
6042
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
6673
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
6043
6674
 
6044
6675
  const onMove = ev => {
6045
6676
  const ws = this.container.querySelector('.codelab-workspace');
@@ -6053,7 +6684,7 @@ declare module 'bun:sqlite' {
6053
6684
  const onUp = ev => {
6054
6685
  fSplitter.classList.remove('is-dragging');
6055
6686
  shell.classList.remove('is-resizing');
6056
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6687
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
6057
6688
  fSplitter.removeEventListener('pointermove', onMove);
6058
6689
  fSplitter.removeEventListener('pointerup', onUp);
6059
6690
  this._saveState();
@@ -6063,6 +6694,42 @@ declare module 'bun:sqlite' {
6063
6694
  fSplitter.addEventListener('pointerup', onUp);
6064
6695
  });
6065
6696
  }
6697
+
6698
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
6699
+ if (pSplitter) {
6700
+ pSplitter.addEventListener('dblclick', () => {
6701
+ shell.style.setProperty('--cl-preview-split-width', '44%');
6702
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
6703
+ });
6704
+
6705
+ pSplitter.addEventListener('pointerdown', e => {
6706
+ e.preventDefault();
6707
+ pSplitter.classList.add('is-dragging');
6708
+ shell.classList.add('is-resizing');
6709
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
6710
+
6711
+ const onMove = ev => {
6712
+ const ws = this.container.querySelector('.codelab-workspace');
6713
+ const rect = (ws || shell).getBoundingClientRect();
6714
+ const minW = 240;
6715
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
6716
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
6717
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
6718
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
6719
+ };
6720
+
6721
+ const onUp = ev => {
6722
+ pSplitter.classList.remove('is-dragging');
6723
+ shell.classList.remove('is-resizing');
6724
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
6725
+ pSplitter.removeEventListener('pointermove', onMove);
6726
+ pSplitter.removeEventListener('pointerup', onUp);
6727
+ };
6728
+
6729
+ pSplitter.addEventListener('pointermove', onMove);
6730
+ pSplitter.addEventListener('pointerup', onUp);
6731
+ });
6732
+ }
6066
6733
  }
6067
6734
 
6068
6735
  selectStep(idx, shouldJump = true) {
@@ -6291,6 +6958,9 @@ declare module 'bun:sqlite' {
6291
6958
  if (this.savedState.customFiles) {
6292
6959
  delete this.savedState.customFiles[key];
6293
6960
  }
6961
+ if (this.savedState.hasSnapshot) {
6962
+ delete this.savedState.hasSnapshot[key];
6963
+ }
6294
6964
  this._saveState();
6295
6965
  this._syncAllModels();
6296
6966
  this._syncActiveFileToView();
@@ -6396,7 +7066,9 @@ declare module 'bun:sqlite' {
6396
7066
  if (this.files['package.json']) {
6397
7067
  try {
6398
7068
  pkgJson = JSON.parse(this.files['package.json']);
6399
- } catch (_) {}
7069
+ } catch (err) {
7070
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
7071
+ }
6400
7072
  }
6401
7073
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
6402
7074
  pkgJson.dependencies = {};
@@ -7057,6 +7729,219 @@ declare module 'bun:sqlite' {
7057
7729
  return true;
7058
7730
  }
7059
7731
 
7732
+ exportProjectZip(options = {}) {
7733
+ const zipMod = root.CodeLabZip;
7734
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
7735
+ throw new Error('CodeLabZip engine is not loaded');
7736
+ }
7737
+ const bytes = zipMod.createZip(this.files || {});
7738
+ if (options && options.download) {
7739
+ try {
7740
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
7741
+ const blob = new Blob([bytes], { type: 'application/zip' });
7742
+ const url = URL.createObjectURL(blob);
7743
+ const a = document.createElement('a');
7744
+ a.href = url;
7745
+ a.download = `${this.labId || 'workspace'}.zip`;
7746
+ a.click();
7747
+ setTimeout(() => URL.revokeObjectURL(url), 500);
7748
+ }
7749
+ } catch (err) {
7750
+ this.logger.error('Failed to download project ZIP export.', err);
7751
+ }
7752
+ }
7753
+ return bytes;
7754
+ }
7755
+
7756
+ importProjectZip(zipBytes) {
7757
+ const zipMod = root.CodeLabZip;
7758
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
7759
+ throw new Error('CodeLabZip engine is not loaded');
7760
+ }
7761
+ const extracted = zipMod.extractZip(zipBytes);
7762
+ if (!extracted || typeof extracted !== 'object') return false;
7763
+ this.setFiles(extracted);
7764
+ this._syncFilesToShellVfs();
7765
+ return true;
7766
+ }
7767
+
7768
+ searchWorkspace(options) {
7769
+ const searchMod = root.CodeLabSearch;
7770
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
7771
+ throw new Error('CodeLabSearch engine is not loaded');
7772
+ }
7773
+ return searchMod.searchInFiles(this.files || {}, options);
7774
+ }
7775
+
7776
+ replaceInWorkspace(options) {
7777
+ const searchMod = root.CodeLabSearch;
7778
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
7779
+ throw new Error('CodeLabSearch engine is not loaded');
7780
+ }
7781
+ const res = searchMod.replaceInFiles(this.files || {}, options);
7782
+ if (res && res.files && res.filesModified > 0) {
7783
+ this.setFiles(res.files);
7784
+ this._syncFilesToShellVfs();
7785
+ }
7786
+ return res;
7787
+ }
7788
+
7789
+ getGitStatus() {
7790
+ const scmMod = root.CodeLabScm;
7791
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
7792
+ return [];
7793
+ }
7794
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
7795
+ return scmMod.computeGitStatus(gs, this.files || {});
7796
+ }
7797
+
7798
+ getDiagnostics() {
7799
+ const diagMod = root.CodeLabDiagnostics;
7800
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
7801
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
7802
+ }
7803
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
7804
+ return this._diagnosticsStore.getAll();
7805
+ }
7806
+ return [];
7807
+ }
7808
+
7809
+ showSearchModal(initialQuery = '') {
7810
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
7811
+ if (!slot) return;
7812
+ const q = String(initialQuery || '');
7813
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
7814
+ const rowsHtml = (results.matches || []).map((m) => `
7815
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
7816
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
7817
+ </div>
7818
+ `).join('');
7819
+ slot.innerHTML = `
7820
+ <div class="codelab-modal-backdrop">
7821
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
7822
+ <div class="codelab-modal__header">
7823
+ <span>Search &amp; Replace Across Workspace</span>
7824
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
7825
+ </div>
7826
+ <div class="codelab-modal__body">
7827
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
7828
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
7829
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
7830
+ </div>
7831
+ <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
7832
+ </div>
7833
+ </div>
7834
+ </div>
7835
+ `;
7836
+ }
7837
+
7838
+ showScmModal() {
7839
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
7840
+ if (!slot) return;
7841
+ const statusList = this.getGitStatus();
7842
+ const rowsHtml = statusList.map((entry) => `
7843
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
7844
+ <span>${escapeHtml(entry.path)}</span>
7845
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
7846
+ </div>
7847
+ `).join('');
7848
+ slot.innerHTML = `
7849
+ <div class="codelab-modal-backdrop">
7850
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
7851
+ <div class="codelab-modal__header">
7852
+ <span>Source Control (Git Status)</span>
7853
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
7854
+ </div>
7855
+ <div class="codelab-modal__body">
7856
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
7857
+ </div>
7858
+ </div>
7859
+ </div>
7860
+ `;
7861
+ }
7862
+
7863
+ showProblemsModal() {
7864
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
7865
+ if (!slot) return;
7866
+ const items = this.getDiagnostics();
7867
+ const rowsHtml = items.map((d) => `
7868
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
7869
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
7870
+ </div>
7871
+ `).join('');
7872
+ slot.innerHTML = `
7873
+ <div class="codelab-modal-backdrop">
7874
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
7875
+ <div class="codelab-modal__header">
7876
+ <span>Problems (${items.length})</span>
7877
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
7878
+ </div>
7879
+ <div class="codelab-modal__body">
7880
+ <div id="cl-problems-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">No problems have been detected in the workspace.</div>'}</div>
7881
+ </div>
7882
+ </div>
7883
+ </div>
7884
+ `;
7885
+ }
7886
+
7887
+ _ensureTerminalSessions() {
7888
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
7889
+ this._terminalSessions = [
7890
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
7891
+ ];
7892
+ this._activeTerminalSessionId = 'session-1';
7893
+ }
7894
+ return this._terminalSessions;
7895
+ }
7896
+
7897
+ listTerminalSessions() {
7898
+ const sessions = this._ensureTerminalSessions();
7899
+ return sessions.map((s) => ({
7900
+ id: s.id,
7901
+ name: s.name,
7902
+ active: s.id === this._activeTerminalSessionId,
7903
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
7904
+ }));
7905
+ }
7906
+
7907
+ createTerminalSession(name) {
7908
+ const sessions = this._ensureTerminalSessions();
7909
+ const nextNum = sessions.length + 1;
7910
+ const id = `session-${Date.now()}-${nextNum}`;
7911
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
7912
+ const newLogs = [];
7913
+ sessions.push({ id, name: label, logs: newLogs });
7914
+ this._activeTerminalSessionId = id;
7915
+ this.terminalLogs = newLogs;
7916
+ this._renderDrawerBody();
7917
+ return id;
7918
+ }
7919
+
7920
+ switchTerminalSession(id) {
7921
+ const sessions = this._ensureTerminalSessions();
7922
+ const target = sessions.find((s) => s.id === id || s.name === id);
7923
+ if (!target) return false;
7924
+ this._activeTerminalSessionId = target.id;
7925
+ this.terminalLogs = target.logs;
7926
+ this._renderDrawerBody();
7927
+ return true;
7928
+ }
7929
+
7930
+ closeTerminalSession(id) {
7931
+ const sessions = this._ensureTerminalSessions();
7932
+ if (sessions.length <= 1) return false;
7933
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
7934
+ if (idx === -1) return false;
7935
+ const removed = sessions.splice(idx, 1)[0];
7936
+ if (this._activeTerminalSessionId === removed.id) {
7937
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
7938
+ this._activeTerminalSessionId = next.id;
7939
+ this.terminalLogs = next.logs;
7940
+ }
7941
+ this._renderDrawerBody();
7942
+ return true;
7943
+ }
7944
+
7060
7945
  getFiles() {
7061
7946
  return { ...this.files };
7062
7947
  }
@@ -7064,7 +7949,7 @@ declare module 'bun:sqlite' {
7064
7949
  setFiles(filesMap) {
7065
7950
  if (!filesMap || typeof filesMap !== 'object') return;
7066
7951
  for (const model of this.models.values()) {
7067
- try { model.dispose(); } catch (_) {}
7952
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
7068
7953
  }
7069
7954
  this.models.clear();
7070
7955
  this.files = {};
@@ -7154,7 +8039,9 @@ declare module 'bun:sqlite' {
7154
8039
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
7155
8040
  try {
7156
8041
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
7157
- } catch (_) {}
8042
+ } catch (err) {
8043
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
8044
+ }
7158
8045
  }
7159
8046
  this._notifyCodeChange(clean, updated);
7160
8047
  }
@@ -7374,9 +8261,26 @@ declare module 'bun:sqlite' {
7374
8261
 
7375
8262
  destroy() {
7376
8263
  this.stopExecution();
8264
+ if (this._previewReloadTimer) {
8265
+ clearTimeout(this._previewReloadTimer);
8266
+ this._previewReloadTimer = null;
8267
+ }
7377
8268
  if (this._escHandler && typeof document !== 'undefined') {
7378
8269
  document.removeEventListener('keydown', this._escHandler);
7379
8270
  }
8271
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
8272
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
8273
+ }
8274
+ this._beforeUnloadHandler = null;
8275
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
8276
+ window.removeEventListener('message', this._previewViolationHandler);
8277
+ }
8278
+ this._previewViolationHandler = null;
8279
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
8280
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
8281
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
8282
+ }
8283
+ this._swMessageHandler = null;
7380
8284
  if (this._themeObserver) {
7381
8285
  this._themeObserver.disconnect();
7382
8286
  }
@@ -7437,7 +8341,9 @@ declare module 'bun:sqlite' {
7437
8341
  if (jsonScript && jsonScript.textContent) {
7438
8342
  try {
7439
8343
  inlineConfig = JSON.parse(jsonScript.textContent);
7440
- } catch (_) {}
8344
+ } catch (err) {
8345
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
8346
+ }
7441
8347
  }
7442
8348
 
7443
8349
  // Parse optional files JSON attribute
@@ -7446,7 +8352,9 @@ declare module 'bun:sqlite' {
7446
8352
  if (filesAttr) {
7447
8353
  try {
7448
8354
  attrFiles = JSON.parse(filesAttr);
7449
- } catch (_) {}
8355
+ } catch (err) {
8356
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
8357
+ }
7450
8358
  }
7451
8359
 
7452
8360
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -7489,6 +8397,19 @@ declare module 'bun:sqlite' {
7489
8397
  reset() { if (this._instance) this._instance.reset(); }
7490
8398
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
7491
8399
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
8400
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
8401
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
8402
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
8403
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
8404
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
8405
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
8406
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
8407
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
8408
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
8409
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
8410
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
8411
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
8412
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
7492
8413
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
7493
8414
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
7494
8415
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -7523,9 +8444,42 @@ declare module 'bun:sqlite' {
7523
8444
  Workbench: CodeLabWorkbench,
7524
8445
  CodeLabWorkbench,
7525
8446
  CodeLabElement: CodeLabElementClass,
8447
+ CodeLabError,
8448
+ isCodeLabError,
8449
+ createLogger,
8450
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
8451
+ html,
8452
+ raw,
8453
+ isSafeHtml,
8454
+ escapeHtml,
8455
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
7526
8456
  Runtime: root.CodeLabRuntime,
7527
8457
  Shell: root.CodeLabShell,
7528
8458
  Terminal: root.CodeLabTerminal,
8459
+ zip: root.CodeLabZip || null,
8460
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
8461
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
8462
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
8463
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
8464
+ storage: root.CodeLabStorage || null,
8465
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
8466
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
8467
+ search: root.CodeLabSearch || null,
8468
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
8469
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
8470
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
8471
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
8472
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
8473
+ diagnostics: root.CodeLabDiagnostics || null,
8474
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
8475
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
8476
+ scm: root.CodeLabScm || null,
8477
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
8478
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
8479
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
8480
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
8481
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
8482
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
7529
8483
  renderMarkdown: renderSimpleMarkdown,
7530
8484
  renderSimpleMarkdown: renderSimpleMarkdown,
7531
8485
  extensions: {