@innovatorved/code-lab 0.1.8 → 0.1.10

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/csp.ts CHANGED
@@ -195,7 +195,12 @@ export function buildPreviewPolicy(options: PreviewCspOptions = {}): string {
195
195
 
196
196
  const directive = (name: string, parts: string[]): string => `${name} ${unique(parts).join(' ')}`;
197
197
 
198
- const script = (): string[] => [self, 'blob:', "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, 'scriptSrc'));
198
+ // `data:` is required for scripts: the preview import map serves every local
199
+ // module as `data:text/javascript;...` so it works in a sandboxed frame (see
200
+ // buildHtmlPreviewResponse in src/shell.ts). Without it, any project with
201
+ // local ES modules fails to boot. `'unsafe-inline'` already allows inline
202
+ // script, so this does not widen the practical attack surface.
203
+ const script = (): string[] => [self, 'data:', 'blob:', "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, 'scriptSrc'));
199
204
  const style = (): string[] => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, 'styleSrc'));
200
205
  const withData = (key: keyof PreviewCspSources): string[] => [self, 'data:', 'blob:'].concat(sourcesFor(mode, allow, key));
201
206
 
@@ -334,13 +339,22 @@ export function buildPreviewShims(): string {
334
339
  document.body.appendChild(existing);
335
340
  }
336
341
  existing.textContent = '';
342
+ var topBar = document.createElement('div');
343
+ 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);';
337
344
  var header = document.createElement('div');
338
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
345
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
339
346
  header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
347
+ var closeBtn = document.createElement('button');
348
+ closeBtn.type = 'button';
349
+ closeBtn.textContent = 'Dismiss \u00d7';
350
+ 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;';
351
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
352
+ topBar.appendChild(header);
353
+ topBar.appendChild(closeBtn);
340
354
  var pre = document.createElement('pre');
341
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
355
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
342
356
  pre.textContent = String(stack || msg || '');
343
- existing.appendChild(header);
357
+ existing.appendChild(topBar);
344
358
  existing.appendChild(pre);
345
359
  } catch (err) {
346
360
  void err;
@@ -381,6 +395,189 @@ export function buildPreviewShims(): string {
381
395
  void err;
382
396
  }
383
397
  });
