@innovatorved/code-lab 0.1.8 → 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.
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -267,13 +267,22 @@ var CodeLabCsp = (() => {
267
267
  document.body.appendChild(existing);
268
268
  }
269
269
  existing.textContent = '';
270
+ var topBar = document.createElement('div');
271
+ topBar.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid rgba(248,113,113,0.28);';
270
272
  var header = document.createElement('div');
271
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
273
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
272
274
  header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
275
+ var closeBtn = document.createElement('button');
276
+ closeBtn.type = 'button';
277
+ closeBtn.textContent = 'Dismiss \xD7';
278
+ closeBtn.style.cssText = 'background:rgba(255,255,255,0.08);color:#e2e8f0;border:1px solid rgba(255,255,255,0.16);border-radius:6px;padding:4px 10px;font-size:11px;cursor:pointer;font-family:inherit;';
279
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
280
+ topBar.appendChild(header);
281
+ topBar.appendChild(closeBtn);
273
282
  var pre = document.createElement('pre');
274
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
283
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
275
284
  pre.textContent = String(stack || msg || '');
276
- existing.appendChild(header);
285
+ existing.appendChild(topBar);
277
286
  existing.appendChild(pre);
278
287
  } catch (err) {
279
288
  void err;
@@ -314,6 +323,189 @@ var CodeLabCsp = (() => {
314
323
  void err;
315
324
  }
316
325
  });
