@innovatorved/code-lab 0.1.6 → 0.1.7

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/ARCHITECTURE.md CHANGED
@@ -1,4 +1,4 @@
1
- # `@innovatorved/code-lab` Architecture (v1.3.2)
1
+ # `@innovatorved/code-lab` Architecture (v0.1.7)
2
2
 
3
3
  `@innovatorved/code-lab` is an embeddable, zero-dependency, browser-native Node.js v22 + Bun v1.1 IDE, POSIX shell, PTY terminal, and virtual execution sandbox.
4
4
 
package/README.md CHANGED
@@ -11,7 +11,7 @@ Browser-native code IDE workbench, modular guided challenge engine (`@innovatorv
11
11
 
12
12
  ## Features
13
13
 
14
- - **Modular Architecture (`v2.0.0`)**: Pure, general-purpose browser IDE (`code-lab`) by default with File Explorer, Monaco Editor, and PTY Terminal. Curriculum features (Guided Steps, Mode Switcher, and JS/TS switcher) are encapsulated in an opt-in modular extension (`@innovatorved/code-lab/extensions/guided-lab`).
14
+ - **Modular Architecture (`v0.1.7`)**: Pure, general-purpose browser IDE (`code-lab`) by default with File Explorer, Monaco Editor, and PTY Terminal. Curriculum features (Guided Steps, Mode Switcher, and JS/TS switcher) are encapsulated in an opt-in modular extension (`@innovatorved/code-lab/extensions/guided-lab`).
15
15
  - **End-to-End TypeScript & Zod Type Safety**: Written in TypeScript with strict runtime schemas and inferred types (`z.infer<typeof ...>`) for workbench options, guided labs, runtime execution, and git cloning.
16
16
  - **Public GitHub Repository Cloning (`git clone`)**: Clone any public GitHub repository (`git clone https://github.com/owner/repo` or `git clone owner/repo --branch main` in the terminal, or `await lab.cloneRepo('owner/repo')` via the SDK) directly into `/workspace` with zero authentication required (automatic GitHub Trees API + jsDelivr unlimited fallback). Clone progress (`remote: Enumerating objects…`, `Receiving objects: n%…`) streams into the terminal in real time as it downloads.
17
17
  - **Interactive IDE Workbench**: Multi-file Monaco editor, collapsible hierarchical file tree with drag-and-drop, a workspace **folder switcher** (breadcrumb dropdown that scopes the explorer to any subfolder), decoupled editor tabs, Command Palette (`Cmd+Shift+P`), Quick Open (`Cmd+P`), breadcrumbs, and line-by-line solution diff viewer.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * TypeScript Definitions for @innovatorved/code-lab v2.0.0
2
+ * TypeScript Definitions for @innovatorved/code-lab v0.1.7
3
3
  */
4
4
 
5
5
  export interface CodeLabStep {
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v2.0.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.7 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -18,6 +18,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
18
18
 
19
19
  // --- Module 1: Runtime Engine ---
20
20
  (function () {
21
+ // @ts-nocheck
21
22
  'use strict';
22
23
  if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined') {
23
24
  globalThis.Bun = { version: '1.1.20' };
@@ -8248,10 +8249,12 @@ if (typeof module !== 'undefined' && module.exports) {
8248
8249
  }
8249
8250
 
8250
8251
 
8252
+
8251
8253
  })();
8252
8254
 
8253
8255
  // --- Module 2: POSIX Shell & Coreutils ---
8254
8256
  (function () {
8257
+ // @ts-nocheck
8255
8258
  /**
8256
8259
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
8257
8260
  *
@@ -10239,7 +10242,7 @@ if (typeof module !== 'undefined' && module.exports) {
10239
10242
  return 10 + depth * 0.1;
10240
10243
  }
10241
10244
 
10242
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
10245
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
10243
10246
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10244
10247
  if (onProgress) {
10245
10248
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -10529,6 +10532,23 @@ if (typeof module !== 'undefined' && module.exports) {
10529
10532
  };
10530
10533
  }
10531
10534
 
10535
+ // Public wrapper: guarantee an `error` progress event when the clone fails
10536
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
10537
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
10538
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10539
+ try {
10540
+ return await _cloneGitHubRepository(repoInput, vfs, options);
10541
+ } catch (err) {
10542
+ if (onProgress) {
10543
+ onProgress({
10544
+ phase: 'error',
10545
+ message: err && err.message ? err.message : String(err)
10546
+ });
10547
+ }
10548
+ throw err;
10549
+ }
10550
+ }
10551
+
10532
10552
  // =========================================================================
10533
10553
  // Package Management Helpers (npm / bun virtual modules & scripts)
10534
10554
  // =========================================================================
@@ -15510,10 +15530,12 @@ if (typeof module !== 'undefined' && module.exports) {
15510
15530
  };
15511
15531
  });
15512
15532
 
15533
+
15513
15534
  })();
15514
15535
 
15515
15536
  // --- Module 3: PTY Terminal Engine ---
15516
15537
  (function () {
15538
+ // @ts-nocheck
15517
15539
  /**
15518
15540
  * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
15519
15541
  *
@@ -16561,10 +16583,12 @@ if (typeof module !== 'undefined' && module.exports) {
16561
16583
  };
16562
16584
  });
16563
16585
 
16586
+
16564
16587
  })();
16565
16588
 
16566
16589
  // --- Module 4: IDE Workbench & Web Component ---
16567
16590
  (function () {
16591
+ // @ts-nocheck
16568
16592
  /* ═══════════════════════════════════════════════════════════════════════════
16569
16593
  @innovatorved/code-lab — Interactive Monaco IDE Workbench & Guided Lab UI
16570
16594
  Supports <code-lab> Custom Element + window.CodeLab.mount() API
@@ -16608,6 +16632,10 @@ if (typeof module !== 'undefined' && module.exports) {
16608
16632
  const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
16609
16633
  const STORAGE_PREFIX = 'sd-codelab-v1:';
16610
16634
 
16635
+ // The bundler rewrites this literal from package.json at build time. Keeping
16636
+ // the fallback in sync lets tests require src/workbench.js directly.
16637
+ const CODELAB_VERSION = '0.1.7';
16638
+
16611
16639
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16612
16640
  const NODE_AMBIENT_DTS = `
16613
16641
  declare var require: (id: string) => any;
@@ -16944,6 +16972,33 @@ declare module 'bun:sqlite' {
16944
16972
  .replace(/'/g, '&#39;');
16945
16973
  }
16946
16974
 
16975
+ // Schemes that may appear in a rendered href. Everything else
16976
+ // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16977
+ const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
16978
+
16979
+ function sanitizeUrl(raw) {
16980
+ if (raw === null || raw === undefined) return '#';
16981
+ const trimmed = String(raw).trim();
16982
+ if (!trimmed) return '#';
16983
+
16984
+ // Browsers ignore C0 controls and zero-width characters while resolving a
16985
+ // scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
16986
+ // them before deciding what the scheme is, but return the original value
16987
+ // when it is safe.
16988
+ const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
16989
+ const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
16990
+
16991
+ if (!schemeMatch) {
16992
+ // No scheme: a fragment, an absolute path, or a relative path.
16993
+ // Backslashes are treated as slashes by the URL parser and can turn a
16994
+ // "relative" URL into a protocol-relative one, so reject those.
16995
+ if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
16996
+ return trimmed;
16997
+ }
16998
+
16999
+ return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
17000
+ }
17001
+
16947
17002
  function formatErrorText(err) {
16948
17003
  if (!err) return '';
16949
17004
  if (typeof err === 'string') return err;
@@ -17137,14 +17192,9 @@ declare module 'bun:sqlite' {
17137
17192
 
17138
17193
  // Markdown Links: [label](url "title") or [label](url)
17139
17194
  text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17140
- const cleanUrl = url.trim();
17195
+ const cleanUrl = sanitizeUrl(url);
17141
17196
  const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17142
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`;
17143
- });
17144
-
17145
- // Autolinks: <https://...>
17146
- text = text.replace(/<(https?:\/\/[^>]+)>/g, (_, url) => {
17147
- return `<a href="${escapeHtml(url)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`;
17197
+ return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
17148
17198
  });
17149
17199
 
17150
17200
  // Strikethrough: ~~del~~
@@ -17339,8 +17389,9 @@ declare module 'bun:sqlite' {
17339
17389
  // Normalize CRLF to LF
17340
17390
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
17341
17391
 
17342
- // Prevent raw custom elements from executing within markdown previews
17343
- text = text.replace(/<\/?code-lab(\s[^>]*)?>/gi, (m) => escapeHtml(m));
17392
+ // NUL delimits internal placeholders. Strip author-supplied NULs so
17393
+ // markdown cannot forge a code-block or autolink placeholder.
17394
+ text = text.replace(/\u0000/g, '');
17344
17395
 
17345
17396
  // Phase 1: Fenced Code Block Extraction
17346
17397
  const codeBlocks = [];
@@ -17363,6 +17414,25 @@ declare module 'bun:sqlite' {
17363
17414
  return `\x00INLINECODE_${idx}\x00`;
17364
17415
  });
17365
17416
 
17417
+ // Phase 2b: Autolinks are the only inline construct that uses angle
17418
+ // brackets. Extract them before raw HTML is neutralized, then restore the
17419
+ // anchors in Phase 7.
17420
+ const autolinks = [];
17421
+ text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
17422
+ const idx = autolinks.length;
17423
+ const safe = sanitizeUrl(url);
17424
+ autolinks.push(
17425
+ `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
17426
+ );
17427
+ return `\x00AUTOLINK_${idx}\x00`;
17428
+ });
17429
+
17430
+ // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
17431
+ // escaping that one character turns any author-supplied markup into text
17432
+ // without disturbing `>` blockquote syntax. From here on, every real tag
17433
+ // in the output is generated by this renderer.
17434
+ text = text.replace(/</g, '&lt;');
17435
+
17366
17436
  // Phase 3: GitHub Callout Alerts & Blockquotes
17367
17437
  const calloutBlocks = [];
17368
17438
  text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
@@ -17440,7 +17510,8 @@ declare module 'bun:sqlite' {
17440
17510
  .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
17441
17511
  .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
17442
17512
  .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
17443
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '');
17513
+ .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
17514
+ .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
17444
17515
 
17445
17516
  return finalHtml;
17446
17517
  }
@@ -17650,24 +17721,102 @@ declare module 'bun:sqlite' {
17650
17721
  let _workbenchInstanceCounter = 0;
17651
17722
  const _fallbackStorage = new Map();
17652
17723
 
17653
- function safeStorageGet(key) {
17724
+ // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17725
+ // in src/preview-sw.js — keep both copies in sync.
17726
+ const PREVIEW_CSP = [
17727
+ "default-src 'self' data: blob:",
17728
+ "base-uri 'self'",
17729
+ "object-src 'none'",
17730
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17731
+ "style-src 'self' 'unsafe-inline'",
17732
+ "img-src 'self' data: blob:",
17733
+ "font-src 'self' data:",
17734
+ "connect-src 'self' data: blob:",
17735
+ "media-src 'self' data: blob:",
17736
+ "worker-src 'self' blob:",
17737
+ "frame-src 'self' data: blob:",
17738
+ "form-action 'self'",
17739
+ "frame-ancestors 'self'"
17740
+ ].join('; ');
17741
+
17742
+ function normalizePreviewOrigin(raw) {
17743
+ if (raw === null || raw === undefined || raw === '') return null;
17744
+ try {
17745
+ const parsed = new URL(String(raw));
17746
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
17747
+ return parsed.origin;
17748
+ } catch (_) {
17749
+ return null;
17750
+ }
17751
+ }
17752
+
17753
+ const LOG_PREFIX = '[code-lab]';
17754
+
17755
+ // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17756
+ // into their own telemetry; `options.debug` enables verbose output. Errors
17757
+ // are never silently discarded.
17758
+ function createLogger(options = {}) {
17759
+ const sink = options.logger;
17760
+ const debugEnabled = options.debug === true;
17761
+
17762
+ const write = (level, args) => {
17763
+ if (level === 'debug' && !debugEnabled) return;
17764
+ if (sink && typeof sink[level] === 'function') {
17765
+ try {
17766
+ sink[level](...args);
17767
+ return;
17768
+ } catch (_) {
17769
+ // A broken host logger must not break the IDE; fall through.
17770
+ }
17771
+ }
17772
+ const fn = typeof console !== 'undefined' ? console[level] : null;
17773
+ if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
17774
+ };
17775
+
17776
+ return {
17777
+ debug: (...args) => write('debug', args),
17778
+ info: (...args) => write('info', args),
17779
+ warn: (...args) => write('warn', args),
17780
+ error: (...args) => write('error', args)
17781
+ };
17782
+ }
17783
+
17784
+ const DEFAULT_LOGGER = createLogger();
17785
+
17786
+ function safeStorageGet(key, logger = DEFAULT_LOGGER) {
17654
17787
  try {
17655
17788
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17656
- return localStorage.getItem(key);
17789
+ const value = localStorage.getItem(key);
17790
+ if (value !== null && value !== undefined) return value;
17657
17791
  }
17658
- } catch (_) {}
17792
+ } catch (err) {
17793
+ logger.warn(
17794
+ `localStorage.getItem("${key}") failed; using in-memory state.`,
17795
+ err && err.message ? err.message : err
17796
+ );
17797
+ }
17659
17798
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17660
17799
  }
17661
17800
 
17662
- function safeStorageSet(key, value) {
17801
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
17663
17802
  const str = String(value);
17664
17803
  try {
17665
17804
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17666
17805
  localStorage.setItem(key, str);
17667
- return;
17806
+ return true;
17668
17807
  }
17669
- } catch (_) {}
17808
+ } catch (err) {
17809
+ if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17810
+ if (!safeStorageSet._warnedKeys.has(key)) {
17811
+ safeStorageSet._warnedKeys.add(key);
17812
+ logger.warn(
17813
+ `localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
17814
+ err && err.message ? err.message : err
17815
+ );
17816
+ }
17817
+ }
17670
17818
  _fallbackStorage.set(key, str);
17819
+ return false;
17671
17820
  }
17672
17821
 
17673
17822
  // ── CodeLabWorkbench Instance Class ──────────────────────────────────────
@@ -17678,12 +17827,22 @@ declare module 'bun:sqlite' {
17678
17827
  throw new Error('CodeLabWorkbench requires a valid DOM container element.');
17679
17828
  }
17680
17829
  this.options = options || {};
17830
+ this.logger = createLogger({ logger: options.logger, debug: options.debug });
17831
+ this._persistenceFailureReported = false;
17681
17832
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17682
17833
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17683
17834
  this.title = options.title || this.labId;
17684
17835
  this.summary = options.summary || '';
17685
17836
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17686
17837
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17838
+ this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
17839
+ this._previewIsolationWarned = false;
17840
+ if (options.previewOrigin && !this.previewOrigin) {
17841
+ this.logger.warn(
17842
+ 'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
17843
+ 'such as "https://preview.example.com".'
17844
+ );
17845
+ }
17687
17846
  this.explicitEntry = options.entry || null;
17688
17847
  this.explicitTestEntry = options.testEntry || options.testFile || null;
17689
17848
  this.backLabel = options.backLabel || 'Back to Build Guide';
@@ -18021,7 +18180,7 @@ declare module 'bun:sqlite' {
18021
18180
  const handlers = this._eventListeners.get(key);
18022
18181
  if (handlers) {
18023
18182
  for (const fn of Array.from(handlers)) {
18024
- try { fn(detail); } catch (_) {}
18183
+ try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
18025
18184
  }
18026
18185
  }
18027
18186
  }
@@ -18055,13 +18214,26 @@ declare module 'bun:sqlite' {
18055
18214
  return {};
18056
18215
  }
18057
18216
  try {
18058
- const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
18217
+ const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
18059
18218
  return raw ? JSON.parse(raw) : {};
18060
- } catch {
18219
+ } catch (err) {
18220
+ this.logger.warn(
18221
+ `Ignoring unreadable saved state for "${this.labId}".`,
18222
+ err && err.message ? err.message : err
18223
+ );
18061
18224
  return {};
18062
18225
  }
18063
18226
  }
18064
18227
 
18228
+ _reportPersistenceFailure() {
18229
+ if (this._persistenceFailureReported) return;
18230
+ this._persistenceFailureReported = true;
18231
+ this.logger.warn(
18232
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18233
+ );
18234
+ this._emitEvent('persistence-error', { labId: this.labId });
18235
+ }
18236
+
18065
18237
  _saveState() {
18066
18238
  try {
18067
18239
  const key = `${this.mode}:${this.lang}`;
@@ -18086,11 +18258,20 @@ declare module 'bun:sqlite' {
18086
18258
  return;
18087
18259
  }
18088
18260
  const serialized = JSON.stringify(state);
18089
- safeStorageSet(this._storageKey(), serialized);
18090
- // Sync with host app sidebar & build overview progress trackers
18091
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr));
18092
- safeStorageSet('sd_codelab_' + this.labId, serialized);
18093
- } catch {}
18261
+ const persisted = [
18262
+ safeStorageSet(this._storageKey(), serialized, this.logger),
18263
+ // Sync with host app sidebar & build overview progress trackers
18264
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18265
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
18266
+ ];
18267
+ if (persisted.includes(false)) this._reportPersistenceFailure();
18268
+ } catch (err) {
18269
+ this.logger.error(
18270
+ 'Failed to save workbench state.',
18271
+ err && err.message ? err.message : err
18272
+ );
18273
+ this._reportPersistenceFailure();
18274
+ }
18094
18275
  }
18095
18276
 
18096
18277
  _detectPackages() {
@@ -20655,8 +20836,44 @@ declare module 'bun:sqlite' {
20655
20836
  return `http://127.0.0.1:${port}${path}`;
20656
20837
  }
20657
20838
 
20839
+ _previewFrameUrl(port, pathAndQuery = '/') {
20840
+ const p = Number(port) || 3000;
20841
+ const rawPath = pathAndQuery || '/';
20842
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20843
+ const base = this.previewOrigin || '';
20844
+ return `${base}/__preview/${p}${path}`;
20845
+ }
20846
+
20847
+ _warnPreviewIsolation() {
20848
+ if (this.previewOrigin || this._previewIsolationWarned) return;
20849
+ this._previewIsolationWarned = true;
20850
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20851
+ console.warn(
20852
+ '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20853
+ 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20854
+ );
20855
+ }
20856
+ }
20857
+
20858
+ _injectPreviewCsp(html, port) {
20859
+ if (typeof html !== 'string' || !html) return html;
20860
+ if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20861
+
20862
+ const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20863
+ (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
20864
+
20865
+ if (/<head\b[^>]*>/i.test(html)) {
20866
+ return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
20867
+ }
20868
+ if (/<html\b[^>]*>/i.test(html)) {
20869
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
20870
+ }
20871
+ return `<head>${tags}</head>${html}`;
20872
+ }
20873
+
20658
20874
  _openWebPreview(port, path = '/') {
20659
20875
  const p = Number(port) || this._firstListeningPort() || 3000;
20876
+ this._warnPreviewIsolation();
20660
20877
  this.previewState.port = p;
20661
20878
  this.previewState.path = path || '/';
20662
20879
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
@@ -20835,10 +21052,10 @@ declare module 'bun:sqlite' {
20835
21052
 
20836
21053
  _popoutPreview() {
20837
21054
  const url = this._previewUrl();
20838
- let popout = '/__preview/';
21055
+ let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
20839
21056
  try {
20840
21057
  const u = new URL(url);
20841
- popout = `/__preview/${u.port}${u.pathname}${u.search || ''}`;
21058
+ popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
20842
21059
  } catch (_) {}
20843
21060
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
20844
21061
  try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
@@ -20848,6 +21065,7 @@ declare module 'bun:sqlite' {
20848
21065
 
20849
21066
  _renderWebPreview(bodyEl) {
20850
21067
  if (!bodyEl) return;
21068
+ this._warnPreviewIsolation();
20851
21069
  const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
20852
21070
  if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
20853
21071
  this._renderWebPreviewControls();
@@ -20885,7 +21103,7 @@ declare module 'bun:sqlite' {
20885
21103
  <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>
20886
21104
  </div>
20887
21105
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
20888
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
21106
+ <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>
20889
21107
  </div>
20890
21108
  ${servers.length
20891
21109
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -20922,7 +21140,7 @@ declare module 'bun:sqlite' {
20922
21140
  try {
20923
21141
  const u = new URL(fullUrl);
20924
21142
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
20925
- iframe.setAttribute('src', `/__preview/${u.port}${u.pathname}${u.search || ''}`);
21143
+ iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
20926
21144
  this.previewState.loading = false;
20927
21145
  return Promise.resolve();
20928
21146
  } catch (_) {}
@@ -20934,8 +21152,8 @@ declare module 'bun:sqlite' {
20934
21152
  .then((res) => {
20935
21153
  let body = res.body || '';
20936
21154
  const contentType = res.headers['content-type'] || res.headers['Content-Type'] || '';
20937
- if (/text\/html/i.test(contentType) && /<head\b/i.test(body) && !/<base\b/i.test(body)) {
20938
- body = body.replace(/<head\b[^>]*>/i, (m) => `${m}<base href="/__preview/${port}/">`);
21155
+ if (/text\/html/i.test(contentType)) {
21156
+ body = this._injectPreviewCsp(body, port);
20939
21157
  }
20940
21158
  this.previewState.srcdoc = body;
20941
21159
  this.previewState.loading = false;
@@ -20947,7 +21165,7 @@ declare module 'bun:sqlite' {
20947
21165
  this.previewState.loading = false;
20948
21166
  this.previewState.error = String((err && err.message) || err);
20949
21167
  const msg = `<body style="font-family:system-ui;padding:24px;color:#888"><h2>Preview unavailable</h2><p>${escapeHtml(this.previewState.error)}</p></body>`;
20950
- iframe.setAttribute('srcdoc', msg);
21168
+ iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
20951
21169
  });
20952
21170
  }
20953
21171
 
@@ -21302,7 +21520,7 @@ declare module 'bun:sqlite' {
21302
21520
 
21303
21521
  _notifyCodeChange(filename, code) {
21304
21522
  if (this.onCodeChange) {
21305
- try { this.onCodeChange(filename, code); } catch (_) {}
21523
+ try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21306
21524
  }
21307
21525
  const detail = { labId: this.labId, filename, path: filename, code, content: code };
21308
21526
  this._emitEvent('codelab:change', detail);
@@ -22941,7 +23159,7 @@ declare module 'bun:sqlite' {
22941
23159
  }
22942
23160
 
22943
23161
  if (this.onRun) {
22944
- try { this.onRun(res); } catch (_) {}
23162
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
22945
23163
  }
22946
23164
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
22947
23165
  } catch (err) {
@@ -23016,10 +23234,10 @@ declare module 'bun:sqlite' {
23016
23234
  }
23017
23235
 
23018
23236
  if (this.onTestResult) {
23019
- try { this.onTestResult(res); } catch (_) {}
23237
+ try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
23020
23238
  }
23021
23239
  if (this.onRun) {
23022
- try { this.onRun(res); } catch (_) {}
23240
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
23023
23241
  }
23024
23242
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
23025
23243
 
@@ -23033,7 +23251,7 @@ declare module 'bun:sqlite' {
23033
23251
  this.completedSteps.add(step.id);
23034
23252
  newlyCompleted = true;
23035
23253
  if (this.onStepComplete) {
23036
- try { this.onStepComplete(step, sIdx); } catch (_) {}
23254
+ try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
23037
23255
  }
23038
23256
  const stepDetail = {
23039
23257
  labId: this.labId,
@@ -23052,7 +23270,7 @@ declare module 'bun:sqlite' {
23052
23270
  this._saveState();
23053
23271
  if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
23054
23272
  if (this.onLabComplete) {
23055
- try { this.onLabComplete(this.labId); } catch (_) {}
23273
+ try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
23056
23274
  }
23057
23275
  this._emitEvent('codelab:lab-complete', {
23058
23276
  labId: this.labId,
@@ -23357,7 +23575,12 @@ declare module 'bun:sqlite' {
23357
23575
  a.click();
23358
23576
  setTimeout(() => URL.revokeObjectURL(url), 500);
23359
23577
  }
23360
- } catch (_) {}
23578
+ } catch (err) {
23579
+ this.logger.error(
23580
+ `Failed to start download for "${filename}".`,
23581
+ err && err.message ? err.message : err
23582
+ );
23583
+ }
23361
23584
  return content;
23362
23585
  }
23363
23586
 
@@ -23385,7 +23608,12 @@ declare module 'bun:sqlite' {
23385
23608
  a.click();
23386
23609
  setTimeout(() => URL.revokeObjectURL(url), 500);
23387
23610
  }
23388
- } catch (_) {}
23611
+ } catch (err) {
23612
+ this.logger.error(
23613
+ 'Failed to download workspace export.',
23614
+ err && err.message ? err.message : err
23615
+ );
23616
+ }
23389
23617
  }
23390
23618
  return snapshot;
23391
23619
  }
@@ -23881,7 +24109,7 @@ declare module 'bun:sqlite' {
23881
24109
  }
23882
24110
 
23883
24111
  const CodeLabSDK = {
23884
- version: '2.0.0',
24112
+ version: CODELAB_VERSION,
23885
24113
  Workbench: CodeLabWorkbench,
23886
24114
  CodeLabWorkbench,
23887
24115
  CodeLabElement: CodeLabElementClass,
@@ -23948,7 +24176,7 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
23948
24176
  const mount = CodeLab ? CodeLab.mount : null;
23949
24177
  const create = CodeLab ? CodeLab.create : null;
23950
24178
  const unmount = CodeLab ? CodeLab.unmount : null;
23951
- const version = CodeLab ? CodeLab.version : '2.0.0';
24179
+ const version = CodeLab ? CodeLab.version : '0.1.7';
23952
24180
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
23953
24181
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
23954
24182
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;