398
+
399
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
400
+ var pendingFetches = new Map();
401
+ var fetchSeq = 0;
402
+ function parseLoopbackTarget(rawUrl) {
403
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
404
+ var trimmed = rawUrl.trim();
405
+ if (!trimmed) return null;
406
+ var lower = trimmed.toLowerCase();
407
+ 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;
408
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
409
+ try {
410
+ var u = new URL(trimmed);
411
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
412
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
413
+ }
414
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
415
+ var rest = u.pathname.slice('/__preview/'.length);
416
+ var slashIdx = rest.indexOf('/');
417
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
418
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
419
+ var portNum = Number(portStr);
420
+ if (portNum > 0) {
421
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
422
+ }
423
+ }
424
+ } catch (e) { void e; }
425
+ return null;
426
+ }
427
+ if (trimmed.indexOf('/__preview/') === 0) {
428
+ var restRel = trimmed.slice('/__preview/'.length);
429
+ var sIdx = restRel.indexOf('/');
430
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
431
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
432
+ var pNum = Number(pStr);
433
+ if (pNum > 0) {
434
+ return { port: pNum, path: sPath || '/' };
435
+ }
436
+ }
437
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
438
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
439
+ return { port: null, path: pathPart };
440
+ }
441
+
442
+ window.addEventListener('message', function (event) {
443
+ var data = event && event.data;
444
+ if (!data || typeof data !== 'object') return;
445
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
446
+ var entry = pendingFetches.get(data.reqId);
447
+ if (!entry) return;
448
+ pendingFetches.delete(data.reqId);
449
+ entry.resolve(data);
450
+ }
451
+ });
452
+
453
+ if (typeof window.fetch === 'function') {
454
+ var origFetch = window.fetch.bind(window);
455
+ window.fetch = function (input, init) {
456
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
457
+ var target = parseLoopbackTarget(urlStr);
458
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
459
+ var isOpaque = false;
460
+ try {
461
+ var lowerUrl = urlStr.toLowerCase();
462
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
463
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
464
+ } catch (e) { isOpaque = true; void e; }
465
+ if (!target || !isOpaque || window.parent === window) {
466
+ return origFetch(input, init);
467
+ }
468
+ return new Promise(function (resolve, reject) {
469
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
470
+ var method = (init && init.method) || (input && input.method) || 'GET';
471
+ var headersObj = {};
472
+ try {
473
+ var rawH = (init && init.headers) || (input && input.headers);
474
+ if (rawH) {
475
+ if (typeof rawH.forEach === 'function') {
476
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
477
+ } else if (Array.isArray(rawH)) {
478
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
479
+ } else if (typeof rawH === 'object') {
480
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
481
+ }
482
+ }
483
+ } catch (e) { void e; }
484
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
485
+ var timer = setTimeout(function () {
486
+ if (pendingFetches.has(reqId)) {
487
+ pendingFetches.delete(reqId);
488
+ origFetch(input, init).then(resolve, reject);
489
+ }
490
+ }, 5000);
491
+ pendingFetches.set(reqId, {
492
+ resolve: function (payload) {
493
+ clearTimeout(timer);
494
+ if (payload && payload.error) {
495
+ reject(new TypeError(String(payload.error)));
496
+ return;
497
+ }
498
+ var status = Number(payload && payload.status) || 200;
499
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
500
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
501
+ try {
502
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
503
+ } catch (err) {
504
+ void err;
505
+ resolve({
506
+ ok: status >= 200 && status < 300,
507
+ status: status,
508
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
509
+ text: function () { return Promise.resolve(body); },
510
+ json: function () { return Promise.resolve(JSON.parse(body)); }
511
+ });
512
+ }
513
+ }
514
+ });
515
+ try {
516
+ parent.postMessage({
517
+ type: 'codelab:preview-fetch',
518
+ reqId: reqId,
519
+ port: target.port,
520
+ path: target.path,
521
+ method: String(method).toUpperCase(),
522
+ headers: headersObj,
523
+ body: bodyStr
524
+ }, '*');
525
+ } catch (err) {
526
+ clearTimeout(timer);
527
+ pendingFetches.delete(reqId);
528
+ origFetch(input, init).then(resolve, reject);
529
+ }
530
+ });
531
+ };
532
+ }
533
+
534
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
535
+ document.addEventListener('click', function (event) {
536
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
537
+ var el = event.target;
538
+ while (el && el.tagName !== 'A') el = el.parentElement;
539
+ if (!el || !el.getAttribute) return;
540
+ var href = el.getAttribute('href');
541
+ var targetAttr = el.getAttribute('target');
542
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
543
+ var lowerHref = href.toLowerCase();
544
+ 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;
545
+ var parsed = parseLoopbackTarget(href);
546
+ if (!parsed) return;
547
+ event.preventDefault();
548
+ try {
549
+ parent.postMessage({
550
+ type: 'codelab:preview-navigate',
551
+ port: parsed.port,
552
+ path: parsed.path
553
+ }, '*');
554
+ } catch (e) { void e; }
555
+ });
556
+
557
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
558
+ try {
559
+ ['pushState', 'replaceState'].forEach(function (method) {
560
+ var orig = history[method];
561
+ if (typeof orig !== 'function') return;
562
+ history[method] = function (state, title, url) {
563
+ var ret;
564
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
565
+ if (url !== undefined && url !== null) {
566
+ var parsed = parseLoopbackTarget(String(url));
567
+ if (parsed) {
568
+ try {
569
+ parent.postMessage({
570
+ type: 'codelab:preview-url-change',
571
+ path: parsed.path,
572
+ replace: method === 'replaceState'
573
+ }, '*');
574
+ } catch (e) { void e; }
575
+ }
576
+ }
577
+ return ret;
578
+ };
579
+ });
580
+ } catch (e) { void e; }
384
581
  })();