326
+
327
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
328
+ var pendingFetches = new Map();
329
+ var fetchSeq = 0;
330
+ function parseLoopbackTarget(rawUrl) {
331
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
332
+ var trimmed = rawUrl.trim();
333
+ if (!trimmed) return null;
334
+ var lower = trimmed.toLowerCase();
335
+ if (lower.indexOf('data:') === 0 || lower.indexOf('blob:') === 0 || lower.indexOf('mailto:') === 0 || lower.indexOf('tel:') === 0 || lower.indexOf('javascript:') === 0 || trimmed.charAt(0) === '#') return null;
336
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
337
+ try {
338
+ var u = new URL(trimmed);
339
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
340
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
341
+ }
342
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
343
+ var rest = u.pathname.slice('/__preview/'.length);
344
+ var slashIdx = rest.indexOf('/');
345
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
346
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
347
+ var portNum = Number(portStr);
348
+ if (portNum > 0) {
349
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
350
+ }
351
+ }
352
+ } catch (e) { void e; }
353
+ return null;
354
+ }
355
+ if (trimmed.indexOf('/__preview/') === 0) {
356
+ var restRel = trimmed.slice('/__preview/'.length);
357
+ var sIdx = restRel.indexOf('/');
358
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
359
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
360
+ var pNum = Number(pStr);
361
+ if (pNum > 0) {
362
+ return { port: pNum, path: sPath || '/' };
363
+ }
364
+ }
365
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
366
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
367
+ return { port: null, path: pathPart };
368
+ }
369
+
370
+ window.addEventListener('message', function (event) {
371
+ var data = event && event.data;
372
+ if (!data || typeof data !== 'object') return;
373
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
374
+ var entry = pendingFetches.get(data.reqId);
375
+ if (!entry) return;
376
+ pendingFetches.delete(data.reqId);
377
+ entry.resolve(data);
378
+ }
379
+ });
380
+
381
+ if (typeof window.fetch === 'function') {
382
+ var origFetch = window.fetch.bind(window);
383
+ window.fetch = function (input, init) {
384
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
385
+ var target = parseLoopbackTarget(urlStr);
386
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
387
+ var isOpaque = false;
388
+ try {
389
+ var lowerUrl = urlStr.toLowerCase();
390
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
391
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
392
+ } catch (e) { isOpaque = true; void e; }
393
+ if (!target || !isOpaque || window.parent === window) {
394
+ return origFetch(input, init);
395
+ }
396
+ return new Promise(function (resolve, reject) {
397
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
398
+ var method = (init && init.method) || (input && input.method) || 'GET';
399
+ var headersObj = {};
400
+ try {
401
+ var rawH = (init && init.headers) || (input && input.headers);
402
+ if (rawH) {
403
+ if (typeof rawH.forEach === 'function') {
404
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
405
+ } else if (Array.isArray(rawH)) {
406
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
407
+ } else if (typeof rawH === 'object') {
408
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
409
+ }
410
+ }
411
+ } catch (e) { void e; }
412
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
413
+ var timer = setTimeout(function () {
414
+ if (pendingFetches.has(reqId)) {
415
+ pendingFetches.delete(reqId);
416
+ origFetch(input, init).then(resolve, reject);
417
+ }
418
+ }, 5000);
419
+ pendingFetches.set(reqId, {
420
+ resolve: function (payload) {
421
+ clearTimeout(timer);
422
+ if (payload && payload.error) {
423
+ reject(new TypeError(String(payload.error)));
424
+ return;
425
+ }
426
+ var status = Number(payload && payload.status) || 200;
427
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
428
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
429
+ try {
430
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
431
+ } catch (err) {
432
+ void err;
433
+ resolve({
434
+ ok: status >= 200 && status < 300,
435
+ status: status,
436
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
437
+ text: function () { return Promise.resolve(body); },
438
+ json: function () { return Promise.resolve(JSON.parse(body)); }
439
+ });
440
+ }
441
+ }
442
+ });
443
+ try {
444
+ parent.postMessage({
445
+ type: 'codelab:preview-fetch',
446
+ reqId: reqId,
447
+ port: target.port,
448
+ path: target.path,
449
+ method: String(method).toUpperCase(),
450
+ headers: headersObj,
451
+ body: bodyStr
452
+ }, '*');
453
+ } catch (err) {
454
+ clearTimeout(timer);
455
+ pendingFetches.delete(reqId);
456
+ origFetch(input, init).then(resolve, reject);
457
+ }
458
+ });
459
+ };
460
+ }
461
+
462
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
463
+ document.addEventListener('click', function (event) {
464
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
465
+ var el = event.target;
466
+ while (el && el.tagName !== 'A') el = el.parentElement;
467
+ if (!el || !el.getAttribute) return;
468
+ var href = el.getAttribute('href');
469
+ var targetAttr = el.getAttribute('target');
470
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
471
+ var lowerHref = href.toLowerCase();
472
+ if (href.charAt(0) === '#' || lowerHref.indexOf('mailto:') === 0 || lowerHref.indexOf('tel:') === 0 || lowerHref.indexOf('javascript:') === 0 || lowerHref.indexOf('data:') === 0 || lowerHref.indexOf('blob:') === 0) return;
473
+ var parsed = parseLoopbackTarget(href);
474
+ if (!parsed) return;
475
+ event.preventDefault();
476
+ try {
477
+ parent.postMessage({
478
+ type: 'codelab:preview-navigate',
479
+ port: parsed.port,
480
+ path: parsed.path
481
+ }, '*');
482
+ } catch (e) { void e; }
483
+ });
484
+
485
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
486
+ try {
487
+ ['pushState', 'replaceState'].forEach(function (method) {
488
+ var orig = history[method];
489
+ if (typeof orig !== 'function') return;
490
+ history[method] = function (state, title, url) {
491
+ var ret;
492
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
493
+ if (url !== undefined && url !== null) {
494
+ var parsed = parseLoopbackTarget(String(url));
495
+ if (parsed) {
496
+ try {
497
+ parent.postMessage({
498
+ type: 'codelab:preview-url-change',
499
+ path: parsed.path,
500
+ replace: method === 'replaceState'
501
+ }, '*');
502
+ } catch (e) { void e; }
503
+ }
504
+ }
505
+ return ret;
506
+ };
507
+ });
508
+ } catch (e) { void e; }
317
509
  })();
