@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.
- package/ARCHITECTURE.md +1 -1
- package/README.md +1 -1
- package/dist/code-lab.css +657 -0
- package/dist/code-lab.d.ts +1 -1
- package/dist/code-lab.esm.js +650 -32
- package/dist/code-lab.js +649 -31
- package/dist/index.d.ts +1 -1
- package/dist/preview-sw.js +196 -4
- package/dist/runtime.esm.js +1 -1
- package/dist/runtime.js +1 -1
- package/dist/schemas.d.ts +1 -1
- package/dist/shell.esm.js +119 -14
- package/dist/shell.js +119 -14
- package/dist/terminal.esm.js +1 -1
- package/dist/terminal.js +1 -1
- package/package.json +1 -1
- package/src/code-lab.css +657 -0
- package/src/csp.ts +195 -3
- package/src/index.ts +1 -1
- package/src/schemas.ts +1 -1
- package/src/shell.ts +118 -13
- package/src/workbench.ts +335 -14
package/dist/code-lab.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
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
|
|
@@ -268,13 +268,22 @@ var CodeLabCsp = (() => {
|
|
|
268
268
|
document.body.appendChild(existing);
|
|
269
269
|
}
|
|
270
270
|
existing.textContent = '';
|
|
271
|
+
var topBar = document.createElement('div');
|
|
272
|
+
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);';
|
|
271
273
|
var header = document.createElement('div');
|
|
272
|
-
header.style.cssText = 'color:#f87171;font-weight:700;font-size:
|
|
274
|
+
header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
|
|
273
275
|
header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
|
|
276
|
+
var closeBtn = document.createElement('button');
|
|
277
|
+
closeBtn.type = 'button';
|
|
278
|
+
closeBtn.textContent = 'Dismiss \xD7';
|
|
279
|
+
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;';
|
|
280
|
+
closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
|
|
281
|
+
topBar.appendChild(header);
|
|
282
|
+
topBar.appendChild(closeBtn);
|
|
274
283
|
var pre = document.createElement('pre');
|
|
275
|
-
pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
|
|
284
|
+
pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
|
|
276
285
|
pre.textContent = String(stack || msg || '');
|
|
277
|
-
existing.appendChild(
|
|
286
|
+
existing.appendChild(topBar);
|
|
278
287
|
existing.appendChild(pre);
|
|
279
288
|
} catch (err) {
|
|
280
289
|
void err;
|
|
@@ -315,6 +324,189 @@ var CodeLabCsp = (() => {
|
|
|
315
324
|
void err;
|
|
316
325
|
}
|
|
317
326
|
});
|
|
327
|
+
|
|
328
|
+
// Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
|
|
329
|
+
var pendingFetches = new Map();
|
|
330
|
+
var fetchSeq = 0;
|
|
331
|
+
function parseLoopbackTarget(rawUrl) {
|
|
332
|
+
if (!rawUrl || typeof rawUrl !== 'string') return null;
|
|
333
|
+
var trimmed = rawUrl.trim();
|
|
334
|
+
if (!trimmed) return null;
|
|
335
|
+
var lower = trimmed.toLowerCase();
|
|
336
|
+
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;
|
|
337
|
+
if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
|
|
338
|
+
try {
|
|
339
|
+
var u = new URL(trimmed);
|
|
340
|
+
if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
|
|
341
|
+
return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
|
|
342
|
+
}
|
|
343
|
+
if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
|
|
344
|
+
var rest = u.pathname.slice('/__preview/'.length);
|
|
345
|
+
var slashIdx = rest.indexOf('/');
|
|
346
|
+
var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
|
|
347
|
+
var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
|
|
348
|
+
var portNum = Number(portStr);
|
|
349
|
+
if (portNum > 0) {
|
|
350
|
+
return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
} catch (e) { void e; }
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
if (trimmed.indexOf('/__preview/') === 0) {
|
|
357
|
+
var restRel = trimmed.slice('/__preview/'.length);
|
|
358
|
+
var sIdx = restRel.indexOf('/');
|
|
359
|
+
var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
|
|
360
|
+
var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
|
|
361
|
+
var pNum = Number(pStr);
|
|
362
|
+
if (pNum > 0) {
|
|
363
|
+
return { port: pNum, path: sPath || '/' };
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
|
|
367
|
+
var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
|
|
368
|
+
return { port: null, path: pathPart };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
window.addEventListener('message', function (event) {
|
|
372
|
+
var data = event && event.data;
|
|
373
|
+
if (!data || typeof data !== 'object') return;
|
|
374
|
+
if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
|
|
375
|
+
var entry = pendingFetches.get(data.reqId);
|
|
376
|
+
if (!entry) return;
|
|
377
|
+
pendingFetches.delete(data.reqId);
|
|
378
|
+
entry.resolve(data);
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
if (typeof window.fetch === 'function') {
|
|
383
|
+
var origFetch = window.fetch.bind(window);
|
|
384
|
+
window.fetch = function (input, init) {
|
|
385
|
+
var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
|
|
386
|
+
var target = parseLoopbackTarget(urlStr);
|
|
387
|
+
// Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
|
|
388
|
+
var isOpaque = false;
|
|
389
|
+
try {
|
|
390
|
+
var lowerUrl = urlStr.toLowerCase();
|
|
391
|
+
var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
|
|
392
|
+
isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
|
|
393
|
+
} catch (e) { isOpaque = true; void e; }
|
|
394
|
+
if (!target || !isOpaque || window.parent === window) {
|
|
395
|
+
return origFetch(input, init);
|
|
396
|
+
}
|
|
397
|
+
return new Promise(function (resolve, reject) {
|
|
398
|
+
var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
|
|
399
|
+
var method = (init && init.method) || (input && input.method) || 'GET';
|
|
400
|
+
var headersObj = {};
|
|
401
|
+
try {
|
|
402
|
+
var rawH = (init && init.headers) || (input && input.headers);
|
|
403
|
+
if (rawH) {
|
|
404
|
+
if (typeof rawH.forEach === 'function') {
|
|
405
|
+
rawH.forEach(function (v, k) { headersObj[k] = v; });
|
|
406
|
+
} else if (Array.isArray(rawH)) {
|
|
407
|
+
rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
|
|
408
|
+
} else if (typeof rawH === 'object') {
|
|
409
|
+
Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
} catch (e) { void e; }
|
|
413
|
+
var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
|
|
414
|
+
var timer = setTimeout(function () {
|
|
415
|
+
if (pendingFetches.has(reqId)) {
|
|
416
|
+
pendingFetches.delete(reqId);
|
|
417
|
+
origFetch(input, init).then(resolve, reject);
|
|
418
|
+
}
|
|
419
|
+
}, 5000);
|
|
420
|
+
pendingFetches.set(reqId, {
|
|
421
|
+
resolve: function (payload) {
|
|
422
|
+
clearTimeout(timer);
|
|
423
|
+
if (payload && payload.error) {
|
|
424
|
+
reject(new TypeError(String(payload.error)));
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
var status = Number(payload && payload.status) || 200;
|
|
428
|
+
var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
|
|
429
|
+
var body = payload && payload.body !== undefined ? String(payload.body) : '';
|
|
430
|
+
try {
|
|
431
|
+
resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
|
|
432
|
+
} catch (err) {
|
|
433
|
+
void err;
|
|
434
|
+
resolve({
|
|
435
|
+
ok: status >= 200 && status < 300,
|
|
436
|
+
status: status,
|
|
437
|
+
headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
|
|
438
|
+
text: function () { return Promise.resolve(body); },
|
|
439
|
+
json: function () { return Promise.resolve(JSON.parse(body)); }
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
try {
|
|
445
|
+
parent.postMessage({
|
|
446
|
+
type: 'codelab:preview-fetch',
|
|
447
|
+
reqId: reqId,
|
|
448
|
+
port: target.port,
|
|
449
|
+
path: target.path,
|
|
450
|
+
method: String(method).toUpperCase(),
|
|
451
|
+
headers: headersObj,
|
|
452
|
+
body: bodyStr
|
|
453
|
+
}, '*');
|
|
454
|
+
} catch (err) {
|
|
455
|
+
clearTimeout(timer);
|
|
456
|
+
pendingFetches.delete(reqId);
|
|
457
|
+
origFetch(input, init).then(resolve, reject);
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
|
|
464
|
+
document.addEventListener('click', function (event) {
|
|
465
|
+
if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
466
|
+
var el = event.target;
|
|
467
|
+
while (el && el.tagName !== 'A') el = el.parentElement;
|
|
468
|
+
if (!el || !el.getAttribute) return;
|
|
469
|
+
var href = el.getAttribute('href');
|
|
470
|
+
var targetAttr = el.getAttribute('target');
|
|
471
|
+
if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
|
|
472
|
+
var lowerHref = href.toLowerCase();
|
|
473
|
+
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;
|
|
474
|
+
var parsed = parseLoopbackTarget(href);
|
|
475
|
+
if (!parsed) return;
|
|
476
|
+
event.preventDefault();
|
|
477
|
+
try {
|
|
478
|
+
parent.postMessage({
|
|
479
|
+
type: 'codelab:preview-navigate',
|
|
480
|
+
port: parsed.port,
|
|
481
|
+
path: parsed.path
|
|
482
|
+
}, '*');
|
|
483
|
+
} catch (e) { void e; }
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
// Sync SPA history.pushState / replaceState with the preview omni-address bar
|
|
487
|
+
try {
|
|
488
|
+
['pushState', 'replaceState'].forEach(function (method) {
|
|
489
|
+
var orig = history[method];
|
|
490
|
+
if (typeof orig !== 'function') return;
|
|
491
|
+
history[method] = function (state, title, url) {
|
|
492
|
+
var ret;
|
|
493
|
+
try { ret = orig.apply(history, arguments); } catch (e) { void e; }
|
|
494
|
+
if (url !== undefined && url !== null) {
|
|
495
|
+
var parsed = parseLoopbackTarget(String(url));
|
|
496
|
+
if (parsed) {
|
|
497
|
+
try {
|
|
498
|
+
parent.postMessage({
|
|
499
|
+
type: 'codelab:preview-url-change',
|
|
500
|
+
path: parsed.path,
|
|
501
|
+
replace: method === 'replaceState'
|
|
502
|
+
}, '*');
|
|
503
|
+
} catch (e) { void e; }
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return ret;
|
|
507
|
+
};
|
|
508
|
+
});
|
|
509
|
+
} catch (e) { void e; }
|
|
318
510
|
})();
|
|
319
511
|
<\/script>`;
|
|
320
512
|
}
|
|
@@ -12992,10 +13184,10 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
12992
13184
|
return imports;
|
|
12993
13185
|
}
|
|
12994
13186
|
|
|
12995
|
-
function
|
|
12996
|
-
const
|
|
13187
|
+
function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
|
|
13188
|
+
const files = [];
|
|
12997
13189
|
const walk = (dir, depth) => {
|
|
12998
|
-
if (depth > 8 ||
|
|
13190
|
+
if (depth > 8 || files.length >= maxFiles) return;
|
|
12999
13191
|
let entries = [];
|
|
13000
13192
|
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
13001
13193
|
for (const name of entries) {
|
|
@@ -13006,13 +13198,23 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13006
13198
|
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
13007
13199
|
if (dirFlag) {
|
|
13008
13200
|
walk(full, depth + 1);
|
|
13009
|
-
} else if (isPreviewScriptPath(name) &&
|
|
13010
|
-
try {
|
|
13201
|
+
} else if (isPreviewScriptPath(name) && files.length < maxFiles) {
|
|
13202
|
+
try {
|
|
13203
|
+
const content = vfs.readFileSync(full, 'utf8');
|
|
13204
|
+
const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
|
|
13205
|
+
files.push({ full, rel, content });
|
|
13206
|
+
} catch (err) {
|
|
13207
|
+
_shellLogger.debug('Preview script read skipped.', full, err);
|
|
13208
|
+
}
|
|
13011
13209
|
}
|
|
13012
13210
|
}
|
|
13013
13211
|
};
|
|
13014
13212
|
walk(rootDir, 0);
|
|
13015
|
-
return
|
|
13213
|
+
return files;
|
|
13214
|
+
}
|
|
13215
|
+
|
|
13216
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
13217
|
+
return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
|
|
13016
13218
|
}
|
|
13017
13219
|
|
|
13018
13220
|
function injectPreviewExtras(html, importMap) {
|
|
@@ -13037,12 +13239,6 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13037
13239
|
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
13038
13240
|
while (taken.has(port)) port++;
|
|
13039
13241
|
|
|
13040
|
-
const specifiers = new Set();
|
|
13041
|
-
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
13042
|
-
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
13043
|
-
}
|
|
13044
|
-
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
13045
|
-
|
|
13046
13242
|
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
13047
13243
|
const isDir = (p) => {
|
|
13048
13244
|
try {
|
|
@@ -13050,8 +13246,109 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13050
13246
|
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
13051
13247
|
} catch (_) { return false; }
|
|
13052
13248
|
};
|
|
13249
|
+
const isFile = (p) => exists(p) && !isDir(p);
|
|
13053
13250
|
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
13054
13251
|
|
|
13252
|
+
const resolveLocalTarget = (baseDir, rawSpec) => {
|
|
13253
|
+
if (!rawSpec || typeof rawSpec !== 'string') return null;
|
|
13254
|
+
const clean = rawSpec.split(/[?#]/)[0].trim();
|
|
13255
|
+
if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
|
|
13256
|
+
const candidateBase = clean.startsWith('/')
|
|
13257
|
+
? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
|
|
13258
|
+
: PosixPath.join(baseDir, clean);
|
|
13259
|
+
if (isFile(candidateBase)) return candidateBase;
|
|
13260
|
+
const cands = [
|
|
13261
|
+
candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
|
|
13262
|
+
candidateBase + '.mjs', candidateBase + '.cjs',
|
|
13263
|
+
PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
|
|
13264
|
+
PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
|
|
13265
|
+
];
|
|
13266
|
+
for (const c of cands) {
|
|
13267
|
+
if (isFile(c)) return c;
|
|
13268
|
+
}
|
|
13269
|
+
return null;
|
|
13270
|
+
};
|
|
13271
|
+
|
|
13272
|
+
const toLocalImportKey = (fullPath) => {
|
|
13273
|
+
const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
|
|
13274
|
+
return `@codelab-local/${rel}`;
|
|
13275
|
+
};
|
|
13276
|
+
|
|
13277
|
+
const transpileAndRewriteLocalImports = (code, sourcePath) => {
|
|
13278
|
+
let out = code;
|
|
13279
|
+
try {
|
|
13280
|
+
const rm = getRuntimeModule();
|
|
13281
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
13282
|
+
out = rm.transpileForBrowser(out, sourcePath);
|
|
13283
|
+
}
|
|
13284
|
+
} catch (err) {
|
|
13285
|
+
_shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
|
|
13286
|
+
}
|
|
13287
|
+
const fromDir = PosixPath.dirname(sourcePath);
|
|
13288
|
+
const rewriteSpec = (spec) => {
|
|
13289
|
+
if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
|
|
13290
|
+
const resolved = resolveLocalTarget(fromDir, spec);
|
|
13291
|
+
return resolved ? toLocalImportKey(resolved) : spec;
|
|
13292
|
+
};
|
|
13293
|
+
out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
|
|
13294
|
+
out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
|
|
13295
|
+
return out;
|
|
13296
|
+
};
|
|
13297
|
+
|
|
13298
|
+
const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
|
|
13299
|
+
const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
|
|
13300
|
+
const specifiers = new Set();
|
|
13301
|
+
for (const f of scriptFiles) {
|
|
13302
|
+
for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
|
|
13303
|
+
}
|
|
13304
|
+
// Also scan inline module scripts in HTML for bare specifiers
|
|
13305
|
+
const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
|
|
13306
|
+
let inlineMatch;
|
|
13307
|
+
while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
|
|
13308
|
+
if (inlineMatch[1]) {
|
|
13309
|
+
for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
|
|
13310
|
+
}
|
|
13311
|
+
}
|
|
13312
|
+
|
|
13313
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
13314
|
+
for (const f of scriptFiles) {
|
|
13315
|
+
const compiled = transpileAndRewriteLocalImports(f.content, f.full);
|
|
13316
|
+
const key = toLocalImportKey(f.full);
|
|
13317
|
+
importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
|
|
13318
|
+
}
|
|
13319
|
+
|
|
13320
|
+
const htmlDir = PosixPath.dirname(htmlTargetPath);
|
|
13321
|
+
let transformedHtml = htmlBody;
|
|
13322
|
+
|
|
13323
|
+
// Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
|
|
13324
|
+
transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
|
|
13325
|
+
if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
|
|
13326
|
+
const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
13327
|
+
if (!hrefMatch) return fullTag;
|
|
13328
|
+
const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
|
|
13329
|
+
if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
|
|
13330
|
+
const cssContent = readText(cssTarget);
|
|
13331
|
+
if (cssContent === null) return fullTag;
|
|
13332
|
+
return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '"')}">\n${cssContent}\n</style>`;
|
|
13333
|
+
});
|
|
13334
|
+
|
|
13335
|
+
// Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
|
|
13336
|
+
transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
|
|
13337
|
+
const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
13338
|
+
if (!srcMatch) return fullTag;
|
|
13339
|
+
const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
|
|
13340
|
+
if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
|
|
13341
|
+
const rawScript = readText(scriptTarget);
|
|
13342
|
+
if (rawScript === null) return fullTag;
|
|
13343
|
+
const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
|
|
13344
|
+
const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
|
|
13345
|
+
const typeAttr = isMod ? ' type="module"' : '';
|
|
13346
|
+
return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '"')}">\n${compiled}\n</script>`;
|
|
13347
|
+
});
|
|
13348
|
+
|
|
13349
|
+
return injectPreviewExtras(transformedHtml, importMap);
|
|
13350
|
+
};
|
|
13351
|
+
|
|
13055
13352
|
const handler = async (request) => {
|
|
13056
13353
|
let pathname = '/';
|
|
13057
13354
|
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
|
|
@@ -13086,7 +13383,7 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13086
13383
|
let body = readText(target);
|
|
13087
13384
|
if (body === null) body = '';
|
|
13088
13385
|
if (/\.html?$/i.test(target)) {
|
|
13089
|
-
body =
|
|
13386
|
+
body = buildHtmlPreviewResponse(body, target);
|
|
13090
13387
|
} else if (isPreviewScriptPath(target)) {
|
|
13091
13388
|
try {
|
|
13092
13389
|
const rm = getRuntimeModule();
|
|
@@ -18456,7 +18753,7 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
18456
18753
|
|
|
18457
18754
|
// The bundler rewrites this literal from package.json at build time. Keeping
|
|
18458
18755
|
// the fallback in sync lets tests require src/workbench.js directly.
|
|
18459
|
-
const CODELAB_VERSION = '0.1.
|
|
18756
|
+
const CODELAB_VERSION = '0.1.9';
|
|
18460
18757
|
|
|
18461
18758
|
// Ambient TypeScript declarations for Node.js built-ins inside Monaco
|
|
18462
18759
|
const NODE_AMBIENT_DTS = `
|
|
@@ -19775,6 +20072,10 @@ declare module 'bun:sqlite' {
|
|
|
19775
20072
|
path: '/',
|
|
19776
20073
|
url: '',
|
|
19777
20074
|
frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
|
|
20075
|
+
dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
|
|
20076
|
+
maximized: false,
|
|
20077
|
+
consoleOpen: false,
|
|
20078
|
+
consoleLogs: [],
|
|
19778
20079
|
loading: false,
|
|
19779
20080
|
error: null,
|
|
19780
20081
|
srcdoc: '',
|
|
@@ -19786,6 +20087,7 @@ declare module 'bun:sqlite' {
|
|
|
19786
20087
|
this._previewSwRegistration = null;
|
|
19787
20088
|
this._previewViolationHandler = null;
|
|
19788
20089
|
this._swMessageHandler = null;
|
|
20090
|
+
this._beforeUnloadHandler = null;
|
|
19789
20091
|
this._portToasts = new Map();
|
|
19790
20092
|
this.isFullscreen = false;
|
|
19791
20093
|
this.isRunning = false;
|
|
@@ -20132,6 +20434,11 @@ declare module 'bun:sqlite' {
|
|
|
20132
20434
|
const key = `${this.mode}:${this.lang}`;
|
|
20133
20435
|
const customFiles = (this.savedState && this.savedState.customFiles) || {};
|
|
20134
20436
|
customFiles[key] = { ...this.files };
|
|
20437
|
+
const hasSnapshot = Object.assign(
|
|
20438
|
+
{},
|
|
20439
|
+
(this.savedState && this.savedState.hasSnapshot) || {},
|
|
20440
|
+
{ [key]: true }
|
|
20441
|
+
);
|
|
20135
20442
|
const completedArr = Array.from(this.completedSteps);
|
|
20136
20443
|
const state = {
|
|
20137
20444
|
mode: this.mode,
|
|
@@ -20139,6 +20446,7 @@ declare module 'bun:sqlite' {
|
|
|
20139
20446
|
activeStepIndex: this.activeStepIndex,
|
|
20140
20447
|
completedSteps: completedArr,
|
|
20141
20448
|
customFiles,
|
|
20449
|
+
hasSnapshot,
|
|
20142
20450
|
openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
|
|
20143
20451
|
activeFile: this.activeFile,
|
|
20144
20452
|
folders: Array.from(this.folders || []),
|
|
@@ -20163,6 +20471,20 @@ declare module 'bun:sqlite' {
|
|
|
20163
20471
|
safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
|
|
20164
20472
|
safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
|
|
20165
20473
|
];
|
|
20474
|
+
if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
|
|
20475
|
+
try {
|
|
20476
|
+
if (!this._idbStorage) {
|
|
20477
|
+
this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
|
|
20478
|
+
}
|
|
20479
|
+
if (this._idbStorage && typeof this._idbStorage.save === 'function') {
|
|
20480
|
+
Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
|
|
20481
|
+
this.logger.debug('Async WorkspaceStorage save skipped.', err);
|
|
20482
|
+
});
|
|
20483
|
+
}
|
|
20484
|
+
} catch (err) {
|
|
20485
|
+
this.logger.debug('WorkspaceStorage initialization skipped.', err);
|
|
20486
|
+
}
|
|
20487
|
+
}
|
|
20166
20488
|
if (persisted.includes(false)) {
|
|
20167
20489
|
this._reportPersistenceFailure(safeStorageSet._lastError);
|
|
20168
20490
|
} else {
|
|
@@ -20315,6 +20637,9 @@ declare module 'bun:sqlite' {
|
|
|
20315
20637
|
const key = `${this.mode}:${this.lang}`;
|
|
20316
20638
|
const saved = this.savedState.customFiles?.[key];
|
|
20317
20639
|
const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
|
|
20640
|
+
if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
|
|
20641
|
+
return { ...saved };
|
|
20642
|
+
}
|
|
20318
20643
|
if (saved && Object.keys(saved).length > 0) {
|
|
20319
20644
|
return { ...base, ...saved };
|
|
20320
20645
|
}
|
|
@@ -20527,6 +20852,10 @@ declare module 'bun:sqlite' {
|
|
|
20527
20852
|
<div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
|
|
20528
20853
|
</div>
|
|
20529
20854
|
</div>
|
|
20855
|
+
|
|
20856
|
+
<!-- Right-Hand Split Web Preview Pane -->
|
|
20857
|
+
<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>
|
|
20858
|
+
<div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
|
|
20530
20859
|
</div>
|
|
20531
20860
|
|
|
20532
20861
|
<!-- Interactive Horizontal Splitter -->
|
|
@@ -22908,6 +23237,10 @@ declare module 'bun:sqlite' {
|
|
|
22908
23237
|
type: level === 'error' ? 'stderr' : 'stdout',
|
|
22909
23238
|
text: `[Preview ${level.toUpperCase()}] ${text}`
|
|
22910
23239
|
});
|
|
23240
|
+
if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
|
|
23241
|
+
this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
|
|
23242
|
+
if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
|
|
23243
|
+
this._updatePreviewConsoleUI();
|
|
22911
23244
|
this._emitEvent('preview-console', { level, text, args });
|
|
22912
23245
|
} else if (data.type === 'codelab:preview-error') {
|
|
22913
23246
|
const msg = String(data.message || 'Uncaught runtime error');
|
|
@@ -22922,9 +23255,66 @@ declare module 'bun:sqlite' {
|
|
|
22922
23255
|
type: 'stderr',
|
|
22923
23256
|
text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
|
|
22924
23257
|
});
|
|
23258
|
+
if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
|
|
23259
|
+
this.previewState.consoleLogs.push({
|
|
23260
|
+
level: 'error',
|
|
23261
|
+
text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
|
|
23262
|
+
timestamp: new Date().toLocaleTimeString()
|
|
23263
|
+
});
|
|
23264
|
+
this._updatePreviewConsoleUI();
|
|
22925
23265
|
this._emitEvent('preview-error', this.previewState.runtimeError);
|
|
22926
23266
|
} else if (data.type === 'codelab:preview-error-clear') {
|
|
22927
23267
|
this.previewState.runtimeError = null;
|
|
23268
|
+
} else if (data.type === 'codelab:preview-fetch') {
|
|
23269
|
+
const reqId = data.reqId || data.id;
|
|
23270
|
+
const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
|
|
23271
|
+
const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
|
|
23272
|
+
const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
|
|
23273
|
+
this._dispatchPreviewRequest({
|
|
23274
|
+
port: targetPort,
|
|
23275
|
+
url: targetUrl,
|
|
23276
|
+
method: data.method || 'GET',
|
|
23277
|
+
headers: data.headers || {},
|
|
23278
|
+
body: data.body !== undefined ? data.body : null
|
|
23279
|
+
})
|
|
23280
|
+
.then((res) => {
|
|
23281
|
+
const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
|
|
23282
|
+
if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
|
|
23283
|
+
if (this.drawerTab === 'network') this._renderDrawerBody();
|
|
23284
|
+
if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
|
|
23285
|
+
iframe.contentWindow.postMessage({
|
|
23286
|
+
type: 'codelab:preview-fetch-res',
|
|
23287
|
+
reqId,
|
|
23288
|
+
id: reqId,
|
|
23289
|
+
status: res.status || 200,
|
|
23290
|
+
statusText: res.statusText || 'OK',
|
|
23291
|
+
headers: res.headers || {},
|
|
23292
|
+
body: res.body || ''
|
|
23293
|
+
}, '*');
|
|
23294
|
+
}
|
|
23295
|
+
})
|
|
23296
|
+
.catch((err) => {
|
|
23297
|
+
if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
|
|
23298
|
+
iframe.contentWindow.postMessage({
|
|
23299
|
+
type: 'codelab:preview-fetch-res',
|
|
23300
|
+
reqId,
|
|
23301
|
+
id: reqId,
|
|
23302
|
+
error: String((err && err.message) || err)
|
|
23303
|
+
}, '*');
|
|
23304
|
+
}
|
|
23305
|
+
});
|
|
23306
|
+
} else if (data.type === 'codelab:preview-navigate') {
|
|
23307
|
+
const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
|
|
23308
|
+
if (navHref) {
|
|
23309
|
+
this._previewGo(String(navHref));
|
|
23310
|
+
}
|
|
23311
|
+
} else if (data.type === 'codelab:preview-url-change') {
|
|
23312
|
+
if (data.path && typeof data.path === 'string') {
|
|
23313
|
+
this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
|
|
23314
|
+
this.previewState.url = this._previewUrl();
|
|
23315
|
+
const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
|
|
23316
|
+
if (input) input.value = this.previewState.url;
|
|
23317
|
+
}
|
|
22928
23318
|
}
|
|
22929
23319
|
};
|
|
22930
23320
|
window.addEventListener('message', this._previewViolationHandler);
|
|
@@ -22988,7 +23378,12 @@ declare module 'bun:sqlite' {
|
|
|
22988
23378
|
this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
|
|
22989
23379
|
this.previewHistory.push(this.previewState.url);
|
|
22990
23380
|
this.previewHistoryIdx = this.previewHistory.length - 1;
|
|
22991
|
-
this.
|
|
23381
|
+
if (this.previewState.dockMode === 'split') {
|
|
23382
|
+
const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
|
|
23383
|
+
if (splitHost) this._renderWebPreview(splitHost);
|
|
23384
|
+
} else {
|
|
23385
|
+
this.switchDrawerTab('preview');
|
|
23386
|
+
}
|
|
22992
23387
|
return this._previewLoadPromise || Promise.resolve();
|
|
22993
23388
|
}
|
|
22994
23389
|
|
|
@@ -23107,7 +23502,12 @@ declare module 'bun:sqlite' {
|
|
|
23107
23502
|
this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
|
|
23108
23503
|
this.previewHistory.push(url);
|
|
23109
23504
|
this.previewHistoryIdx = this.previewHistory.length - 1;
|
|
23110
|
-
this.
|
|
23505
|
+
if (this.previewState.dockMode === 'split') {
|
|
23506
|
+
const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
|
|
23507
|
+
if (splitHost) this._renderWebPreview(splitHost);
|
|
23508
|
+
} else {
|
|
23509
|
+
this.switchDrawerTab('preview');
|
|
23510
|
+
}
|
|
23111
23511
|
return this._previewLoadPromise || Promise.resolve();
|
|
23112
23512
|
}
|
|
23113
23513
|
|
|
@@ -23148,6 +23548,94 @@ declare module 'bun:sqlite' {
|
|
|
23148
23548
|
if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
|
|
23149
23549
|
this.previewState.frameMode = mode;
|
|
23150
23550
|
this._renderDrawerBody();
|
|
23551
|
+
if (this.previewState.dockMode === 'split') {
|
|
23552
|
+
const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
|
|
23553
|
+
if (splitHost) this._renderWebPreview(splitHost);
|
|
23554
|
+
}
|
|
23555
|
+
}
|
|
23556
|
+
|
|
23557
|
+
_togglePreviewDock() {
|
|
23558
|
+
this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
|
|
23559
|
+
this._previewRenderKey = null;
|
|
23560
|
+
const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
|
|
23561
|
+
const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
|
|
23562
|
+
if (this.previewState.dockMode === 'split') {
|
|
23563
|
+
if (splitBar) splitBar.style.display = 'block';
|
|
23564
|
+
if (splitHost) {
|
|
23565
|
+
splitHost.style.display = 'flex';
|
|
23566
|
+
this._renderWebPreview(splitHost);
|
|
23567
|
+
}
|
|
23568
|
+
if (this.drawerTab === 'preview') {
|
|
23569
|
+
this.switchDrawerTab('terminal');
|
|
23570
|
+
} else {
|
|
23571
|
+
this._renderDrawerBody();
|
|
23572
|
+
}
|
|
23573
|
+
} else {
|
|
23574
|
+
if (splitBar) splitBar.style.display = 'none';
|
|
23575
|
+
if (splitHost) {
|
|
23576
|
+
splitHost.style.display = 'none';
|
|
23577
|
+
splitHost.innerHTML = '';
|
|
23578
|
+
}
|
|
23579
|
+
this.switchDrawerTab('preview');
|
|
23580
|
+
}
|
|
23581
|
+
if (this.editor && typeof this.editor.layout === 'function') {
|
|
23582
|
+
setTimeout(() => {
|
|
23583
|
+
if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
|
|
23584
|
+
}, 30);
|
|
23585
|
+
}
|
|
23586
|
+
}
|
|
23587
|
+
|
|
23588
|
+
_togglePreviewMaximize() {
|
|
23589
|
+
this.previewState.maximized = !this.previewState.maximized;
|
|
23590
|
+
const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
|
|
23591
|
+
if (previewEl) {
|
|
23592
|
+
previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
|
|
23593
|
+
}
|
|
23594
|
+
const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
|
|
23595
|
+
if (maxBtn) {
|
|
23596
|
+
maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
|
|
23597
|
+
}
|
|
23598
|
+
}
|
|
23599
|
+
|
|
23600
|
+
_togglePreviewConsole() {
|
|
23601
|
+
this.previewState.consoleOpen = !this.previewState.consoleOpen;
|
|
23602
|
+
this._updatePreviewConsoleUI();
|
|
23603
|
+
}
|
|
23604
|
+
|
|
23605
|
+
_clearPreviewConsole() {
|
|
23606
|
+
this.previewState.consoleLogs = [];
|
|
23607
|
+
this._updatePreviewConsoleUI();
|
|
23608
|
+
}
|
|
23609
|
+
|
|
23610
|
+
_updatePreviewConsoleUI() {
|
|
23611
|
+
if (!this.container) return;
|
|
23612
|
+
const consoleDrawer = this.container.querySelector('#cl-preview-console');
|
|
23613
|
+
const consoleBody = this.container.querySelector('#cl-preview-console-body');
|
|
23614
|
+
const consolePill = this.container.querySelector('#cl-preview-console-pill');
|
|
23615
|
+
const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
|
|
23616
|
+
const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
|
|
23617
|
+
if (consolePill) {
|
|
23618
|
+
consolePill.textContent = String(logs.length);
|
|
23619
|
+
}
|
|
23620
|
+
if (consoleBtn) {
|
|
23621
|
+
consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
|
|
23622
|
+
}
|
|
23623
|
+
if (consoleDrawer) {
|
|
23624
|
+
consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
|
|
23625
|
+
}
|
|
23626
|
+
if (consoleBody) {
|
|
23627
|
+
if (logs.length === 0) {
|
|
23628
|
+
consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
|
|
23629
|
+
} else {
|
|
23630
|
+
consoleBody.innerHTML = logs.map((entry) => `
|
|
23631
|
+
<div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
|
|
23632
|
+
<span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
|
|
23633
|
+
<span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
|
|
23634
|
+
</div>
|
|
23635
|
+
`).join('');
|
|
23636
|
+
consoleBody.scrollTop = consoleBody.scrollHeight;
|
|
23637
|
+
}
|
|
23638
|
+
}
|
|
23151
23639
|
}
|
|
23152
23640
|
|
|
23153
23641
|
_renderWebPreviewControls() {
|
|
@@ -23159,6 +23647,7 @@ declare module 'bun:sqlite' {
|
|
|
23159
23647
|
if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
|
|
23160
23648
|
const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
|
|
23161
23649
|
if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
|
|
23650
|
+
this._updatePreviewConsoleUI();
|
|
23162
23651
|
}
|
|
23163
23652
|
|
|
23164
23653
|
_popoutPreview() {
|
|
@@ -23179,8 +23668,32 @@ declare module 'bun:sqlite' {
|
|
|
23179
23668
|
_renderWebPreview(bodyEl) {
|
|
23180
23669
|
if (!bodyEl) return;
|
|
23181
23670
|
this._warnPreviewIsolation();
|
|
23182
|
-
const
|
|
23183
|
-
|
|
23671
|
+
const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
|
|
23672
|
+
const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
|
|
23673
|
+
|
|
23674
|
+
let targetHost = bodyEl;
|
|
23675
|
+
if (this.previewState.dockMode === 'split' && splitHost) {
|
|
23676
|
+
if (splitBar) splitBar.style.display = 'block';
|
|
23677
|
+
splitHost.style.display = 'flex';
|
|
23678
|
+
if (bodyEl !== splitHost) {
|
|
23679
|
+
bodyEl.innerHTML = `
|
|
23680
|
+
<div class="codelab-preview-split-notice">
|
|
23681
|
+
<span>Web Preview is docked to the right split pane.</span>
|
|
23682
|
+
<button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
|
|
23683
|
+
</div>
|
|
23684
|
+
`;
|
|
23685
|
+
}
|
|
23686
|
+
targetHost = splitHost;
|
|
23687
|
+
} else {
|
|
23688
|
+
if (splitBar) splitBar.style.display = 'none';
|
|
23689
|
+
if (splitHost && bodyEl !== splitHost) {
|
|
23690
|
+
splitHost.style.display = 'none';
|
|
23691
|
+
splitHost.innerHTML = '';
|
|
23692
|
+
}
|
|
23693
|
+
}
|
|
23694
|
+
|
|
23695
|
+
const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
|
|
23696
|
+
if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
|
|
23184
23697
|
this._renderWebPreviewControls();
|
|
23185
23698
|
return;
|
|
23186
23699
|
}
|
|
@@ -23211,8 +23724,11 @@ declare module 'bun:sqlite' {
|
|
|
23211
23724
|
? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
|
|
23212
23725
|
: `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
|
|
23213
23726
|
|
|
23214
|
-
|
|
23215
|
-
|
|
23727
|
+
const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
|
|
23728
|
+
const isSplit = this.previewState.dockMode === 'split';
|
|
23729
|
+
|
|
23730
|
+
targetHost.innerHTML = `
|
|
23731
|
+
<div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
|
|
23216
23732
|
<div class="codelab-preview-chrome">
|
|
23217
23733
|
<div class="codelab-preview-nav">
|
|
23218
23734
|
<button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
|
|
@@ -23228,11 +23744,30 @@ declare module 'bun:sqlite' {
|
|
|
23228
23744
|
</div>
|
|
23229
23745
|
<span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
|
|
23230
23746
|
<span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
|
|
23747
|
+
<button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
|
|
23748
|
+
${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
|
|
23749
|
+
</button>
|
|
23750
|
+
<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'}">
|
|
23751
|
+
${CL_ICONS.layout || '◫'}
|
|
23752
|
+
</button>
|
|
23753
|
+
<button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
|
|
23754
|
+
${CL_ICONS.maximize || '⛶'}
|
|
23755
|
+
</button>
|
|
23231
23756
|
<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>
|
|
23232
23757
|
</div>
|
|
23233
23758
|
<div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
|
|
23234
23759
|
<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>
|
|
23235
23760
|
</div>
|
|
23761
|
+
<div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
|
|
23762
|
+
<div class="codelab-preview-console__bar">
|
|
23763
|
+
<span>Preview Console</span>
|
|
23764
|
+
<div style="display:flex;align-items:center;gap:6px;">
|
|
23765
|
+
<button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
|
|
23766
|
+
<button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
|
|
23767
|
+
</div>
|
|
23768
|
+
</div>
|
|
23769
|
+
<div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
|
|
23770
|
+
</div>
|
|
23236
23771
|
${servers.length
|
|
23237
23772
|
? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
|
|
23238
23773
|
: `<div class="codelab-preview-empty">
|
|
@@ -23245,6 +23780,7 @@ declare module 'bun:sqlite' {
|
|
|
23245
23780
|
</div>
|
|
23246
23781
|
`;
|
|
23247
23782
|
this._updatePreviewCspStatus();
|
|
23783
|
+
this._updatePreviewConsoleUI();
|
|
23248
23784
|
this._loadPreviewFrame();
|
|
23249
23785
|
}
|
|
23250
23786
|
|
|
@@ -23261,11 +23797,12 @@ declare module 'bun:sqlite' {
|
|
|
23261
23797
|
this.previewState.error = 'No port selected';
|
|
23262
23798
|
return Promise.resolve();
|
|
23263
23799
|
}
|
|
23800
|
+
this._syncFilesToShellVfs();
|
|
23264
23801
|
const fullUrl = this._previewUrl();
|
|
23265
23802
|
this.previewState.loading = true;
|
|
23266
23803
|
this.previewState.error = null;
|
|
23267
23804
|
|
|
23268
|
-
if (this._previewSwReady) {
|
|
23805
|
+
if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
|
|
23269
23806
|
try {
|
|
23270
23807
|
const u = new URL(fullUrl);
|
|
23271
23808
|
if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
|
|
@@ -23277,8 +23814,8 @@ declare module 'bun:sqlite' {
|
|
|
23277
23814
|
}
|
|
23278
23815
|
}
|
|
23279
23816
|
|
|
23280
|
-
//
|
|
23281
|
-
//
|
|
23817
|
+
// Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
|
|
23818
|
+
// race conditions and 100% deterministic loading inside sandboxed iframes.
|
|
23282
23819
|
return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
|
|
23283
23820
|
.then((res) => {
|
|
23284
23821
|
let body = res.body || '';
|
|
@@ -23664,7 +24201,7 @@ declare module 'bun:sqlite' {
|
|
|
23664
24201
|
this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
|
|
23665
24202
|
}
|
|
23666
24203
|
}
|
|
23667
|
-
if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
|
|
24204
|
+
if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
|
|
23668
24205
|
if (this._previewReloadTimer) {
|
|
23669
24206
|
clearTimeout(this._previewReloadTimer);
|
|
23670
24207
|
}
|
|
@@ -23840,6 +24377,16 @@ declare module 'bun:sqlite' {
|
|
|
23840
24377
|
};
|
|
23841
24378
|
if (typeof document !== 'undefined') {
|
|
23842
24379
|
document.addEventListener('keydown', this._escHandler);
|
|
24380
|
+
this._beforeUnloadHandler = () => {
|
|
24381
|
+
if (document.visibilityState === 'hidden') {
|
|
24382
|
+
try {
|
|
24383
|
+
this._saveState();
|
|
24384
|
+
} catch (err) {
|
|
24385
|
+
void err;
|
|
24386
|
+
}
|
|
24387
|
+
}
|
|
24388
|
+
};
|
|
24389
|
+
document.addEventListener('visibilitychange', this._beforeUnloadHandler);
|
|
23843
24390
|
}
|
|
23844
24391
|
|
|
23845
24392
|
this.container.addEventListener('keydown', e => {
|
|
@@ -24286,15 +24833,29 @@ declare module 'bun:sqlite' {
|
|
|
24286
24833
|
this._previewSetFrameMode(actionBtn.dataset.mode);
|
|
24287
24834
|
} else if (action === 'preview-popout') {
|
|
24288
24835
|
this._popoutPreview();
|
|
24836
|
+
} else if (action === 'preview-dock-toggle') {
|
|
24837
|
+
this._togglePreviewDock();
|
|
24838
|
+
} else if (action === 'preview-maximize') {
|
|
24839
|
+
this._togglePreviewMaximize();
|
|
24840
|
+
} else if (action === 'preview-console-toggle') {
|
|
24841
|
+
this._togglePreviewConsole();
|
|
24842
|
+
} else if (action === 'preview-console-clear') {
|
|
24843
|
+
this._clearPreviewConsole();
|
|
24289
24844
|
} else if (action === 'open-port-client') {
|
|
24290
|
-
const port = actionBtn.dataset.port;
|
|
24845
|
+
const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
|
|
24291
24846
|
if (port) {
|
|
24292
24847
|
this.httpClientUrl = `http://localhost:${port}/`;
|
|
24848
|
+
if (this.httpClientState) {
|
|
24849
|
+
this.httpClientState.url = `http://localhost:${port}/`;
|
|
24850
|
+
}
|
|
24293
24851
|
this._renderDrawerBody();
|
|
24294
24852
|
}
|
|
24295
24853
|
} else if (action === 'stop-port') {
|
|
24296
|
-
const port = Number(actionBtn.dataset.port);
|
|
24854
|
+
const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
|
|
24297
24855
|
if (port) {
|
|
24856
|
+
if (this.portTable && typeof this.portTable.closeServer === 'function') {
|
|
24857
|
+
this.portTable.closeServer(port);
|
|
24858
|
+
}
|
|
24298
24859
|
if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
|
|
24299
24860
|
this.shell.portTable.unregister(port);
|
|
24300
24861
|
}
|
|
@@ -24304,18 +24865,32 @@ declare module 'bun:sqlite' {
|
|
|
24304
24865
|
} else if (action === 'http-send') {
|
|
24305
24866
|
this._sendHttpClientRequest();
|
|
24306
24867
|
} else if (action === 'http-tab') {
|
|
24307
|
-
|
|
24868
|
+
const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
|
|
24869
|
+
this.httpActiveTab = nextTab;
|
|
24870
|
+
if (this.httpClientState) {
|
|
24871
|
+
this.httpClientState.activeResponseTab = nextTab;
|
|
24872
|
+
}
|
|
24308
24873
|
this._renderDrawerBody();
|
|
24309
24874
|
} else if (action === 'clear-net-traces') {
|
|
24310
24875
|
this.lastHttpTrace = [];
|
|
24311
24876
|
this.selectedNetTraceIdx = null;
|
|
24877
|
+
if (this.networkFilter) {
|
|
24878
|
+
this.networkFilter.selectedTraceId = null;
|
|
24879
|
+
}
|
|
24312
24880
|
this._renderDrawerBody();
|
|
24313
24881
|
} else if (action === 'select-net-trace') {
|
|
24882
|
+
const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
|
|
24314
24883
|
const idx = Number(actionBtn.dataset.traceIdx);
|
|
24315
24884
|
this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
|
|
24885
|
+
if (this.networkFilter) {
|
|
24886
|
+
this.networkFilter.selectedTraceId = traceId;
|
|
24887
|
+
}
|
|
24316
24888
|
this._renderDrawerBody();
|
|
24317
24889
|
} else if (action === 'close-net-detail') {
|
|
24318
24890
|
this.selectedNetTraceIdx = null;
|
|
24891
|
+
if (this.networkFilter) {
|
|
24892
|
+
this.networkFilter.selectedTraceId = null;
|
|
24893
|
+
}
|
|
24319
24894
|
this._renderDrawerBody();
|
|
24320
24895
|
}
|
|
24321
24896
|
return;
|
|
@@ -24815,6 +25390,42 @@ declare module 'bun:sqlite' {
|
|
|
24815
25390
|
fSplitter.addEventListener('pointerup', onUp);
|
|
24816
25391
|
});
|
|
24817
25392
|
}
|
|
25393
|
+
|
|
25394
|
+
const pSplitter = this.container.querySelector('#cl-splitter-preview');
|
|
25395
|
+
if (pSplitter) {
|
|
25396
|
+
pSplitter.addEventListener('dblclick', () => {
|
|
25397
|
+
shell.style.setProperty('--cl-preview-split-width', '44%');
|
|
25398
|
+
if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
|
|
25399
|
+
});
|
|
25400
|
+
|
|
25401
|
+
pSplitter.addEventListener('pointerdown', e => {
|
|
25402
|
+
e.preventDefault();
|
|
25403
|
+
pSplitter.classList.add('is-dragging');
|
|
25404
|
+
shell.classList.add('is-resizing');
|
|
25405
|
+
try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
|
|
25406
|
+
|
|
25407
|
+
const onMove = ev => {
|
|
25408
|
+
const ws = this.container.querySelector('.codelab-workspace');
|
|
25409
|
+
const rect = (ws || shell).getBoundingClientRect();
|
|
25410
|
+
const minW = 240;
|
|
25411
|
+
const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
|
|
25412
|
+
const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
|
|
25413
|
+
shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
|
|
25414
|
+
if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
|
|
25415
|
+
};
|
|
25416
|
+
|
|
25417
|
+
const onUp = ev => {
|
|
25418
|
+
pSplitter.classList.remove('is-dragging');
|
|
25419
|
+
shell.classList.remove('is-resizing');
|
|
25420
|
+
try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
|
|
25421
|
+
pSplitter.removeEventListener('pointermove', onMove);
|
|
25422
|
+
pSplitter.removeEventListener('pointerup', onUp);
|
|
25423
|
+
};
|
|
25424
|
+
|
|
25425
|
+
pSplitter.addEventListener('pointermove', onMove);
|
|
25426
|
+
pSplitter.addEventListener('pointerup', onUp);
|
|
25427
|
+
});
|
|
25428
|
+
}
|
|
24818
25429
|
}
|
|
24819
25430
|
|
|
24820
25431
|
selectStep(idx, shouldJump = true) {
|
|
@@ -25043,6 +25654,9 @@ declare module 'bun:sqlite' {
|
|
|
25043
25654
|
if (this.savedState.customFiles) {
|
|
25044
25655
|
delete this.savedState.customFiles[key];
|
|
25045
25656
|
}
|
|
25657
|
+
if (this.savedState.hasSnapshot) {
|
|
25658
|
+
delete this.savedState.hasSnapshot[key];
|
|
25659
|
+
}
|
|
25046
25660
|
this._saveState();
|
|
25047
25661
|
this._syncAllModels();
|
|
25048
25662
|
this._syncActiveFileToView();
|
|
@@ -26350,6 +26964,10 @@ declare module 'bun:sqlite' {
|
|
|
26350
26964
|
if (this._escHandler && typeof document !== 'undefined') {
|
|
26351
26965
|
document.removeEventListener('keydown', this._escHandler);
|
|
26352
26966
|
}
|
|
26967
|
+
if (this._beforeUnloadHandler && typeof document !== 'undefined') {
|
|
26968
|
+
document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
|
|
26969
|
+
}
|
|
26970
|
+
this._beforeUnloadHandler = null;
|
|
26353
26971
|
if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
|
26354
26972
|
window.removeEventListener('message', this._previewViolationHandler);
|
|
26355
26973
|
}
|