385
582
  </script>`;
386
583
  }
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.1.8
2
+ * @innovatorved/code-lab v0.1.10
3
3
  * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, and Git Engine.
4
4
  */
5
5
 
package/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.8
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.10
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
package/src/shell.ts CHANGED
@@ -3024,10 +3024,40 @@
3024
3024
  return imports;
3025
3025
  }
3026
3026
 
3027
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3028
- const scripts = [];
3027
+ // Some templates pin a CDN URL in the source instead of importing a bare
3028
+ // specifier, e.g. `import React from "https://cdn.jsdelivr.net/npm/react@19.3.1/+esm"`.
3029
+ // Those URL specifiers are resolved by the browser directly, so they bypass the
3030
+ // generated import map (and with it the project's declared version and the
3031
+ // multi-CDN fallback). Import maps can remap URL specifiers, so alias each
3032
+ // literal URL found in the project to the resolved bare-specifier URL.
3033
+ // The pinned version is kept when the project has no dependency to resolve.
3034
+ const PINNED_CDN_URL_RE = /https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;
3035
+
3036
+ function aliasPinnedCdnUrls(vfs, rootDir, text, importMap) {
3037
+ if (!text || typeof text !== 'string') return;
3038
+ const re = new RegExp(PINNED_CDN_URL_RE.source, 'g');
3039
+ let match;
3040
+ while ((match = re.exec(text)) !== null) {
3041
+ const url = match[0];
3042
+ const pkgName = decodeURIComponent(match[1]);
3043
+ const rest = match[2];
3044
+ const pinnedVersion = rest.split(/[\/?]/)[0];
3045
+ const tail = rest.slice(pinnedVersion.length);
3046
+ const rawSubpath = tail.startsWith('/') && tail !== '/+esm' ? tail.slice(1).split(/[?#]/)[0] : '';
3047
+ const subpath = rawSubpath.replace(/^\/+|\/+$/g, '');
3048
+ const bare = subpath ? `${pkgName}/${subpath}` : pkgName;
3049
+
3050
+ const declared = resolveBareVersion(vfs, rootDir, pkgName);
3051
+ const version = declared && declared !== 'latest' ? declared : decodeURIComponent(pinnedVersion);
3052
+ const target = importMap[bare] || cdnEsmUrl(pkgName, version, subpath || undefined);
3053
+ if (target && target !== url) importMap[url] = target;
3054
+ }
3055
+ }
3056
+
3057
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
3058
+ const files = [];
3029
3059
  const walk = (dir, depth) => {
3030
- if (depth > 8 || scripts.length >= maxFiles) return;
3060
+ if (depth > 8 || files.length >= maxFiles) return;
3031
3061
  let entries = [];
3032
3062
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
3033
3063
  for (const name of entries) {
@@ -3038,13 +3068,23 @@
3038
3068
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
3039
3069
  if (dirFlag) {
3040
3070
  walk(full, depth + 1);
3041
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
3042
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
3071
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
3072
+ try {
3073
+ const content = vfs.readFileSync(full, 'utf8');
3074
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
3075
+ files.push({ full, rel, content });
3076
+ } catch (err) {
3077
+ _shellLogger.debug('Preview script read skipped.', full, err);
3078
+ }
3043
3079
  }
3044
3080
  }
3045
3081
  };
3046
3082
  walk(rootDir, 0);
3047
- return scripts;
3083
+ return files;
3084
+ }
3085
+
3086
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3087
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
3048
3088
  }
3049
3089
 
3050
3090
  function injectPreviewExtras(html, importMap) {
@@ -3069,12 +3109,6 @@
3069
3109
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
3070
3110
  while (taken.has(port)) port++;
3071
3111
 
3072
- const specifiers = new Set();
3073
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
3074
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
3075
- }
3076
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3077
-
3078
3112
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
3079
3113
  const isDir = (p) => {
3080
3114
  try {
@@ -3082,8 +3116,111 @@
3082
3116
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
3083
3117
  } catch (_) { return false; }
3084
3118
  };
3119
+ const isFile = (p) => exists(p) && !isDir(p);
3085
3120
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3086
3121
 
3122
+ const resolveLocalTarget = (baseDir, rawSpec) => {
3123
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
3124
+ const clean = rawSpec.split(/[?#]/)[0].trim();
3125
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
3126
+ const candidateBase = clean.startsWith('/')
3127
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3128
+ : PosixPath.join(baseDir, clean);
3129
+ if (isFile(candidateBase)) return candidateBase;
3130
+ const cands = [
3131
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
3132
+ candidateBase + '.mjs', candidateBase + '.cjs',
3133
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
3134
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3135
+ ];
3136
+ for (const c of cands) {
3137
+ if (isFile(c)) return c;
3138
+ }
3139
+ return null;
3140
+ };
3141
+
3142
+ const toLocalImportKey = (fullPath) => {
3143
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
3144
+ return `@codelab-local/${rel}`;
3145
+ };
3146
+
3147
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
3148
+ let out = code;
3149
+ try {
3150
+ const rm = getRuntimeModule();
3151
+ if (rm && typeof rm.transpileForBrowser === 'function') {
3152
+ out = rm.transpileForBrowser(out, sourcePath);
3153
+ }
3154
+ } catch (err) {
3155
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
3156
+ }
3157
+ const fromDir = PosixPath.dirname(sourcePath);
3158
+ const rewriteSpec = (spec) => {
3159
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
3160
+ const resolved = resolveLocalTarget(fromDir, spec);
3161
+ return resolved ? toLocalImportKey(resolved) : spec;
3162
+ };
3163
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3164
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3165
+ return out;
3166
+ };
3167
+
3168
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
3169
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
3170
+ const specifiers = new Set();
3171
+ for (const f of scriptFiles) {
3172
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
3173
+ }
3174
+ // Also scan inline module scripts in HTML for bare specifiers
3175
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
3176
+ let inlineMatch;
3177
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
3178
+ if (inlineMatch[1]) {
3179
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
3180
+ }
3181
+ }
3182
+
3183
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3184
+ for (const f of scriptFiles) aliasPinnedCdnUrls(ctx.vfs, rootDir, f.content, importMap);
3185
+ aliasPinnedCdnUrls(ctx.vfs, rootDir, htmlBody, importMap);
3186
+ for (const f of scriptFiles) {
3187
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3188
+ const key = toLocalImportKey(f.full);
3189
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
3190
+ }
3191
+
3192
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
3193
+ let transformedHtml = htmlBody;
3194
+
3195
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
3196
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
3197
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
3198
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
3199
+ if (!hrefMatch) return fullTag;
3200
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
3201
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
3202
+ const cssContent = readText(cssTarget);
3203
+ if (cssContent === null) return fullTag;
3204
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
3205
+ });
3206
+
3207
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
3208
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
3209
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
3210
+ if (!srcMatch) return fullTag;
3211
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
3212
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3213
+ const rawScript = readText(scriptTarget);
3214
+ if (rawScript === null) return fullTag;
3215
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3216
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
3217
+ const typeAttr = isMod ? ' type="module"' : '';
3218
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
3219
+ });
3220
+
3221
+ return injectPreviewExtras(transformedHtml, importMap);
3222
+ };
3223
+
3087
3224
  const handler = async (request) => {
3088
3225
  let pathname = '/';
3089
3226
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -3118,7 +3255,7 @@
3118
3255
  let body = readText(target);
3119
3256
  if (body === null) body = '';
3120
3257
  if (/\.html?$/i.test(target)) {
3121
- body = injectPreviewExtras(body, importMap);
3258
+ body = buildHtmlPreviewResponse(body, target);
3122
3259
  } else if (isPreviewScriptPath(target)) {
3123
3260
  try {
3124
3261
  const rm = getRuntimeModule();