318
510
  <\/script>`;
319
511
  }
@@ -12989,10 +13181,10 @@ if (typeof module !== 'undefined' && module.exports) {
12989
13181
  return imports;
12990
13182
  }
12991
13183
 
12992
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
12993
- const scripts = [];
13184
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
13185
+ const files = [];
12994
13186
  const walk = (dir, depth) => {
12995
- if (depth > 8 || scripts.length >= maxFiles) return;
13187
+ if (depth > 8 || files.length >= maxFiles) return;
12996
13188
  let entries = [];
12997
13189
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
12998
13190
  for (const name of entries) {
@@ -13003,13 +13195,23 @@ if (typeof module !== 'undefined' && module.exports) {
13003
13195
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
13004
13196
  if (dirFlag) {
13005
13197
  walk(full, depth + 1);
13006
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
13007
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
13198
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
13199
+ try {
13200
+ const content = vfs.readFileSync(full, 'utf8');
13201
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
13202
+ files.push({ full, rel, content });
13203
+ } catch (err) {
13204
+ _shellLogger.debug('Preview script read skipped.', full, err);
13205
+ }
13008
13206
  }
13009
13207
  }
13010
13208
  };
13011
13209
  walk(rootDir, 0);
13012
- return scripts;
13210
+ return files;
13211
+ }
13212
+
13213
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
13214
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
13013
13215
  }
13014
13216
 
13015
13217
  function injectPreviewExtras(html, importMap) {
@@ -13034,12 +13236,6 @@ if (typeof module !== 'undefined' && module.exports) {
13034
13236
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
13035
13237
  while (taken.has(port)) port++;
13036
13238
 
13037
- const specifiers = new Set();
13038
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
13039
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
13040
- }
13041
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13042
-
13043
13239
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
13044
13240
  const isDir = (p) => {
13045
13241
  try {
@@ -13047,8 +13243,109 @@ if (typeof module !== 'undefined' && module.exports) {
13047
13243
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
13048
13244
  } catch (_) { return false; }
13049
13245
  };
13246
+ const isFile = (p) => exists(p) && !isDir(p);
13050
13247
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
13051
13248
 
13249
+ const resolveLocalTarget = (baseDir, rawSpec) => {
13250
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
13251
+ const clean = rawSpec.split(/[?#]/)[0].trim();
13252
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
13253
+ const candidateBase = clean.startsWith('/')
13254
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
13255
+ : PosixPath.join(baseDir, clean);
13256
+ if (isFile(candidateBase)) return candidateBase;
13257
+ const cands = [
13258
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
13259
+ candidateBase + '.mjs', candidateBase + '.cjs',
13260
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
13261
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
13262
+ ];
13263
+ for (const c of cands) {
13264
+ if (isFile(c)) return c;
13265
+ }
13266
+ return null;
13267
+ };
13268
+
13269
+ const toLocalImportKey = (fullPath) => {
13270
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
13271
+ return `@codelab-local/${rel}`;
13272
+ };
13273
+
13274
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
13275
+ let out = code;
13276
+ try {
13277
+ const rm = getRuntimeModule();
13278
+ if (rm && typeof rm.transpileForBrowser === 'function') {
13279
+ out = rm.transpileForBrowser(out, sourcePath);
13280
+ }
13281
+ } catch (err) {
13282
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
13283
+ }
13284
+ const fromDir = PosixPath.dirname(sourcePath);
13285
+ const rewriteSpec = (spec) => {
13286
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
13287
+ const resolved = resolveLocalTarget(fromDir, spec);
13288
+ return resolved ? toLocalImportKey(resolved) : spec;
13289
+ };
13290
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13291
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13292
+ return out;
13293
+ };
13294
+
13295
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
13296
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
13297
+ const specifiers = new Set();
13298
+ for (const f of scriptFiles) {
13299
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
13300
+ }
13301
+ // Also scan inline module scripts in HTML for bare specifiers
13302
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
13303
+ let inlineMatch;
13304
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
13305
+ if (inlineMatch[1]) {
13306
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
13307
+ }
13308
+ }
13309
+
13310
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13311
+ for (const f of scriptFiles) {
13312
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
13313
+ const key = toLocalImportKey(f.full);
13314
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
13315
+ }
13316
+
13317
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
13318
+ let transformedHtml = htmlBody;
13319
+
13320
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
13321
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
13322
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
13323
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
13324
+ if (!hrefMatch) return fullTag;
13325
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
13326
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
13327
+ const cssContent = readText(cssTarget);
13328
+ if (cssContent === null) return fullTag;
13329
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
13330
+ });
13331
+
13332
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
13333
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
13334
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
13335
+ if (!srcMatch) return fullTag;
13336
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
13337
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
13338
+ const rawScript = readText(scriptTarget);
13339
+ if (rawScript === null) return fullTag;
13340
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
13341
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
13342
+ const typeAttr = isMod ? ' type="module"' : '';
13343
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
13344
+ });
13345
+
13346
+ return injectPreviewExtras(transformedHtml, importMap);
13347
+ };
13348
+
13052
13349
  const handler = async (request) => {
13053
13350
  let pathname = '/';
13054
13351
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -13083,7 +13380,7 @@ if (typeof module !== 'undefined' && module.exports) {
13083
13380
  let body = readText(target);
13084
13381
  if (body === null) body = '';
13085
13382
  if (/\.html?$/i.test(target)) {
13086
- body = injectPreviewExtras(body, importMap);
13383
+ body = buildHtmlPreviewResponse(body, target);
13087
13384
  } else if (isPreviewScriptPath(target)) {
13088
13385
  try {
13089
13386
  const rm = getRuntimeModule();
@@ -18449,7 +18746,7 @@ if (typeof module !== 'undefined' && module.exports) {
18449
18746
 
18450
18747
  // The bundler rewrites this literal from package.json at build time. Keeping
18451
18748
  // the fallback in sync lets tests require src/workbench.js directly.
18452
- const CODELAB_VERSION = '0.1.8';
18749
+ const CODELAB_VERSION = '0.1.9';
18453
18750
 
18454
18751
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
18455
18752
  const NODE_AMBIENT_DTS = `
@@ -19768,6 +20065,10 @@ declare module 'bun:sqlite' {
19768
20065
  path: '/',
19769
20066
  url: '',
19770
20067
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
20068
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
20069
+ maximized: false,
20070
+ consoleOpen: false,
20071
+ consoleLogs: [],
19771
20072
  loading: false,
19772
20073
  error: null,
19773
20074
  srcdoc: '',
@@ -19779,6 +20080,7 @@ declare module 'bun:sqlite' {
19779
20080
  this._previewSwRegistration = null;
19780
20081
  this._previewViolationHandler = null;
19781
20082
  this._swMessageHandler = null;
20083
+ this._beforeUnloadHandler = null;
19782
20084
  this._portToasts = new Map();
19783
20085
  this.isFullscreen = false;
19784
20086
  this.isRunning = false;
@@ -20125,6 +20427,11 @@ declare module 'bun:sqlite' {
20125
20427
  const key = `${this.mode}:${this.lang}`;
20126
20428
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
20127
20429
  customFiles[key] = { ...this.files };
20430
+ const hasSnapshot = Object.assign(
20431
+ {},
20432
+ (this.savedState && this.savedState.hasSnapshot) || {},
20433
+ { [key]: true }
20434
+ );
20128
20435
  const completedArr = Array.from(this.completedSteps);
20129
20436
  const state = {
20130
20437
  mode: this.mode,
@@ -20132,6 +20439,7 @@ declare module 'bun:sqlite' {
20132
20439
  activeStepIndex: this.activeStepIndex,
20133
20440
  completedSteps: completedArr,
20134
20441
  customFiles,
20442
+ hasSnapshot,
20135
20443
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
20136
20444
  activeFile: this.activeFile,
20137
20445
  folders: Array.from(this.folders || []),
@@ -20156,6 +20464,20 @@ declare module 'bun:sqlite' {
20156
20464
  safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20157
20465
  safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
20158
20466
  ];
20467
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
20468
+ try {
20469
+ if (!this._idbStorage) {
20470
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
20471
+ }
20472
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
20473
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
20474
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
20475
+ });
20476
+ }
20477
+ } catch (err) {
20478
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
20479
+ }
20480
+ }
20159
20481
  if (persisted.includes(false)) {
20160
20482
  this._reportPersistenceFailure(safeStorageSet._lastError);
20161
20483
  } else {
@@ -20308,6 +20630,9 @@ declare module 'bun:sqlite' {
20308
20630
  const key = `${this.mode}:${this.lang}`;
20309
20631
  const saved = this.savedState.customFiles?.[key];
20310
20632
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
20633
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
20634
+ return { ...saved };
20635
+ }
20311
20636
  if (saved && Object.keys(saved).length > 0) {
20312
20637
  return { ...base, ...saved };
20313
20638
  }
@@ -20520,6 +20845,10 @@ declare module 'bun:sqlite' {
20520
20845
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
20521
20846
  </div>
20522
20847
  </div>
20848
+
20849
+ <!-- Right-Hand Split Web Preview Pane -->
20850
+ <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>
20851
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
20523
20852
  </div>
20524
20853
 
20525
20854
  <!-- Interactive Horizontal Splitter -->
@@ -22901,6 +23230,10 @@ declare module 'bun:sqlite' {
22901
23230
  type: level === 'error' ? 'stderr' : 'stdout',
22902
23231
  text: `[Preview ${level.toUpperCase()}] ${text}`
22903
23232
  });
23233
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23234
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
23235
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
23236
+ this._updatePreviewConsoleUI();
22904
23237
  this._emitEvent('preview-console', { level, text, args });
22905
23238
  } else if (data.type === 'codelab:preview-error') {
22906
23239
  const msg = String(data.message || 'Uncaught runtime error');
@@ -22915,9 +23248,66 @@ declare module 'bun:sqlite' {
22915
23248
  type: 'stderr',
22916
23249
  text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
22917
23250
  });
23251
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23252
+ this.previewState.consoleLogs.push({
23253
+ level: 'error',
23254
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
23255
+ timestamp: new Date().toLocaleTimeString()
23256
+ });
23257
+ this._updatePreviewConsoleUI();
22918
23258
  this._emitEvent('preview-error', this.previewState.runtimeError);
22919
23259
  } else if (data.type === 'codelab:preview-error-clear') {
22920
23260
  this.previewState.runtimeError = null;
23261
+ } else if (data.type === 'codelab:preview-fetch') {
23262
+ const reqId = data.reqId || data.id;
23263
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
23264
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
23265
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
23266
+ this._dispatchPreviewRequest({
23267
+ port: targetPort,
23268
+ url: targetUrl,
23269
+ method: data.method || 'GET',
23270
+ headers: data.headers || {},
23271
+ body: data.body !== undefined ? data.body : null
23272
+ })
23273
+ .then((res) => {
23274
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
23275
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
23276
+ if (this.drawerTab === 'network') this._renderDrawerBody();
23277
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23278
+ iframe.contentWindow.postMessage({
23279
+ type: 'codelab:preview-fetch-res',
23280
+ reqId,
23281
+ id: reqId,
23282
+ status: res.status || 200,
23283
+ statusText: res.statusText || 'OK',
23284
+ headers: res.headers || {},
23285
+ body: res.body || ''
23286
+ }, '*');
23287
+ }
23288
+ })
23289
+ .catch((err) => {
23290
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23291
+ iframe.contentWindow.postMessage({
23292
+ type: 'codelab:preview-fetch-res',
23293
+ reqId,
23294
+ id: reqId,
23295
+ error: String((err && err.message) || err)
23296
+ }, '*');
23297
+ }
23298
+ });
23299
+ } else if (data.type === 'codelab:preview-navigate') {
23300
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
23301
+ if (navHref) {
23302
+ this._previewGo(String(navHref));
23303
+ }
23304
+ } else if (data.type === 'codelab:preview-url-change') {
23305
+ if (data.path && typeof data.path === 'string') {
23306
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
23307
+ this.previewState.url = this._previewUrl();
23308
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
23309
+ if (input) input.value = this.previewState.url;
23310
+ }
22921
23311
  }
22922
23312
  };
22923
23313
  window.addEventListener('message', this._previewViolationHandler);
@@ -22981,7 +23371,12 @@ declare module 'bun:sqlite' {
22981
23371
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
22982
23372
  this.previewHistory.push(this.previewState.url);
22983
23373
  this.previewHistoryIdx = this.previewHistory.length - 1;
22984
- this.switchDrawerTab('preview');
23374
+ if (this.previewState.dockMode === 'split') {
23375
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23376
+ if (splitHost) this._renderWebPreview(splitHost);
23377
+ } else {
23378
+ this.switchDrawerTab('preview');
23379
+ }
22985
23380
  return this._previewLoadPromise || Promise.resolve();
22986
23381
  }
22987
23382
 
@@ -23100,7 +23495,12 @@ declare module 'bun:sqlite' {
23100
23495
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
23101
23496
  this.previewHistory.push(url);
23102
23497
  this.previewHistoryIdx = this.previewHistory.length - 1;
23103
- this.switchDrawerTab('preview');
23498
+ if (this.previewState.dockMode === 'split') {
23499
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23500
+ if (splitHost) this._renderWebPreview(splitHost);
23501
+ } else {
23502
+ this.switchDrawerTab('preview');
23503
+ }
23104
23504
  return this._previewLoadPromise || Promise.resolve();
23105
23505
  }
23106
23506
 
@@ -23141,6 +23541,94 @@ declare module 'bun:sqlite' {
23141
23541
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
23142
23542
  this.previewState.frameMode = mode;
23143
23543
  this._renderDrawerBody();
23544
+ if (this.previewState.dockMode === 'split') {
23545
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23546
+ if (splitHost) this._renderWebPreview(splitHost);
23547
+ }
23548
+ }
23549
+
23550
+ _togglePreviewDock() {
23551
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
23552
+ this._previewRenderKey = null;
23553
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23554
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23555
+ if (this.previewState.dockMode === 'split') {
23556
+ if (splitBar) splitBar.style.display = 'block';
23557
+ if (splitHost) {
23558
+ splitHost.style.display = 'flex';
23559
+ this._renderWebPreview(splitHost);
23560
+ }
23561
+ if (this.drawerTab === 'preview') {
23562
+ this.switchDrawerTab('terminal');
23563
+ } else {
23564
+ this._renderDrawerBody();
23565
+ }
23566
+ } else {
23567
+ if (splitBar) splitBar.style.display = 'none';
23568
+ if (splitHost) {
23569
+ splitHost.style.display = 'none';
23570
+ splitHost.innerHTML = '';
23571
+ }
23572
+ this.switchDrawerTab('preview');
23573
+ }
23574
+ if (this.editor && typeof this.editor.layout === 'function') {
23575
+ setTimeout(() => {
23576
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
23577
+ }, 30);
23578
+ }
23579
+ }
23580
+
23581
+ _togglePreviewMaximize() {
23582
+ this.previewState.maximized = !this.previewState.maximized;
23583
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
23584
+ if (previewEl) {
23585
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
23586
+ }
23587
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
23588
+ if (maxBtn) {
23589
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
23590
+ }
23591
+ }
23592
+
23593
+ _togglePreviewConsole() {
23594
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
23595
+ this._updatePreviewConsoleUI();
23596
+ }
23597
+
23598
+ _clearPreviewConsole() {
23599
+ this.previewState.consoleLogs = [];
23600
+ this._updatePreviewConsoleUI();
23601
+ }
23602
+
23603
+ _updatePreviewConsoleUI() {
23604
+ if (!this.container) return;
23605
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
23606
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
23607
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
23608
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
23609
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
23610
+ if (consolePill) {
23611
+ consolePill.textContent = String(logs.length);
23612
+ }
23613
+ if (consoleBtn) {
23614
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
23615
+ }
23616
+ if (consoleDrawer) {
23617
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
23618
+ }
23619
+ if (consoleBody) {
23620
+ if (logs.length === 0) {
23621
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
23622
+ } else {
23623
+ consoleBody.innerHTML = logs.map((entry) => `
23624
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
23625
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
23626
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
23627
+ </div>
23628
+ `).join('');
23629
+ consoleBody.scrollTop = consoleBody.scrollHeight;
23630
+ }
23631
+ }
23144
23632
  }
23145
23633
 
23146
23634
  _renderWebPreviewControls() {
@@ -23152,6 +23640,7 @@ declare module 'bun:sqlite' {
23152
23640
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
23153
23641
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
23154
23642
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
23643
+ this._updatePreviewConsoleUI();
23155
23644
  }
23156
23645
 
23157
23646
  _popoutPreview() {
@@ -23172,8 +23661,32 @@ declare module 'bun:sqlite' {
23172
23661
  _renderWebPreview(bodyEl) {
23173
23662
  if (!bodyEl) return;
23174
23663
  this._warnPreviewIsolation();
23175
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
23176
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23664
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23665
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23666
+
23667
+ let targetHost = bodyEl;
23668
+ if (this.previewState.dockMode === 'split' && splitHost) {
23669
+ if (splitBar) splitBar.style.display = 'block';
23670
+ splitHost.style.display = 'flex';
23671
+ if (bodyEl !== splitHost) {
23672
+ bodyEl.innerHTML = `
23673
+ <div class="codelab-preview-split-notice">
23674
+ <span>Web Preview is docked to the right split pane.</span>
23675
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
23676
+ </div>
23677
+ `;
23678
+ }
23679
+ targetHost = splitHost;
23680
+ } else {
23681
+ if (splitBar) splitBar.style.display = 'none';
23682
+ if (splitHost && bodyEl !== splitHost) {
23683
+ splitHost.style.display = 'none';
23684
+ splitHost.innerHTML = '';
23685
+ }
23686
+ }
23687
+
23688
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
23689
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23177
23690
  this._renderWebPreviewControls();
23178
23691
  return;
23179
23692
  }
@@ -23204,8 +23717,11 @@ declare module 'bun:sqlite' {
23204
23717
  ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23205
23718
  : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23206
23719
 
23207
- bodyEl.innerHTML = `
23208
- <div class="codelab-preview">
23720
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
23721
+ const isSplit = this.previewState.dockMode === 'split';
23722
+
23723
+ targetHost.innerHTML = `
23724
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
23209
23725
  <div class="codelab-preview-chrome">
23210
23726
  <div class="codelab-preview-nav">
23211
23727
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -23221,11 +23737,30 @@ declare module 'bun:sqlite' {
23221
23737
  </div>
23222
23738
  <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23223
23739
  <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
23740
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
23741
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
23742
+ </button>
23743
+ <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'}">
23744
+ ${CL_ICONS.layout || '◫'}
23745
+ </button>
23746
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
23747
+ ${CL_ICONS.maximize || '⛶'}
23748
+ </button>
23224
23749
  <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>
23225
23750
  </div>
23226
23751
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
23227
23752
  <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>
23228
23753
  </div>
23754
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
23755
+ <div class="codelab-preview-console__bar">
23756
+ <span>Preview Console</span>
23757
+ <div style="display:flex;align-items:center;gap:6px;">
23758
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
23759
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
23760
+ </div>
23761
+ </div>
23762
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
23763
+ </div>
23229
23764
  ${servers.length
23230
23765
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
23231
23766
  : `<div class="codelab-preview-empty">
@@ -23238,6 +23773,7 @@ declare module 'bun:sqlite' {
23238
23773
  </div>
23239
23774
  `;
23240
23775
  this._updatePreviewCspStatus();
23776
+ this._updatePreviewConsoleUI();
23241
23777
  this._loadPreviewFrame();
23242
23778
  }
23243
23779
 
@@ -23254,11 +23790,12 @@ declare module 'bun:sqlite' {
23254
23790
  this.previewState.error = 'No port selected';
23255
23791
  return Promise.resolve();
23256
23792
  }
23793
+ this._syncFilesToShellVfs();
23257
23794
  const fullUrl = this._previewUrl();
23258
23795
  this.previewState.loading = true;
23259
23796
  this.previewState.error = null;
23260
23797
 
23261
- if (this._previewSwReady) {
23798
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
23262
23799
  try {
23263
23800
  const u = new URL(fullUrl);
23264
23801
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
@@ -23270,8 +23807,8 @@ declare module 'bun:sqlite' {
23270
23807
  }
23271
23808
  }
23272
23809
 
23273
- // Fallback (no Service Worker): dispatch via the virtual port table and
23274
- // inline the response with an injected <base> for relative asset URLs.
23810
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
23811
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
23275
23812
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
23276
23813
  .then((res) => {
23277
23814
  let body = res.body || '';
@@ -23657,7 +24194,7 @@ declare module 'bun:sqlite' {
23657
24194
  this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
23658
24195
  }
23659
24196
  }
23660
- if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
24197
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
23661
24198
  if (this._previewReloadTimer) {
23662
24199
  clearTimeout(this._previewReloadTimer);
23663
24200
  }
@@ -23833,6 +24370,16 @@ declare module 'bun:sqlite' {
23833
24370
  };
23834
24371
  if (typeof document !== 'undefined') {
23835
24372
  document.addEventListener('keydown', this._escHandler);
24373
+ this._beforeUnloadHandler = () => {
24374
+ if (document.visibilityState === 'hidden') {
24375
+ try {
24376
+ this._saveState();
24377
+ } catch (err) {
24378
+ void err;
24379
+ }
24380
+ }
24381
+ };
24382
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
23836
24383
  }
23837
24384
 
23838
24385
  this.container.addEventListener('keydown', e => {
@@ -24279,15 +24826,29 @@ declare module 'bun:sqlite' {
24279
24826
  this._previewSetFrameMode(actionBtn.dataset.mode);
24280
24827
  } else if (action === 'preview-popout') {
24281
24828
  this._popoutPreview();
24829
+ } else if (action === 'preview-dock-toggle') {
24830
+ this._togglePreviewDock();
24831
+ } else if (action === 'preview-maximize') {
24832
+ this._togglePreviewMaximize();
24833
+ } else if (action === 'preview-console-toggle') {
24834
+ this._togglePreviewConsole();
24835
+ } else if (action === 'preview-console-clear') {
24836
+ this._clearPreviewConsole();
24282
24837
  } else if (action === 'open-port-client') {
24283
- const port = actionBtn.dataset.port;
24838
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
24284
24839
  if (port) {
24285
24840
  this.httpClientUrl = `http://localhost:${port}/`;
24841
+ if (this.httpClientState) {
24842
+ this.httpClientState.url = `http://localhost:${port}/`;
24843
+ }
24286
24844
  this._renderDrawerBody();
24287
24845
  }
24288
24846
  } else if (action === 'stop-port') {
24289
- const port = Number(actionBtn.dataset.port);
24847
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
24290
24848
  if (port) {
24849
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
24850
+ this.portTable.closeServer(port);
24851
+ }
24291
24852
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
24292
24853
  this.shell.portTable.unregister(port);
24293
24854
  }
@@ -24297,18 +24858,32 @@ declare module 'bun:sqlite' {
24297
24858
  } else if (action === 'http-send') {
24298
24859
  this._sendHttpClientRequest();
24299
24860
  } else if (action === 'http-tab') {
24300
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
24861
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
24862
+ this.httpActiveTab = nextTab;
24863
+ if (this.httpClientState) {
24864
+ this.httpClientState.activeResponseTab = nextTab;
24865
+ }
24301
24866
  this._renderDrawerBody();
24302
24867
  } else if (action === 'clear-net-traces') {
24303
24868
  this.lastHttpTrace = [];
24304
24869
  this.selectedNetTraceIdx = null;
24870
+ if (this.networkFilter) {
24871
+ this.networkFilter.selectedTraceId = null;
24872
+ }
24305
24873
  this._renderDrawerBody();
24306
24874
  } else if (action === 'select-net-trace') {
24875
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
24307
24876
  const idx = Number(actionBtn.dataset.traceIdx);
24308
24877
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
24878
+ if (this.networkFilter) {
24879
+ this.networkFilter.selectedTraceId = traceId;
24880
+ }
24309
24881
  this._renderDrawerBody();
24310
24882
  } else if (action === 'close-net-detail') {
24311
24883
  this.selectedNetTraceIdx = null;
24884
+ if (this.networkFilter) {
24885
+ this.networkFilter.selectedTraceId = null;
24886
+ }
24312
24887
  this._renderDrawerBody();
24313
24888
  }
24314
24889
  return;
@@ -24808,6 +25383,42 @@ declare module 'bun:sqlite' {
24808
25383
  fSplitter.addEventListener('pointerup', onUp);
24809
25384
  });
24810
25385
  }
25386
+
25387
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
25388
+ if (pSplitter) {
25389
+ pSplitter.addEventListener('dblclick', () => {
25390
+ shell.style.setProperty('--cl-preview-split-width', '44%');
25391
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25392
+ });
25393
+
25394
+ pSplitter.addEventListener('pointerdown', e => {
25395
+ e.preventDefault();
25396
+ pSplitter.classList.add('is-dragging');
25397
+ shell.classList.add('is-resizing');
25398
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
25399
+
25400
+ const onMove = ev => {
25401
+ const ws = this.container.querySelector('.codelab-workspace');
25402
+ const rect = (ws || shell).getBoundingClientRect();
25403
+ const minW = 240;
25404
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
25405
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
25406
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
25407
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25408
+ };
25409
+
25410
+ const onUp = ev => {
25411
+ pSplitter.classList.remove('is-dragging');
25412
+ shell.classList.remove('is-resizing');
25413
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
25414
+ pSplitter.removeEventListener('pointermove', onMove);
25415
+ pSplitter.removeEventListener('pointerup', onUp);
25416
+ };
25417
+
25418
+ pSplitter.addEventListener('pointermove', onMove);
25419
+ pSplitter.addEventListener('pointerup', onUp);
25420
+ });
25421
+ }
24811
25422
  }
24812
25423
 
24813
25424
  selectStep(idx, shouldJump = true) {
@@ -25036,6 +25647,9 @@ declare module 'bun:sqlite' {
25036
25647
  if (this.savedState.customFiles) {
25037
25648
  delete this.savedState.customFiles[key];
25038
25649
  }
25650
+ if (this.savedState.hasSnapshot) {
25651
+ delete this.savedState.hasSnapshot[key];
25652
+ }
25039
25653
  this._saveState();
25040
25654
  this._syncAllModels();
25041
25655
  this._syncActiveFileToView();
@@ -26343,6 +26957,10 @@ declare module 'bun:sqlite' {
26343
26957
  if (this._escHandler && typeof document !== 'undefined') {
26344
26958
  document.removeEventListener('keydown', this._escHandler);
26345
26959
  }
26960
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
26961
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
26962
+ }
26963
+ this._beforeUnloadHandler = null;
26346
26964
  if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26347
26965
  window.removeEventListener('message', this._previewViolationHandler);
26348
26966
  }
@@ -26612,7 +27230,7 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
26612
27230
  const mount = CodeLab ? CodeLab.mount : null;
26613
27231
  const create = CodeLab ? CodeLab.create : null;
26614
27232
  const unmount = CodeLab ? CodeLab.unmount : null;
26615
- const version = CodeLab ? CodeLab.version : '0.1.8';
27233
+ const version = CodeLab ? CodeLab.version : '0.1.9';
26616
27234
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
26617
27235
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
26618
27236
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;