@innovatorved/code-lab 0.1.6 → 0.1.8

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.
Files changed (51) hide show
  1. package/ARCHITECTURE.md +34 -16
  2. package/README.md +17 -7
  3. package/dist/code-lab.css +26 -0
  4. package/dist/code-lab.d.ts +271 -1
  5. package/dist/code-lab.esm.js +2909 -166
  6. package/dist/code-lab.js +2869 -164
  7. package/dist/csp.d.ts +86 -0
  8. package/dist/diagnostics.d.ts +43 -0
  9. package/dist/extensions/guided-lab.esm.js +66 -0
  10. package/dist/extensions/guided-lab.js +66 -0
  11. package/dist/html.d.ts +24 -0
  12. package/dist/index.d.ts +9 -1
  13. package/dist/logger.d.ts +60 -0
  14. package/dist/preview-sw.js +425 -11
  15. package/dist/runtime.d.ts +6 -27
  16. package/dist/runtime.esm.js +171 -31
  17. package/dist/runtime.js +171 -31
  18. package/dist/schemas.d.ts +366 -25
  19. package/dist/schemas.esm.js +73 -0
  20. package/dist/schemas.js +73 -0
  21. package/dist/scm.d.ts +77 -0
  22. package/dist/search.d.ts +75 -0
  23. package/dist/shell.d.ts +18 -47
  24. package/dist/shell.esm.js +236 -37
  25. package/dist/shell.js +236 -37
  26. package/dist/storage.d.ts +57 -0
  27. package/dist/terminal.d.ts +11 -87
  28. package/dist/terminal.esm.js +124 -7
  29. package/dist/terminal.js +124 -7
  30. package/dist/zip.d.ts +42 -0
  31. package/package.json +11 -3
  32. package/src/code-lab.css +26 -0
  33. package/src/csp.ts +396 -0
  34. package/src/diagnostics.ts +116 -0
  35. package/src/html.ts +88 -0
  36. package/src/index.ts +39 -1
  37. package/src/logger.ts +139 -0
  38. package/src/preview-sw.js +97 -11
  39. package/src/runtime.ts +132 -105
  40. package/src/schemas.ts +94 -1
  41. package/src/scm.ts +268 -0
  42. package/src/search.ts +389 -0
  43. package/src/shell.ts +410 -369
  44. package/src/storage.ts +377 -0
  45. package/src/terminal.ts +898 -918
  46. package/src/workbench.ts +926 -89
  47. package/src/zip.ts +326 -0
  48. package/src/runtime.js +0 -8229
  49. package/src/shell.js +0 -7257
  50. package/src/terminal.js +0 -1046
  51. package/src/workbench.js +0 -7353
@@ -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.8 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -16,8 +16,1681 @@
16
16
  */
17
17
  const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : {};
18
18
 
19
+ // --- Module 0: Preview CSP, Structured Logger, Safe HTML & Leaf Engines ---
20
+ var CodeLabCsp = (() => {
21
+ var __defProp = Object.defineProperty;
22
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
23
+ var __getOwnPropNames = Object.getOwnPropertyNames;
24
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+
39
+ // src/csp.ts
40
+ var csp_exports = {};
41
+ __export(csp_exports, {
42
+ PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
43
+ buildPreviewPolicy: () => buildPreviewPolicy,
44
+ buildPreviewShims: () => buildPreviewShims,
45
+ default: () => csp_default,
46
+ describePreviewNetwork: () => describePreviewNetwork,
47
+ normalizeOrigin: () => normalizeOrigin,
48
+ normalizePreviewCspConfig: () => normalizePreviewCspConfig
49
+ });
50
+ var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
51
+ var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
52
+ var PRESETS = {
53
+ strict: {},
54
+ balanced: {
55
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
56
+ styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
57
+ fontSrc: FONT_CDNS.slice(),
58
+ connectSrc: IMPORT_MAP_CDNS.slice(),
59
+ imgSrc: ["https://cdn.jsdelivr.net"]
60
+ }
61
+ };
62
+ var SOURCE_KEYS = [
63
+ "scriptSrc",
64
+ "styleSrc",
65
+ "imgSrc",
66
+ "fontSrc",
67
+ "connectSrc",
68
+ "mediaSrc",
69
+ "workerSrc",
70
+ "frameSrc"
71
+ ];
72
+ var MAX_SOURCES = 64;
73
+ var MAX_SOURCE_LENGTH = 512;
74
+ var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
75
+ function normalizeOrigin(raw) {
76
+ if (raw === null || raw === void 0 || raw === "") return null;
77
+ try {
78
+ const parsed = new URL(String(raw));
79
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
80
+ return parsed.origin;
81
+ } catch (_) {
82
+ return null;
83
+ }
84
+ }
85
+ function normalizeMode(raw) {
86
+ if (raw === "strict" || raw === "custom") return raw;
87
+ return "balanced";
88
+ }
89
+ var ALLOWED_KEYWORDS = [
90
+ "'self'",
91
+ "'none'",
92
+ "'unsafe-inline'",
93
+ "'unsafe-eval'",
94
+ "'wasm-unsafe-eval'",
95
+ "'strict-dynamic'",
96
+ "'unsafe-hashes'"
97
+ ];
98
+ var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
99
+ function isSafeSource(source) {
100
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
101
+ }
102
+ function cleanSources(raw) {
103
+ if (!Array.isArray(raw)) return [];
104
+ const out = [];
105
+ for (const value of raw.slice(0, MAX_SOURCES)) {
106
+ if (typeof value !== "string") continue;
107
+ const source = value.trim();
108
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
109
+ if (!isSafeSource(source)) continue;
110
+ if (out.indexOf(source) === -1) out.push(source);
111
+ }
112
+ return out;
113
+ }
114
+ function unique(...lists) {
115
+ const out = [];
116
+ for (const list of lists) {
117
+ if (!list) continue;
118
+ for (const value of list) {
119
+ if (value && out.indexOf(value) === -1) out.push(value);
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+ function normalizePreviewCspConfig(raw) {
125
+ if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
126
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
127
+ return { mode: "balanced", allow: {} };
128
+ }
129
+ const input = raw;
130
+ const nested = input.allow;
131
+ const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
132
+ const allow = {};
133
+ for (const key of SOURCE_KEYS) {
134
+ const list = cleanSources(sources[key]);
135
+ if (list.length) allow[key] = list;
136
+ }
137
+ return { mode: normalizeMode(input.mode), allow };
138
+ }
139
+ function sourcesFor(mode, allow, key) {
140
+ const preset = mode === "custom" ? {} : PRESETS[mode];
141
+ return unique(preset[key], cleanSources(allow[key]));
142
+ }
143
+ function buildPreviewPolicy(options = {}) {
144
+ const mode = normalizeMode(options.mode);
145
+ const allow = options;
146
+ const host = normalizeOrigin(options.hostOrigin);
147
+ const self = host || "'self'";
148
+ const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
149
+ const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
150
+ const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
151
+ const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
152
+ return [
153
+ directive("default-src", [self, "data:", "blob:"]),
154
+ directive("base-uri", [self]),
155
+ "object-src 'none'",
156
+ directive("script-src", script()),
157
+ directive("style-src", style()),
158
+ directive("img-src", withData("imgSrc")),
159
+ directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
160
+ directive("connect-src", withData("connectSrc")),
161
+ directive("media-src", withData("mediaSrc")),
162
+ directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
163
+ directive("frame-src", withData("frameSrc")),
164
+ directive("form-action", [self]),
165
+ directive("frame-ancestors", [options.frameAncestors || "'self'"])
166
+ ].join("; ");
167
+ }
168
+ function describePreviewNetwork(config) {
169
+ const normalized = normalizePreviewCspConfig(config);
170
+ if (normalized.mode === "strict") return [];
171
+ const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
172
+ const hosts = [];
173
+ for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
174
+ for (const source of unique(preset[key], normalized.allow[key])) {
175
+ if (!/^https?:\/\//i.test(source)) continue;
176
+ let host;
177
+ try {
178
+ host = new URL(source).host;
179
+ } catch (_) {
180
+ continue;
181
+ }
182
+ if (hosts.indexOf(host) === -1) hosts.push(host);
183
+ }
184
+ }
185
+ return hosts;
186
+ }
187
+ function buildPreviewShims() {
188
+ return `<script ${PREVIEW_SHIM_MARKER}>
189
+ (function () {
190
+ 'use strict';
191
+ function memoryStorage() {
192
+ var data = new Map();
193
+ return {
194
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
195
+ setItem: function (k, v) { data.set(String(k), String(v)); },
196
+ removeItem: function (k) { data.delete(String(k)); },
197
+ clear: function () { data.clear(); },
198
+ key: function (i) { return Array.from(data.keys())[i] || null; },
199
+ get length() { return data.size; }
200
+ };
201
+ }
202
+ function shim(name) {
203
+ var blocked = false;
204
+ try {
205
+ var existing = window[name];
206
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
207
+ } catch (err) {
208
+ // Expected on an opaque origin: the accessor itself throws.
209
+ blocked = Boolean(err);
210
+ }
211
+ void blocked;
212
+ try {
213
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
214
+ } catch (err) {
215
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
216
+ }
217
+ }
218
+ shim('localStorage');
219
+ shim('sessionStorage');
220
+ document.addEventListener('securitypolicyviolation', function (event) {
221
+ try {
222
+ parent.postMessage({
223
+ type: 'codelab:preview-violation',
224
+ directive: event.effectiveDirective || event.violatedDirective || '',
225
+ blockedURI: event.blockedURI || '',
226
+ sourceFile: event.sourceFile || '',
227
+ line: event.lineNumber || 0
228
+ }, '*');
229
+ } catch (err) {
230
+ console.warn('[code-lab] preview: could not report CSP violation', err);
231
+ }
232
+ });
233
+ function serializeArg(arg) {
234
+ if (typeof arg !== 'object' || arg === null) return String(arg);
235
+ try {
236
+ return JSON.stringify(arg);
237
+ } catch (err) {
238
+ void err;
239
+ return '[Circular/Unserializable]';
240
+ }
241
+ }
242
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
243
+ var orig = console[level];
244
+ if (typeof orig !== 'function') return;
245
+ console[level] = function () {
246
+ var args = Array.prototype.slice.call(arguments);
247
+ try {
248
+ parent.postMessage({
249
+ type: 'codelab:preview-console',
250
+ level: level,
251
+ args: args.map(serializeArg)
252
+ }, '*');
253
+ } catch (err) {
254
+ void err;
255
+ }
256
+ return orig.apply(console, args);
257
+ };
258
+ });
259
+ function showPreviewErrorOverlay(msg, stack) {
260
+ try {
261
+ if (!document || !document.body) return;
262
+ var existing = document.getElementById('codelab-preview-error-overlay');
263
+ if (!existing) {
264
+ existing = document.createElement('div');
265
+ existing.id = 'codelab-preview-error-overlay';
266
+ existing.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,0.94);color:#f8fafc;font-family:ui-monospace,monospace;padding:24px;overflow:auto;';
267
+ document.body.appendChild(existing);
268
+ }
269
+ existing.textContent = '';
270
+ var header = document.createElement('div');
271
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
272
+ header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
273
+ var pre = document.createElement('pre');
274
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
275
+ pre.textContent = String(stack || msg || '');
276
+ existing.appendChild(header);
277
+ existing.appendChild(pre);
278
+ } catch (err) {
279
+ void err;
280
+ }
281
+ }
282
+ window.addEventListener('error', function (event) {
283
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
284
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
285
+ showPreviewErrorOverlay(msg, stack);
286
+ try {
287
+ parent.postMessage({
288
+ type: 'codelab:preview-error',
289
+ message: msg,
290
+ file: (event && event.filename) || null,
291
+ line: (event && event.lineno) || null,
292
+ col: (event && event.colno) || null,
293
+ stack: stack || null
294
+ }, '*');
295
+ } catch (err) {
296
+ void err;
297
+ }
298
+ });
299
+ window.addEventListener('unhandledrejection', function (event) {
300
+ var reason = event ? event.reason : null;
301
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
302
+ var stack = reason && reason.stack ? String(reason.stack) : '';
303
+ showPreviewErrorOverlay(msg, stack);
304
+ try {
305
+ parent.postMessage({
306
+ type: 'codelab:preview-error',
307
+ message: msg,
308
+ file: null,
309
+ line: null,
310
+ col: null,
311
+ stack: stack || null
312
+ }, '*');
313
+ } catch (err) {
314
+ void err;
315
+ }
316
+ });
317
+ })();
318
+ <\/script>`;
319
+ }
320
+ var csp_default = {
321
+ buildPreviewPolicy,
322
+ buildPreviewShims,
323
+ describePreviewNetwork,
324
+ normalizePreviewCspConfig,
325
+ normalizeOrigin,
326
+ PREVIEW_SHIM_MARKER
327
+ };
328
+ return __toCommonJS(csp_exports);
329
+ })();
330
+
331
+ var CodeLabLogger = (() => {
332
+ var __defProp = Object.defineProperty;
333
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
334
+ var __getOwnPropNames = Object.getOwnPropertyNames;
335
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
336
+ var __export = (target, all) => {
337
+ for (var name in all)
338
+ __defProp(target, name, { get: all[name], enumerable: true });
339
+ };
340
+ var __copyProps = (to, from, except, desc) => {
341
+ if (from && typeof from === "object" || typeof from === "function") {
342
+ for (let key of __getOwnPropNames(from))
343
+ if (!__hasOwnProp.call(to, key) && key !== except)
344
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
345
+ }
346
+ return to;
347
+ };
348
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
349
+
350
+ // src/logger.ts
351
+ var logger_exports = {};
352
+ __export(logger_exports, {
353
+ CodeLabError: () => CodeLabError,
354
+ DEFAULT_LOGGER: () => DEFAULT_LOGGER,
355
+ LOG_PREFIX: () => LOG_PREFIX,
356
+ createLogger: () => createLogger,
357
+ default: () => logger_default,
358
+ isCodeLabError: () => isCodeLabError
359
+ });
360
+ var LOG_PREFIX = "[code-lab]";
361
+ var CodeLabError = class extends Error {
362
+ code;
363
+ options;
364
+ cause;
365
+ recoverable;
366
+ details;
367
+ context;
368
+ constructor(code, message, options = {}) {
369
+ super(message);
370
+ this.name = "CodeLabError";
371
+ this.code = code;
372
+ this.options = options;
373
+ this.cause = options.cause;
374
+ this.recoverable = options.recoverable !== false;
375
+ const meta = options.details ?? options.context;
376
+ if (meta !== void 0) {
377
+ this.details = meta;
378
+ this.context = meta;
379
+ }
380
+ Object.setPrototypeOf(this, new.target.prototype);
381
+ }
382
+ };
383
+ function isCodeLabError(value) {
384
+ return Boolean(
385
+ value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
386
+ );
387
+ }
388
+ function createLogger(options = {}) {
389
+ const sink = options.logger ?? null;
390
+ const debugEnabled = options.debug === true;
391
+ const prefix = options.prefix || LOG_PREFIX;
392
+ const write = (level, args) => {
393
+ if (level === "debug" && !debugEnabled) return;
394
+ if (sink && typeof sink[level] === "function") {
395
+ let sinkError = null;
396
+ try {
397
+ sink[level](...args);
398
+ return;
399
+ } catch (err) {
400
+ sinkError = err;
401
+ }
402
+ }
403
+ const consoleObj = typeof console !== "undefined" ? console : null;
404
+ const fn = consoleObj ? consoleObj[level] : null;
405
+ if (typeof fn === "function") {
406
+ fn.call(consoleObj, prefix, ...args);
407
+ }
408
+ };
409
+ return {
410
+ debug: (...args) => write("debug", args),
411
+ info: (...args) => write("info", args),
412
+ warn: (...args) => write("warn", args),
413
+ error: (...args) => write("error", args)
414
+ };
415
+ }
416
+ var DEFAULT_LOGGER = createLogger();
417
+ var _loggerNamespace = {
418
+ LOG_PREFIX,
419
+ CodeLabError,
420
+ isCodeLabError,
421
+ createLogger,
422
+ DEFAULT_LOGGER
423
+ };
424
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
425
+ if (_globalRoot && !_globalRoot.CodeLabLogger) {
426
+ _globalRoot.CodeLabLogger = _loggerNamespace;
427
+ }
428
+ var logger_default = _loggerNamespace;
429
+ return __toCommonJS(logger_exports);
430
+ })();
431
+
432
+ var CodeLabHtml = (() => {
433
+ var __defProp = Object.defineProperty;
434
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
435
+ var __getOwnPropNames = Object.getOwnPropertyNames;
436
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
437
+ var __export = (target, all) => {
438
+ for (var name in all)
439
+ __defProp(target, name, { get: all[name], enumerable: true });
440
+ };
441
+ var __copyProps = (to, from, except, desc) => {
442
+ if (from && typeof from === "object" || typeof from === "function") {
443
+ for (let key of __getOwnPropNames(from))
444
+ if (!__hasOwnProp.call(to, key) && key !== except)
445
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
446
+ }
447
+ return to;
448
+ };
449
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
450
+
451
+ // src/html.ts
452
+ var html_exports = {};
453
+ __export(html_exports, {
454
+ default: () => html_default,
455
+ escapeHtml: () => escapeHtml,
456
+ html: () => html,
457
+ isSafeHtml: () => isSafeHtml,
458
+ raw: () => raw
459
+ });
460
+ var SAFE_HTML_BRAND = Symbol.for("codelab.SafeHtml");
461
+ var SafeHtmlImpl = class {
462
+ [SAFE_HTML_BRAND] = true;
463
+ __html;
464
+ constructor(trusted) {
465
+ this.__html = String(trusted);
466
+ }
467
+ toString() {
468
+ return this.__html;
469
+ }
470
+ };
471
+ function isSafeHtml(value) {
472
+ return Boolean(
473
+ value && typeof value === "object" && value[SAFE_HTML_BRAND] === true && typeof value.__html === "string"
474
+ );
475
+ }
476
+ function escapeHtml(value) {
477
+ if (value === null || value === void 0) return "";
478
+ if (isSafeHtml(value)) return value.__html;
479
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
480
+ }
481
+ function raw(trustedHtml) {
482
+ return new SafeHtmlImpl(trustedHtml);
483
+ }
484
+ function renderInterpolation(value) {
485
+ if (value === null || value === void 0 || value === false) return "";
486
+ if (isSafeHtml(value)) return value.__html;
487
+ if (Array.isArray(value)) {
488
+ let out = "";
489
+ for (let i = 0; i < value.length; i++) {
490
+ out += renderInterpolation(value[i]);
491
+ }
492
+ return out;
493
+ }
494
+ return escapeHtml(value);
495
+ }
496
+ function html(strings, ...values) {
497
+ let out = strings[0] ?? "";
498
+ for (let i = 0; i < values.length; i++) {
499
+ out += renderInterpolation(values[i]);
500
+ out += strings[i + 1] ?? "";
501
+ }
502
+ return new SafeHtmlImpl(out);
503
+ }
504
+ var _htmlNamespace = {
505
+ escapeHtml,
506
+ raw,
507
+ isSafeHtml,
508
+ html
509
+ };
510
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
511
+ if (_globalRoot && !_globalRoot.CodeLabHtml) {
512
+ _globalRoot.CodeLabHtml = _htmlNamespace;
513
+ }
514
+ var html_default = _htmlNamespace;
515
+ return __toCommonJS(html_exports);
516
+ })();
517
+
518
+ var CodeLabZip = (() => {
519
+ var __defProp = Object.defineProperty;
520
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
521
+ var __getOwnPropNames = Object.getOwnPropertyNames;
522
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
523
+ var __export = (target, all) => {
524
+ for (var name in all)
525
+ __defProp(target, name, { get: all[name], enumerable: true });
526
+ };
527
+ var __copyProps = (to, from, except, desc) => {
528
+ if (from && typeof from === "object" || typeof from === "function") {
529
+ for (let key of __getOwnPropNames(from))
530
+ if (!__hasOwnProp.call(to, key) && key !== except)
531
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
532
+ }
533
+ return to;
534
+ };
535
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
536
+
537
+ // src/zip.ts
538
+ var zip_exports = {};
539
+ __export(zip_exports, {
540
+ computeCrc32: () => computeCrc32,
541
+ createZip: () => createZip,
542
+ default: () => zip_default,
543
+ extractZip: () => extractZip,
544
+ sanitizeZipPath: () => sanitizeZipPath,
545
+ toUint8Array: () => toUint8Array
546
+ });
547
+ var LOCAL_FILE_HEADER_SIG = 67324752;
548
+ var CENTRAL_DIR_HEADER_SIG = 33639248;
549
+ var END_OF_CENTRAL_DIR_SIG = 101010256;
550
+ var UTF8_FLAG = 2048;
551
+ var CRC32_TABLE = new Uint32Array(256);
552
+ for (let i = 0; i < 256; i++) {
553
+ let c = i;
554
+ for (let k = 0; k < 8; k++) {
555
+ c = (c & 1) !== 0 ? 3988292384 ^ c >>> 1 : c >>> 1;
556
+ }
557
+ CRC32_TABLE[i] = c >>> 0;
558
+ }
559
+ var textEncoder = new TextEncoder();
560
+ var textDecoder = new TextDecoder("utf-8");
561
+ function toUint8Array(input) {
562
+ if (typeof input === "string") {
563
+ return textEncoder.encode(input);
564
+ }
565
+ if (input instanceof Uint8Array) {
566
+ return input;
567
+ }
568
+ if (input instanceof ArrayBuffer) {
569
+ return new Uint8Array(input);
570
+ }
571
+ return new Uint8Array(0);
572
+ }
573
+ function computeCrc32(data) {
574
+ const bytes = toUint8Array(data);
575
+ let crc = 4294967295;
576
+ for (let i = 0; i < bytes.length; i++) {
577
+ const index = (crc ^ bytes[i]) & 255;
578
+ crc = crc >>> 8 ^ CRC32_TABLE[index];
579
+ }
580
+ return (crc ^ 4294967295) >>> 0;
581
+ }
582
+ function sanitizeZipPath(rawPath) {
583
+ const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
584
+ const parts = normalized.split("/");
585
+ const safeParts = [];
586
+ for (const part of parts) {
587
+ const trimmed = part.trim();
588
+ if (!trimmed || trimmed === ".") continue;
589
+ if (trimmed === "..") {
590
+ if (safeParts.length > 0) {
591
+ safeParts.pop();
592
+ }
593
+ continue;
594
+ }
595
+ safeParts.push(trimmed);
596
+ }
597
+ return safeParts.join("/");
598
+ }
599
+ function writeUInt16LE(buf, offset, value) {
600
+ buf[offset] = value & 255;
601
+ buf[offset + 1] = value >>> 8 & 255;
602
+ }
603
+ function writeUInt32LE(buf, offset, value) {
604
+ buf[offset] = value & 255;
605
+ buf[offset + 1] = value >>> 8 & 255;
606
+ buf[offset + 2] = value >>> 16 & 255;
607
+ buf[offset + 3] = value >>> 24 & 255;
608
+ }
609
+ function readUInt16LE(buf, offset) {
610
+ return (buf[offset] | buf[offset + 1] << 8) >>> 0;
611
+ }
612
+ function readUInt32LE(buf, offset) {
613
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
614
+ }
615
+ async function createZip(files) {
616
+ const entries = [];
617
+ let localSectionSize = 0;
618
+ let centralDirSize = 0;
619
+ const rawKeys = Object.keys(files || {});
620
+ for (const rawKey of rawKeys) {
621
+ const safePath = sanitizeZipPath(rawKey);
622
+ if (!safePath) continue;
623
+ const rawContent = files[rawKey];
624
+ const dataBytes = toUint8Array(rawContent);
625
+ const nameBytes = textEncoder.encode(safePath);
626
+ const crc = computeCrc32(dataBytes);
627
+ entries.push({
628
+ nameBytes,
629
+ dataBytes,
630
+ crc32: crc,
631
+ offset: localSectionSize
632
+ });
633
+ localSectionSize += 30 + nameBytes.length + dataBytes.length;
634
+ centralDirSize += 46 + nameBytes.length;
635
+ }
636
+ const totalSize = localSectionSize + centralDirSize + 22;
637
+ const out = new Uint8Array(totalSize);
638
+ let cursor = 0;
639
+ for (const entry of entries) {
640
+ writeUInt32LE(out, cursor, LOCAL_FILE_HEADER_SIG);
641
+ writeUInt16LE(out, cursor + 4, 20);
642
+ writeUInt16LE(out, cursor + 6, UTF8_FLAG);
643
+ writeUInt16LE(out, cursor + 8, 0);
644
+ writeUInt16LE(out, cursor + 10, 0);
645
+ writeUInt16LE(out, cursor + 12, 8448);
646
+ writeUInt32LE(out, cursor + 14, entry.crc32);
647
+ writeUInt32LE(out, cursor + 18, entry.dataBytes.length);
648
+ writeUInt32LE(out, cursor + 22, entry.dataBytes.length);
649
+ writeUInt16LE(out, cursor + 26, entry.nameBytes.length);
650
+ writeUInt16LE(out, cursor + 28, 0);
651
+ cursor += 30;
652
+ out.set(entry.nameBytes, cursor);
653
+ cursor += entry.nameBytes.length;
654
+ out.set(entry.dataBytes, cursor);
655
+ cursor += entry.dataBytes.length;
656
+ }
657
+ const centralDirOffset = cursor;
658
+ for (const entry of entries) {
659
+ writeUInt32LE(out, cursor, CENTRAL_DIR_HEADER_SIG);
660
+ writeUInt16LE(out, cursor + 4, 20);
661
+ writeUInt16LE(out, cursor + 6, 20);
662
+ writeUInt16LE(out, cursor + 8, UTF8_FLAG);
663
+ writeUInt16LE(out, cursor + 10, 0);
664
+ writeUInt16LE(out, cursor + 12, 0);
665
+ writeUInt16LE(out, cursor + 14, 8448);
666
+ writeUInt32LE(out, cursor + 16, entry.crc32);
667
+ writeUInt32LE(out, cursor + 20, entry.dataBytes.length);
668
+ writeUInt32LE(out, cursor + 24, entry.dataBytes.length);
669
+ writeUInt16LE(out, cursor + 28, entry.nameBytes.length);
670
+ writeUInt16LE(out, cursor + 30, 0);
671
+ writeUInt16LE(out, cursor + 32, 0);
672
+ writeUInt16LE(out, cursor + 34, 0);
673
+ writeUInt16LE(out, cursor + 36, 0);
674
+ writeUInt32LE(out, cursor + 38, 0);
675
+ writeUInt32LE(out, cursor + 42, entry.offset);
676
+ cursor += 46;
677
+ out.set(entry.nameBytes, cursor);
678
+ cursor += entry.nameBytes.length;
679
+ }
680
+ writeUInt32LE(out, cursor, END_OF_CENTRAL_DIR_SIG);
681
+ writeUInt16LE(out, cursor + 4, 0);
682
+ writeUInt16LE(out, cursor + 6, 0);
683
+ writeUInt16LE(out, cursor + 8, entries.length);
684
+ writeUInt16LE(out, cursor + 10, entries.length);
685
+ writeUInt32LE(out, cursor + 12, centralDirSize);
686
+ writeUInt32LE(out, cursor + 16, centralDirOffset);
687
+ writeUInt16LE(out, cursor + 20, 0);
688
+ return out;
689
+ }
690
+ async function extractZip(data) {
691
+ const bytes = toUint8Array(data);
692
+ if (bytes.length < 22) {
693
+ throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
694
+ }
695
+ let eocdOffset = -1;
696
+ const minSearchOffset = Math.max(0, bytes.length - 65557);
697
+ for (let i = bytes.length - 22; i >= minSearchOffset; i--) {
698
+ if (readUInt32LE(bytes, i) === END_OF_CENTRAL_DIR_SIG) {
699
+ eocdOffset = i;
700
+ break;
701
+ }
702
+ }
703
+ if (eocdOffset === -1) {
704
+ throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
705
+ }
706
+ const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
707
+ const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
708
+ const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
709
+ if (centralDirOffset + centralDirSize > bytes.length) {
710
+ throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
711
+ }
712
+ const result = {};
713
+ let cdCursor = centralDirOffset;
714
+ for (let i = 0; i < totalEntries; i++) {
715
+ if (cdCursor + 46 > bytes.length) {
716
+ throw new Error("Corrupted ZIP archive: truncated Central Directory header");
717
+ }
718
+ const sig = readUInt32LE(bytes, cdCursor);
719
+ if (sig !== CENTRAL_DIR_HEADER_SIG) {
720
+ throw new Error(`Corrupted ZIP archive: invalid Central Directory signature 0x${sig.toString(16)}`);
721
+ }
722
+ const compressionMethod = readUInt16LE(bytes, cdCursor + 10);
723
+ const expectedCrc = readUInt32LE(bytes, cdCursor + 16);
724
+ const compressedSize = readUInt32LE(bytes, cdCursor + 20);
725
+ const fileNameLen = readUInt16LE(bytes, cdCursor + 28);
726
+ const extraLen = readUInt16LE(bytes, cdCursor + 30);
727
+ const commentLen = readUInt16LE(bytes, cdCursor + 32);
728
+ const localHeaderOffset = readUInt32LE(bytes, cdCursor + 42);
729
+ const nameStart = cdCursor + 46;
730
+ const nameEnd = nameStart + fileNameLen;
731
+ if (nameEnd > bytes.length) {
732
+ throw new Error("Corrupted ZIP archive: file name exceeds buffer");
733
+ }
734
+ const rawName = textDecoder.decode(bytes.subarray(nameStart, nameEnd));
735
+ cdCursor = nameEnd + extraLen + commentLen;
736
+ if (rawName.endsWith("/")) continue;
737
+ const safeName = sanitizeZipPath(rawName);
738
+ if (!safeName) continue;
739
+ if (localHeaderOffset + 30 > bytes.length) {
740
+ throw new Error(`Corrupted ZIP archive: local header offset out of bounds for ${safeName}`);
741
+ }
742
+ const localSig = readUInt32LE(bytes, localHeaderOffset);
743
+ if (localSig !== LOCAL_FILE_HEADER_SIG) {
744
+ throw new Error(`Corrupted ZIP archive: invalid Local File Header signature for ${safeName}`);
745
+ }
746
+ const localNameLen = readUInt16LE(bytes, localHeaderOffset + 26);
747
+ const localExtraLen = readUInt16LE(bytes, localHeaderOffset + 28);
748
+ const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
749
+ const dataEnd = dataStart + compressedSize;
750
+ if (dataEnd > bytes.length) {
751
+ throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
752
+ }
753
+ const rawFileBytes = bytes.subarray(dataStart, dataEnd);
754
+ if (compressionMethod !== 0) {
755
+ throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
756
+ }
757
+ const actualCrc = computeCrc32(rawFileBytes);
758
+ if (actualCrc !== expectedCrc) {
759
+ throw new Error(
760
+ `CRC32 integrity mismatch for ${safeName}: expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)}`
761
+ );
762
+ }
763
+ result[safeName] = textDecoder.decode(rawFileBytes);
764
+ }
765
+ return result;
766
+ }
767
+ var zip_default = {
768
+ createZip,
769
+ extractZip,
770
+ computeCrc32,
771
+ sanitizeZipPath,
772
+ toUint8Array
773
+ };
774
+ return __toCommonJS(zip_exports);
775
+ })();
776
+
777
+ var CodeLabStorage = (() => {
778
+ var __defProp = Object.defineProperty;
779
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
780
+ var __getOwnPropNames = Object.getOwnPropertyNames;
781
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
782
+ var __export = (target, all) => {
783
+ for (var name in all)
784
+ __defProp(target, name, { get: all[name], enumerable: true });
785
+ };
786
+ var __copyProps = (to, from, except, desc) => {
787
+ if (from && typeof from === "object" || typeof from === "function") {
788
+ for (let key of __getOwnPropNames(from))
789
+ if (!__hasOwnProp.call(to, key) && key !== except)
790
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
791
+ }
792
+ return to;
793
+ };
794
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
795
+
796
+ // src/storage.ts
797
+ var storage_exports = {};
798
+ __export(storage_exports, {
799
+ WorkspaceStorage: () => WorkspaceStorage,
800
+ createWorkspaceStorage: () => createWorkspaceStorage,
801
+ default: () => storage_default
802
+ });
803
+ var DEFAULT_DB_NAME = "codelab_workspace_db";
804
+ var DEFAULT_STORE_NAME = "projects";
805
+ var DEFAULT_LS_PREFIX = "codelab:project:";
806
+ function cloneProject(project) {
807
+ const filesCopy = {};
808
+ if (project.files && typeof project.files === "object") {
809
+ for (const [k, v] of Object.entries(project.files)) {
810
+ filesCopy[k] = String(v);
811
+ }
812
+ }
813
+ return {
814
+ id: String(project.id),
815
+ name: String(project.name || project.id),
816
+ files: filesCopy,
817
+ updatedAt: typeof project.updatedAt === "number" ? project.updatedAt : Date.now(),
818
+ ...project.createdAt !== void 0 ? { createdAt: project.createdAt } : {},
819
+ ...project.entry !== void 0 ? { entry: project.entry } : {},
820
+ ...project.testEntry !== void 0 ? { testEntry: project.testEntry } : {},
821
+ ...project.version !== void 0 ? { version: project.version } : {}
822
+ };
823
+ }
824
+ function isLocalStorageAvailable(prefix) {
825
+ try {
826
+ if (typeof globalThis === "undefined" || !("localStorage" in globalThis)) {
827
+ return false;
828
+ }
829
+ const ls = globalThis.localStorage;
830
+ if (!ls || typeof ls.getItem !== "function" || typeof ls.setItem !== "function") {
831
+ return false;
832
+ }
833
+ const probeKey = `${prefix}__probe__`;
834
+ ls.setItem(probeKey, "1");
835
+ ls.removeItem(probeKey);
836
+ return true;
837
+ } catch (err) {
838
+ const _ignored = err;
839
+ return false;
840
+ }
841
+ }
842
+ function isIndexedDbAvailable() {
843
+ try {
844
+ if (typeof globalThis === "undefined" || !("indexedDB" in globalThis)) {
845
+ return false;
846
+ }
847
+ return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === "function");
848
+ } catch (err) {
849
+ const _ignored = err;
850
+ return false;
851
+ }
852
+ }
853
+ var WorkspaceStorage = class {
854
+ dbName;
855
+ storeName;
856
+ storagePrefix;
857
+ backendType;
858
+ memoryStore = /* @__PURE__ */ new Map();
859
+ dbPromise = null;
860
+ constructor(options = {}) {
861
+ this.dbName = options.dbName || DEFAULT_DB_NAME;
862
+ this.storeName = options.storeName || DEFAULT_STORE_NAME;
863
+ this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
864
+ if (options.preferredBackend) {
865
+ this.backendType = options.preferredBackend;
866
+ } else if (isIndexedDbAvailable()) {
867
+ this.backendType = "indexeddb";
868
+ } else if (isLocalStorageAvailable(this.storagePrefix)) {
869
+ this.backendType = "localstorage";
870
+ } else {
871
+ this.backendType = "memory";
872
+ }
873
+ }
874
+ getBackendType() {
875
+ return this.backendType;
876
+ }
877
+ openIdb() {
878
+ if (this.dbPromise) return this.dbPromise;
879
+ this.dbPromise = new Promise((resolve) => {
880
+ try {
881
+ const req = globalThis.indexedDB.open(this.dbName, 1);
882
+ req.onupgradeneeded = () => {
883
+ const db = req.result;
884
+ if (!db.objectStoreNames.contains(this.storeName)) {
885
+ db.createObjectStore(this.storeName, { keyPath: "id" });
886
+ }
887
+ };
888
+ req.onsuccess = () => {
889
+ resolve(req.result);
890
+ };
891
+ req.onerror = () => {
892
+ resolve(null);
893
+ };
894
+ } catch (err) {
895
+ const _ignored = err;
896
+ resolve(null);
897
+ }
898
+ });
899
+ return this.dbPromise;
900
+ }
901
+ downgradeFromIdb() {
902
+ if (isLocalStorageAvailable(this.storagePrefix)) {
903
+ this.backendType = "localstorage";
904
+ } else {
905
+ this.backendType = "memory";
906
+ }
907
+ }
908
+ async saveProject(project) {
909
+ if (!project || typeof project.id !== "string" || !project.id.trim()) {
910
+ return false;
911
+ }
912
+ const normalized = cloneProject(project);
913
+ this.memoryStore.set(normalized.id, normalized);
914
+ if (this.backendType === "indexeddb") {
915
+ const db = await this.openIdb();
916
+ if (!db) {
917
+ this.downgradeFromIdb();
918
+ } else {
919
+ const ok = await new Promise((resolve) => {
920
+ try {
921
+ const tx = db.transaction(this.storeName, "readwrite");
922
+ const store = tx.objectStore(this.storeName);
923
+ const req = store.put(normalized);
924
+ req.onsuccess = () => resolve(true);
925
+ req.onerror = () => resolve(false);
926
+ } catch (err) {
927
+ const _ignored = err;
928
+ resolve(false);
929
+ }
930
+ });
931
+ if (ok) return true;
932
+ this.downgradeFromIdb();
933
+ }
934
+ }
935
+ if (this.backendType === "localstorage") {
936
+ try {
937
+ const key = `${this.storagePrefix}${normalized.id}`;
938
+ globalThis.localStorage.setItem(key, JSON.stringify(normalized));
939
+ return true;
940
+ } catch (err) {
941
+ const _ignored = err;
942
+ this.backendType = "memory";
943
+ }
944
+ }
945
+ return true;
946
+ }
947
+ async loadProject(id) {
948
+ if (!id || typeof id !== "string") return null;
949
+ if (this.backendType === "indexeddb") {
950
+ const db = await this.openIdb();
951
+ if (!db) {
952
+ this.downgradeFromIdb();
953
+ } else {
954
+ const found = await new Promise((resolve) => {
955
+ try {
956
+ const tx = db.transaction(this.storeName, "readonly");
957
+ const store = tx.objectStore(this.storeName);
958
+ const req = store.get(id);
959
+ req.onsuccess = () => {
960
+ const res = req.result;
961
+ resolve(res ? cloneProject(res) : null);
962
+ };
963
+ req.onerror = () => resolve(null);
964
+ } catch (err) {
965
+ const _ignored = err;
966
+ resolve(null);
967
+ }
968
+ });
969
+ if (found) return found;
970
+ }
971
+ }
972
+ if (this.backendType === "localstorage") {
973
+ try {
974
+ const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
975
+ if (raw) {
976
+ const parsed = JSON.parse(raw);
977
+ if (parsed && typeof parsed.id === "string" && parsed.files && typeof parsed.files === "object") {
978
+ return cloneProject(parsed);
979
+ }
980
+ }
981
+ } catch (err) {
982
+ const _ignored = err;
983
+ }
984
+ }
985
+ const fromMem = this.memoryStore.get(id);
986
+ return fromMem ? cloneProject(fromMem) : null;
987
+ }
988
+ async listProjects() {
989
+ const byId = /* @__PURE__ */ new Map();
990
+ const recordSummary = (proj) => {
991
+ if (!proj || typeof proj.id !== "string") return;
992
+ byId.set(proj.id, {
993
+ id: proj.id,
994
+ name: proj.name || proj.id,
995
+ updatedAt: typeof proj.updatedAt === "number" ? proj.updatedAt : Date.now(),
996
+ fileCount: proj.files && typeof proj.files === "object" ? Object.keys(proj.files).length : 0
997
+ });
998
+ };
999
+ for (const p of this.memoryStore.values()) {
1000
+ recordSummary(p);
1001
+ }
1002
+ if (this.backendType === "indexeddb") {
1003
+ const db = await this.openIdb();
1004
+ if (db) {
1005
+ await new Promise((resolve) => {
1006
+ try {
1007
+ const tx = db.transaction(this.storeName, "readonly");
1008
+ const store = tx.objectStore(this.storeName);
1009
+ const req = store.getAll();
1010
+ req.onsuccess = () => {
1011
+ const items = Array.isArray(req.result) ? req.result : [];
1012
+ for (const item of items) {
1013
+ recordSummary(item);
1014
+ }
1015
+ resolve();
1016
+ };
1017
+ req.onerror = () => resolve();
1018
+ } catch (err) {
1019
+ const _ignored = err;
1020
+ resolve();
1021
+ }
1022
+ });
1023
+ }
1024
+ } else if (this.backendType === "localstorage") {
1025
+ try {
1026
+ const ls = globalThis.localStorage;
1027
+ for (let i = 0; i < ls.length; i++) {
1028
+ const key = ls.key(i);
1029
+ if (key && key.startsWith(this.storagePrefix)) {
1030
+ const raw = ls.getItem(key);
1031
+ if (raw) {
1032
+ try {
1033
+ const parsed = JSON.parse(raw);
1034
+ recordSummary(parsed);
1035
+ } catch (parseErr) {
1036
+ const _ignored = parseErr;
1037
+ }
1038
+ }
1039
+ }
1040
+ }
1041
+ } catch (err) {
1042
+ const _ignored = err;
1043
+ }
1044
+ }
1045
+ return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
1046
+ }
1047
+ async deleteProject(id) {
1048
+ if (!id || typeof id !== "string") return false;
1049
+ let existed = this.memoryStore.delete(id);
1050
+ if (this.backendType === "indexeddb") {
1051
+ const db = await this.openIdb();
1052
+ if (db) {
1053
+ const idbDeleted = await new Promise((resolve) => {
1054
+ try {
1055
+ const tx = db.transaction(this.storeName, "readwrite");
1056
+ const store = tx.objectStore(this.storeName);
1057
+ const checkReq = store.get(id);
1058
+ checkReq.onsuccess = () => {
1059
+ if (!checkReq.result) {
1060
+ resolve(false);
1061
+ return;
1062
+ }
1063
+ const delReq = store.delete(id);
1064
+ delReq.onsuccess = () => resolve(true);
1065
+ delReq.onerror = () => resolve(false);
1066
+ };
1067
+ checkReq.onerror = () => resolve(false);
1068
+ } catch (err) {
1069
+ const _ignored = err;
1070
+ resolve(false);
1071
+ }
1072
+ });
1073
+ existed = existed || idbDeleted;
1074
+ }
1075
+ }
1076
+ if (this.backendType === "localstorage") {
1077
+ try {
1078
+ const key = `${this.storagePrefix}${id}`;
1079
+ if (globalThis.localStorage.getItem(key) !== null) {
1080
+ globalThis.localStorage.removeItem(key);
1081
+ existed = true;
1082
+ }
1083
+ } catch (err) {
1084
+ const _ignored = err;
1085
+ }
1086
+ }
1087
+ return existed;
1088
+ }
1089
+ };
1090
+ function createWorkspaceStorage(options = {}) {
1091
+ return new WorkspaceStorage(options);
1092
+ }
1093
+ var storage_default = {
1094
+ WorkspaceStorage,
1095
+ createWorkspaceStorage
1096
+ };
1097
+ return __toCommonJS(storage_exports);
1098
+ })();
1099
+
1100
+ var CodeLabSearch = (() => {
1101
+ var __defProp = Object.defineProperty;
1102
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1103
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1104
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1105
+ var __export = (target, all) => {
1106
+ for (var name in all)
1107
+ __defProp(target, name, { get: all[name], enumerable: true });
1108
+ };
1109
+ var __copyProps = (to, from, except, desc) => {
1110
+ if (from && typeof from === "object" || typeof from === "function") {
1111
+ for (let key of __getOwnPropNames(from))
1112
+ if (!__hasOwnProp.call(to, key) && key !== except)
1113
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1114
+ }
1115
+ return to;
1116
+ };
1117
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1118
+
1119
+ // src/search.ts
1120
+ var search_exports = {};
1121
+ __export(search_exports, {
1122
+ escapeRegex: () => escapeRegex,
1123
+ matchesGlob: () => matchesGlob,
1124
+ normalizeSearchPath: () => normalizeSearchPath,
1125
+ replaceInFiles: () => replaceInFiles,
1126
+ searchInFiles: () => searchInFiles
1127
+ });
1128
+ function escapeRegex(text) {
1129
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1130
+ }
1131
+ function normalizeSearchPath(filePath) {
1132
+ let p = filePath.replace(/\\/g, "/");
1133
+ while (p.startsWith("./")) {
1134
+ p = p.slice(2);
1135
+ }
1136
+ while (p.startsWith("/")) {
1137
+ p = p.slice(1);
1138
+ }
1139
+ return p;
1140
+ }
1141
+ function matchesGlob(filePath, pattern) {
1142
+ if (!pattern || pattern === "*" || pattern === "**") return true;
1143
+ const normPath = normalizeSearchPath(filePath);
1144
+ const normPattern = normalizeSearchPath(pattern);
1145
+ if (normPattern === normPath) return true;
1146
+ if (!normPattern.includes("*") && !normPattern.includes("?")) {
1147
+ return normPath.includes(normPattern) || normPath.endsWith(normPattern);
1148
+ }
1149
+ let regexStr = "^";
1150
+ let i = 0;
1151
+ while (i < normPattern.length) {
1152
+ const c = normPattern[i];
1153
+ if (c === "*") {
1154
+ if (normPattern[i + 1] === "*") {
1155
+ regexStr += ".*";
1156
+ i += 2;
1157
+ if (normPattern[i] === "/") {
1158
+ i++;
1159
+ }
1160
+ continue;
1161
+ } else {
1162
+ regexStr += "[^/]*";
1163
+ i++;
1164
+ continue;
1165
+ }
1166
+ } else if (c === "?") {
1167
+ regexStr += "[^/]";
1168
+ i++;
1169
+ continue;
1170
+ } else if ("./+^$()|[]{}\\".includes(c)) {
1171
+ regexStr += "\\" + c;
1172
+ i++;
1173
+ continue;
1174
+ } else {
1175
+ regexStr += c;
1176
+ i++;
1177
+ }
1178
+ }
1179
+ regexStr += "$";
1180
+ try {
1181
+ const re = new RegExp(regexStr);
1182
+ return re.test(normPath);
1183
+ } catch (err) {
1184
+ return normPath.includes(normPattern.replace(/[*?]/g, ""));
1185
+ }
1186
+ }
1187
+ function checkFilter(path, filter) {
1188
+ if (!filter) return true;
1189
+ if (Array.isArray(filter)) {
1190
+ return filter.some((f) => matchesGlob(path, f));
1191
+ }
1192
+ return matchesGlob(path, filter);
1193
+ }
1194
+ function createSearchResult(groups, totalMatches, fileCount, query, error) {
1195
+ const arr = [...groups];
1196
+ const result = Object.assign(arr, {
1197
+ matches: groups,
1198
+ totalMatches,
1199
+ fileCount,
1200
+ filesCount: fileCount,
1201
+ query,
1202
+ durationMs: 0,
1203
+ error
1204
+ });
1205
+ return result;
1206
+ }
1207
+ function searchInFiles(files, queryOrOptions, optionsOrUndefined) {
1208
+ let query = "";
1209
+ let opts = {};
1210
+ if (typeof queryOrOptions === "string") {
1211
+ query = queryOrOptions;
1212
+ opts = optionsOrUndefined || {};
1213
+ } else if (queryOrOptions && typeof queryOrOptions === "object") {
1214
+ opts = queryOrOptions;
1215
+ query = opts.query || "";
1216
+ }
1217
+ if (!query) {
1218
+ return createSearchResult([], 0, 0, query);
1219
+ }
1220
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1221
+ const isWholeWord = Boolean(opts.wholeWord);
1222
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1223
+ const maxMatches = opts.maxMatches ?? 1e4;
1224
+ const maxMatchesPerFile = opts.maxMatchesPerFile ?? 1e3;
1225
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1226
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1227
+ let patternStr = isRegex ? query : escapeRegex(query);
1228
+ if (isWholeWord) {
1229
+ patternStr = `\\b${patternStr}\\b`;
1230
+ }
1231
+ let regex = /(?:)/;
1232
+ try {
1233
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1234
+ } catch (err) {
1235
+ const _err = err;
1236
+ const msg = typeof _err === "object" && _err && "message" in _err ? String(_err.message) : "Invalid regular expression";
1237
+ return createSearchResult([], 0, 0, query, msg);
1238
+ }
1239
+ const matchedGroups = [];
1240
+ let totalMatches = 0;
1241
+ for (const [filePath, content] of Object.entries(files)) {
1242
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1243
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1244
+ if (opts.targetFiles && !opts.targetFiles.includes(filePath)) continue;
1245
+ const fileMatches = [];
1246
+ const lines = content.split("\n");
1247
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1248
+ const lineText = lines[lineIndex];
1249
+ regex.lastIndex = 0;
1250
+ let m = null;
1251
+ while ((m = regex.exec(lineText)) !== null) {
1252
+ const matchLen = m[0].length;
1253
+ const col = m.index + 1;
1254
+ fileMatches.push({
1255
+ line: lineIndex + 1,
1256
+ col,
1257
+ column: col,
1258
+ length: matchLen,
1259
+ matchText: m[0],
1260
+ lineText,
1261
+ beforeSnippet: lineText.slice(0, m.index),
1262
+ afterSnippet: lineText.slice(m.index + matchLen),
1263
+ matchIndex: m.index,
1264
+ matchEndIndex: m.index + matchLen
1265
+ });
1266
+ totalMatches++;
1267
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1268
+ break;
1269
+ }
1270
+ if (matchLen === 0) {
1271
+ regex.lastIndex++;
1272
+ if (regex.lastIndex > lineText.length) {
1273
+ break;
1274
+ }
1275
+ }
1276
+ }
1277
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1278
+ break;
1279
+ }
1280
+ }
1281
+ if (fileMatches.length > 0) {
1282
+ matchedGroups.push({
1283
+ file: filePath,
1284
+ matches: fileMatches
1285
+ });
1286
+ }
1287
+ if (totalMatches >= maxMatches) {
1288
+ break;
1289
+ }
1290
+ }
1291
+ return createSearchResult(matchedGroups, totalMatches, matchedGroups.length, query);
1292
+ }
1293
+ function replaceInFiles(files, arg2, arg3, arg4) {
1294
+ let query = "";
1295
+ const replacement = typeof arg3 === "string" ? arg3 : "";
1296
+ let opts = {};
1297
+ let targetFiles = void 0;
1298
+ if (typeof arg2 === "string") {
1299
+ query = arg2;
1300
+ if (Array.isArray(arg4)) {
1301
+ targetFiles = arg4;
1302
+ } else if (arg4 && typeof arg4 === "object") {
1303
+ opts = arg4;
1304
+ targetFiles = opts.targetFiles;
1305
+ }
1306
+ } else if (arg2 && typeof arg2 === "object") {
1307
+ opts = arg2;
1308
+ query = opts.query || "";
1309
+ if (Array.isArray(arg4)) {
1310
+ targetFiles = arg4;
1311
+ } else {
1312
+ targetFiles = opts.targetFiles;
1313
+ }
1314
+ }
1315
+ if (!query) {
1316
+ return {
1317
+ updatedFiles: { ...files },
1318
+ replacedCount: 0,
1319
+ filesAffected: []
1320
+ };
1321
+ }
1322
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1323
+ const isWholeWord = Boolean(opts.wholeWord);
1324
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1325
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1326
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1327
+ let patternStr = isRegex ? query : escapeRegex(query);
1328
+ if (isWholeWord) {
1329
+ patternStr = `\\b${patternStr}\\b`;
1330
+ }
1331
+ let regex = /(?:)/;
1332
+ try {
1333
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1334
+ } catch (err) {
1335
+ return {
1336
+ updatedFiles: { ...files },
1337
+ replacedCount: 0,
1338
+ filesAffected: []
1339
+ };
1340
+ }
1341
+ const updatedFiles = { ...files };
1342
+ const filesAffected = [];
1343
+ let replacedCount = 0;
1344
+ for (const [filePath, content] of Object.entries(files)) {
1345
+ if (targetFiles && !targetFiles.includes(filePath)) continue;
1346
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1347
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1348
+ regex.lastIndex = 0;
1349
+ let countInFile = 0;
1350
+ let m;
1351
+ while ((m = regex.exec(content)) !== null) {
1352
+ countInFile++;
1353
+ if (m[0].length === 0) {
1354
+ regex.lastIndex++;
1355
+ if (regex.lastIndex > content.length) {
1356
+ break;
1357
+ }
1358
+ }
1359
+ }
1360
+ if (countInFile > 0) {
1361
+ regex.lastIndex = 0;
1362
+ let newContent;
1363
+ if (isRegex) {
1364
+ newContent = content.replace(regex, replacement);
1365
+ } else {
1366
+ newContent = content.replace(regex, () => replacement);
1367
+ }
1368
+ updatedFiles[filePath] = newContent;
1369
+ filesAffected.push(filePath);
1370
+ replacedCount += countInFile;
1371
+ }
1372
+ }
1373
+ return {
1374
+ updatedFiles,
1375
+ replacedCount,
1376
+ filesAffected
1377
+ };
1378
+ }
1379
+ return __toCommonJS(search_exports);
1380
+ })();
1381
+
1382
+ var CodeLabDiagnostics = (() => {
1383
+ var __defProp = Object.defineProperty;
1384
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1385
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1386
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1387
+ var __export = (target, all) => {
1388
+ for (var name in all)
1389
+ __defProp(target, name, { get: all[name], enumerable: true });
1390
+ };
1391
+ var __copyProps = (to, from, except, desc) => {
1392
+ if (from && typeof from === "object" || typeof from === "function") {
1393
+ for (let key of __getOwnPropNames(from))
1394
+ if (!__hasOwnProp.call(to, key) && key !== except)
1395
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1396
+ }
1397
+ return to;
1398
+ };
1399
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1400
+
1401
+ // src/diagnostics.ts
1402
+ var diagnostics_exports = {};
1403
+ __export(diagnostics_exports, {
1404
+ DiagnosticsStore: () => DiagnosticsStore,
1405
+ createDiagnosticsStore: () => createDiagnosticsStore,
1406
+ default: () => diagnostics_default
1407
+ });
1408
+ var DiagnosticsStore = class {
1409
+ items = /* @__PURE__ */ new Map();
1410
+ listeners = /* @__PURE__ */ new Set();
1411
+ add(item) {
1412
+ if (!item || typeof item.id !== "string" || !item.id) return;
1413
+ const normalized = {
1414
+ ...item,
1415
+ file: String(item.file || ""),
1416
+ line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
1417
+ col: typeof item.col === "number" && item.col > 0 ? Math.floor(item.col) : typeof item.column === "number" && item.column > 0 ? Math.floor(item.column) : 1,
1418
+ message: String(item.message || ""),
1419
+ severity: item.severity || "error"
1420
+ };
1421
+ this.items.set(normalized.id, normalized);
1422
+ this.notify();
1423
+ }
1424
+ remove(id) {
1425
+ if (this.items.delete(id)) {
1426
+ this.notify();
1427
+ }
1428
+ }
1429
+ clear(source) {
1430
+ if (source !== void 0 && source !== "") {
1431
+ let changed = false;
1432
+ for (const [id, item] of this.items.entries()) {
1433
+ if (item.source === source) {
1434
+ this.items.delete(id);
1435
+ changed = true;
1436
+ }
1437
+ }
1438
+ if (changed) {
1439
+ this.notify();
1440
+ }
1441
+ } else if (this.items.size > 0) {
1442
+ this.items.clear();
1443
+ this.notify();
1444
+ }
1445
+ }
1446
+ getAll() {
1447
+ return Array.from(this.items.values());
1448
+ }
1449
+ getByFile(file) {
1450
+ const out = [];
1451
+ for (const item of this.items.values()) {
1452
+ if (item.file === file) {
1453
+ out.push(item);
1454
+ }
1455
+ }
1456
+ return out;
1457
+ }
1458
+ subscribe(listener) {
1459
+ this.listeners.add(listener);
1460
+ return () => {
1461
+ this.listeners.delete(listener);
1462
+ };
1463
+ }
1464
+ notify() {
1465
+ if (this.listeners.size === 0) return;
1466
+ const snapshot = this.getAll();
1467
+ for (const listener of this.listeners) {
1468
+ try {
1469
+ listener(snapshot);
1470
+ } catch (err) {
1471
+ console.warn("[code-lab] diagnostics subscriber error:", err);
1472
+ }
1473
+ }
1474
+ }
1475
+ };
1476
+ function createDiagnosticsStore() {
1477
+ return new DiagnosticsStore();
1478
+ }
1479
+ var diagnostics_default = {
1480
+ DiagnosticsStore,
1481
+ createDiagnosticsStore
1482
+ };
1483
+ return __toCommonJS(diagnostics_exports);
1484
+ })();
1485
+
1486
+ var CodeLabScm = (() => {
1487
+ var __defProp = Object.defineProperty;
1488
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1489
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1490
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1491
+ var __export = (target, all) => {
1492
+ for (var name in all)
1493
+ __defProp(target, name, { get: all[name], enumerable: true });
1494
+ };
1495
+ var __copyProps = (to, from, except, desc) => {
1496
+ if (from && typeof from === "object" || typeof from === "function") {
1497
+ for (let key of __getOwnPropNames(from))
1498
+ if (!__hasOwnProp.call(to, key) && key !== except)
1499
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1500
+ }
1501
+ return to;
1502
+ };
1503
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1504
+
1505
+ // src/scm.ts
1506
+ var scm_exports = {};
1507
+ __export(scm_exports, {
1508
+ commitChanges: () => commitChanges,
1509
+ computeGitStatus: () => computeGitStatus,
1510
+ computeShortCommitHash: () => computeShortCommitHash,
1511
+ createGitState: () => createGitState,
1512
+ default: () => scm_default,
1513
+ stageFile: () => stageFile,
1514
+ unstageFile: () => unstageFile
1515
+ });
1516
+ function computeShortCommitHash(input) {
1517
+ let h1 = 3735928559 ^ input.length;
1518
+ let h2 = 1103547991 ^ input.length;
1519
+ for (let i = 0; i < input.length; i++) {
1520
+ const ch = input.charCodeAt(i);
1521
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1522
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1523
+ }
1524
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1525
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1526
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
1527
+ return combined.toString(16).padStart(7, "0").slice(0, 7);
1528
+ }
1529
+ function createGitState(initialFiles = {}, branch = "main") {
1530
+ const headFiles = { ...initialFiles };
1531
+ const initialHash = computeShortCommitHash(JSON.stringify(headFiles) + ":init");
1532
+ return {
1533
+ branch,
1534
+ branches: [branch],
1535
+ headCommit: initialHash,
1536
+ headFiles,
1537
+ staged: /* @__PURE__ */ new Map(),
1538
+ commits: [
1539
+ {
1540
+ hash: initialHash,
1541
+ message: "Initial commit",
1542
+ timestamp: Date.now(),
1543
+ files: { ...headFiles }
1544
+ }
1545
+ ]
1546
+ };
1547
+ }
1548
+ function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1549
+ const state = gitState || createGitState({});
1550
+ const headFiles = state.headFiles || {};
1551
+ const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1552
+ const untracked = [];
1553
+ const modified = [];
1554
+ const deleted = [];
1555
+ const staged = [];
1556
+ for (const [filePath, stagedContent] of currentStaged.entries()) {
1557
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1558
+ if (stagedContent === null) {
1559
+ staged.push({
1560
+ path: filePath,
1561
+ status: "deleted",
1562
+ staged: true,
1563
+ oldContent: headFiles[filePath]
1564
+ });
1565
+ } else {
1566
+ staged.push({
1567
+ path: filePath,
1568
+ status: inHead ? "modified" : "added",
1569
+ staged: true,
1570
+ oldContent: inHead ? headFiles[filePath] : void 0,
1571
+ newContent: stagedContent
1572
+ });
1573
+ }
1574
+ }
1575
+ for (const [filePath, content] of Object.entries(vfsFiles || {})) {
1576
+ if (currentStaged.has(filePath)) {
1577
+ const stagedVal = currentStaged.get(filePath);
1578
+ if (stagedVal !== content) {
1579
+ modified.push({
1580
+ path: filePath,
1581
+ status: "modified",
1582
+ staged: false,
1583
+ oldContent: stagedVal ?? void 0,
1584
+ newContent: content
1585
+ });
1586
+ }
1587
+ } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
1588
+ if (headFiles[filePath] !== content) {
1589
+ modified.push({
1590
+ path: filePath,
1591
+ status: "modified",
1592
+ staged: false,
1593
+ oldContent: headFiles[filePath],
1594
+ newContent: content
1595
+ });
1596
+ }
1597
+ } else {
1598
+ untracked.push({
1599
+ path: filePath,
1600
+ status: "untracked",
1601
+ staged: false,
1602
+ newContent: content
1603
+ });
1604
+ }
1605
+ }
1606
+ for (const filePath of Object.keys(headFiles)) {
1607
+ if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath) && !currentStaged.has(filePath)) {
1608
+ deleted.push({
1609
+ path: filePath,
1610
+ status: "deleted",
1611
+ staged: false,
1612
+ oldContent: headFiles[filePath]
1613
+ });
1614
+ }
1615
+ }
1616
+ const unstaged = [...modified, ...deleted];
1617
+ const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1618
+ return {
1619
+ branch: state.branch || "main",
1620
+ headCommit: state.headCommit || "",
1621
+ untracked,
1622
+ modified,
1623
+ deleted,
1624
+ staged,
1625
+ unstaged,
1626
+ hasChanges: !isClean,
1627
+ isClean
1628
+ };
1629
+ }
1630
+ function stageFile(gitState, relativePath, currentContent) {
1631
+ if (!gitState) return;
1632
+ if (!(gitState.staged instanceof Map)) {
1633
+ gitState.staged = /* @__PURE__ */ new Map();
1634
+ }
1635
+ gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1636
+ }
1637
+ function unstageFile(gitState, relativePath) {
1638
+ if (!gitState || !(gitState.staged instanceof Map)) return;
1639
+ gitState.staged.delete(relativePath);
1640
+ }
1641
+ function commitChanges(gitState, message) {
1642
+ const trimmed = typeof message === "string" ? message.trim() : "";
1643
+ if (!trimmed) {
1644
+ throw new Error("Commit message cannot be empty");
1645
+ }
1646
+ if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1647
+ throw new Error("Nothing to commit (staging area is empty)");
1648
+ }
1649
+ const newHeadFiles = { ...gitState.headFiles || {} };
1650
+ for (const [filePath, content] of gitState.staged.entries()) {
1651
+ if (content === null) {
1652
+ delete newHeadFiles[filePath];
1653
+ } else {
1654
+ newHeadFiles[filePath] = content;
1655
+ }
1656
+ }
1657
+ const timestamp = Date.now();
1658
+ const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1659
+ const commit = {
1660
+ hash,
1661
+ message: trimmed,
1662
+ timestamp,
1663
+ files: newHeadFiles
1664
+ };
1665
+ if (!Array.isArray(gitState.commits)) {
1666
+ gitState.commits = [];
1667
+ }
1668
+ gitState.commits.push(commit);
1669
+ gitState.headCommit = hash;
1670
+ gitState.headFiles = newHeadFiles;
1671
+ gitState.staged.clear();
1672
+ return hash;
1673
+ }
1674
+ var scm_default = {
1675
+ createGitState,
1676
+ computeGitStatus,
1677
+ stageFile,
1678
+ unstageFile,
1679
+ commitChanges,
1680
+ computeShortCommitHash
1681
+ };
1682
+ return __toCommonJS(scm_exports);
1683
+ })();
1684
+
1685
+ _root.CodeLabZip = CodeLabZip;
1686
+ _root.CodeLabStorage = CodeLabStorage;
1687
+ _root.CodeLabSearch = CodeLabSearch;
1688
+ _root.CodeLabDiagnostics = CodeLabDiagnostics;
1689
+ _root.CodeLabScm = CodeLabScm;
1690
+
19
1691
  // --- Module 1: Runtime Engine ---
20
1692
  (function () {
1693
+ // @ts-nocheck
21
1694
  'use strict';
22
1695
  if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined') {
23
1696
  globalThis.Bun = { version: '1.1.20' };
@@ -39,6 +1712,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
39
1712
  */
40
1713
 
41
1714
  function __initVirtualRuntime(rootScope) {
1715
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
1716
+ ? rootScope.CodeLabLogger.createLogger()
1717
+ : {
1718
+ debug() {},
1719
+ info() {},
1720
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
1721
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
1722
+ };
42
1723
  // =========================================================================
43
1724
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
44
1725
  // =========================================================================
@@ -1598,7 +3279,7 @@ function __initVirtualRuntime(rootScope) {
1598
3279
  },
1599
3280
  final(cb) {
1600
3281
  if (fd !== null) {
1601
- try { fsShim.closeSync(fd); } catch (_) {}
3282
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1602
3283
  fd = null;
1603
3284
  }
1604
3285
  cb(null);
@@ -2118,7 +3799,9 @@ function __initVirtualRuntime(rootScope) {
2118
3799
  return pathname + search + hash;
2119
3800
  }
2120
3801
  return resolvedUrl.href;
2121
- } catch (_) {}
3802
+ } catch (err) {
3803
+ _runtimeLogger.debug('url.resolve fallback used', err);
3804
+ }
2122
3805
  }
2123
3806
  if (toStr.startsWith('/')) {
2124
3807
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2557,10 +4240,10 @@ function __initVirtualRuntime(rootScope) {
2557
4240
  for (const [port, entry] of Array.from(table.entries())) {
2558
4241
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2559
4242
  if (entry.server && typeof entry.server.close === 'function') {
2560
- try { entry.server.close(); } catch (_) {}
4243
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2561
4244
  }
2562
4245
  if (typeof entry.stop === 'function') {
2563
- try { entry.stop(); } catch (_) {}
4246
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2564
4247
  }
2565
4248
  // Avoid a double 'close' emission when entry.server.close() already
2566
4249
  // unregistered the port through unregisterServer().
@@ -3197,7 +4880,7 @@ function __initVirtualRuntime(rootScope) {
3197
4880
  },
3198
4881
  closeAllServers() {
3199
4882
  for (const s of Array.from(activeServers.values())) {
3200
- try { s.close(); } catch (_) {}
4883
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3201
4884
  }
3202
4885
  activeServers.clear();
3203
4886
  }
@@ -4023,7 +5706,7 @@ function __initVirtualRuntime(rootScope) {
4023
5706
 
4024
5707
  function closeAllServers() {
4025
5708
  for (const srv of servers.values()) {
4026
- try { srv.close(); } catch (_) {}
5709
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4027
5710
  }
4028
5711
  servers.clear();
4029
5712
  }
@@ -5103,7 +6786,9 @@ function __initVirtualRuntime(rootScope) {
5103
6786
  try {
5104
6787
  const pkgJson = JSON.parse(content);
5105
6788
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5106
- } catch (_) {}
6789
+ } catch (err) {
6790
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
6791
+ }
5107
6792
  continue;
5108
6793
  }
5109
6794
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5132,7 +6817,9 @@ function __initVirtualRuntime(rootScope) {
5132
6817
  const meta = await res.json();
5133
6818
  deps = Object.keys((meta && meta.dependencies) || {});
5134
6819
  }
5135
- } catch (_) {}
6820
+ } catch (err) {
6821
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
6822
+ }
5136
6823
  _npmMetadataCache.set(pkg, deps);
5137
6824
  }));
5138
6825
  for (const pkg of pending) {
@@ -5150,7 +6837,7 @@ function __initVirtualRuntime(rootScope) {
5150
6837
  continue;
5151
6838
  }
5152
6839
  if (typeof onProgress === 'function') {
5153
- try { onProgress(pkg); } catch (_) {}
6840
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5154
6841
  }
5155
6842
  if (typeof fetch === 'function') {
5156
6843
  try {
@@ -5160,7 +6847,9 @@ function __initVirtualRuntime(rootScope) {
5160
6847
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5161
6848
  loaded[pkg] = text;
5162
6849
  }
5163
- } catch (_) {}
6850
+ } catch (err) {
6851
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
6852
+ }
5164
6853
  }
5165
6854
  }
5166
6855
  return loaded;
@@ -5352,7 +7041,9 @@ function __initVirtualRuntime(rootScope) {
5352
7041
  const dir = VirtualPath.dirname(abs);
5353
7042
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5354
7043
  vfs.writeFileSync(abs, content);
5355
- } catch (_) {}
7044
+ } catch (err) {
7045
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
7046
+ }
5356
7047
  }
5357
7048
  }
5358
7049
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5797,7 +7488,7 @@ function __initVirtualRuntime(rootScope) {
5797
7488
  exitCode = Number(code) || 0;
5798
7489
  if (!hasExited) {
5799
7490
  hasExited = true;
5800
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7491
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5801
7492
  }
5802
7493
  if (syncExecDepth > 0) {
5803
7494
  throw new ProcessExitSignal(exitCode);
@@ -5830,8 +7521,8 @@ function __initVirtualRuntime(rootScope) {
5830
7521
  resourceTracker.inFlightHttp.clear();
5831
7522
 
5832
7523
  if (!isBackground) {
5833
- try { vhttp.closeAllServers(); } catch (_) {}
5834
- try { vnet.closeAllServers(); } catch (_) {}
7524
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
7525
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5835
7526
  }
5836
7527
  };
5837
7528
 
@@ -5941,10 +7632,10 @@ function __initVirtualRuntime(rootScope) {
5941
7632
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5942
7633
  } finally {
5943
7634
  for (const ae of hooksSnapshot.afterEachList) {
5944
- try { await ae(); } catch (_) {}
7635
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5945
7636
  }
5946
7637
  for (const af of hooksSnapshot.afterToRun) {
5947
- try { await af(); } catch (_) {}
7638
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5948
7639
  }
5949
7640
  hooksSnapshot.afterToRun.length = 0;
5950
7641
  }
@@ -5992,7 +7683,7 @@ function __initVirtualRuntime(rootScope) {
5992
7683
  const afters = [...suiteCtx.afterCallbacks];
5993
7684
  const cleanupTask = nodeTestChain.then(async () => {
5994
7685
  for (const af of afters) {
5995
- try { await af(); } catch (_) {}
7686
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5996
7687
  }
5997
7688
  });
5998
7689
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6038,7 +7729,7 @@ function __initVirtualRuntime(rootScope) {
6038
7729
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6039
7730
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6040
7731
  };
6041
- try { obs._cb(list, obs); } catch (_) {}
7732
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6042
7733
  }
6043
7734
  }
6044
7735
  }
@@ -6143,7 +7834,7 @@ function __initVirtualRuntime(rootScope) {
6143
7834
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6144
7835
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6145
7836
  };
6146
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
7837
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6147
7838
  }
6148
7839
  }
6149
7840
  }
@@ -7414,7 +9105,9 @@ function __initVirtualRuntime(rootScope) {
7414
9105
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7415
9106
  if (resolvedEntry) return resolvedEntry;
7416
9107
  }
7417
- } catch (_) {}
9108
+ } catch (err) {
9109
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
9110
+ }
7418
9111
  }
7419
9112
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7420
9113
  for (const idx of indexCandidates) {
@@ -7484,7 +9177,9 @@ function __initVirtualRuntime(rootScope) {
7484
9177
  if (found) return found;
7485
9178
  }
7486
9179
  }
7487
- } catch (_) {}
9180
+ } catch (err) {
9181
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
9182
+ }
7488
9183
  }
7489
9184
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7490
9185
  if (foundSub) return foundSub;
@@ -7526,7 +9221,9 @@ function __initVirtualRuntime(rootScope) {
7526
9221
  if (isLocal && activePortTable) {
7527
9222
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7528
9223
  }
7529
- } catch (_) {}
9224
+ } catch (err) {
9225
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
9226
+ }
7530
9227
 
7531
9228
  if (typeof globalThis.fetch === 'function') {
7532
9229
  return await globalThis.fetch(urlOrReq, init);
@@ -7693,7 +9390,9 @@ function __initVirtualRuntime(rootScope) {
7693
9390
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7694
9391
  try {
7695
9392
  return new AsyncFunction(...argNames, body);
7696
- } catch (_) {}
9393
+ } catch (asyncErr) {
9394
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
9395
+ }
7697
9396
  }
7698
9397
  if (
7699
9398
  err &&
@@ -7747,7 +9446,9 @@ function __initVirtualRuntime(rootScope) {
7747
9446
  if (signal && onAbort) {
7748
9447
  try {
7749
9448
  signal.removeEventListener('abort', onAbort);
7750
- } catch (_) {}
9449
+ } catch (err) {
9450
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
9451
+ }
7751
9452
  }
7752
9453
  };
7753
9454
 
@@ -7906,11 +9607,11 @@ function __initVirtualRuntime(rootScope) {
7906
9607
  }
7907
9608
  } finally {
7908
9609
  if (signal && signalListener) {
7909
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
9610
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7910
9611
  }
7911
9612
  if (!hasExited) {
7912
9613
  hasExited = true;
7913
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
9614
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7914
9615
  }
7915
9616
  for (const rawId of resourceTracker.allTimers) {
7916
9617
  clearTimeout(rawId);
@@ -8018,7 +9719,16 @@ function createWorkerRuntimeSource() {
8018
9719
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8019
9720
  }
8020
9721
 
8021
- const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
9722
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
9723
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
9724
+ ? _hostScope.CodeLabLogger.createLogger()
9725
+ : {
9726
+ debug() {},
9727
+ info() {},
9728
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
9729
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
9730
+ };
9731
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8022
9732
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8023
9733
 
8024
9734
  let _cachedWorkerUrl = null;
@@ -8042,7 +9752,7 @@ function _ensureWarmWorker() {
8042
9752
 
8043
9753
  function _destroyWarmWorker() {
8044
9754
  if (_warmWorker) {
8045
- try { _warmWorker.terminate(); } catch (_) {}
9755
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8046
9756
  _warmWorker = null;
8047
9757
  }
8048
9758
  _warmWorkerBusy = false;
@@ -8097,7 +9807,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8097
9807
 
8098
9808
  function releaseWorker(terminateWorker) {
8099
9809
  if (options.signal && abortListener) {
8100
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
9810
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8101
9811
  abortListener = null;
8102
9812
  }
8103
9813
  _activeWorkerJobs.delete(requestId);
@@ -8112,7 +9822,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8112
9822
  }
8113
9823
  }
8114
9824
  } else {
8115
- try { worker.terminate(); } catch (_) {}
9825
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8116
9826
  }
8117
9827
  }
8118
9828
 
@@ -8248,10 +9958,12 @@ if (typeof module !== 'undefined' && module.exports) {
8248
9958
  }
8249
9959
 
8250
9960
 
9961
+
8251
9962
  })();
8252
9963
 
8253
9964
  // --- Module 2: POSIX Shell & Coreutils ---
8254
9965
  (function () {
9966
+ // @ts-nocheck
8255
9967
  /**
8256
9968
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
8257
9969
  *
@@ -8298,12 +10010,23 @@ if (typeof module !== 'undefined' && module.exports) {
8298
10010
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
8299
10011
  'use strict';
8300
10012
 
10013
+ const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
10014
+ ? root.CodeLabLogger.createLogger()
10015
+ : {
10016
+ debug() {},
10017
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
10018
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
10019
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
10020
+ };
10021
+
8301
10022
  function getRuntimeModule() {
8302
10023
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
8303
10024
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
8304
10025
  try {
8305
10026
  if (typeof require !== 'undefined') return require('./runtime.js');
8306
- } catch (_) {}
10027
+ } catch (err) {
10028
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
10029
+ }
8307
10030
  return null;
8308
10031
  }
8309
10032
 
@@ -8895,7 +10618,9 @@ if (typeof module !== 'undefined' && module.exports) {
8895
10618
  if (typeof vfs.statSync === 'function') {
8896
10619
  isDir = vfs.statSync(full).isDirectory();
8897
10620
  }
8898
- } catch (_) {}
10621
+ } catch (err) {
10622
+ _shellLogger.debug('Glob statSync failed.', full, err);
10623
+ }
8899
10624
 
8900
10625
  if (isDir) {
8901
10626
  traverse(full, rel);
@@ -10217,7 +11942,9 @@ if (typeof module !== 'undefined' && module.exports) {
10217
11942
  : name;
10218
11943
  try {
10219
11944
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
10220
- } catch (_) {}
11945
+ } catch (err) {
11946
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
11947
+ }
10221
11948
  }
10222
11949
  }
10223
11950
  }
@@ -10239,7 +11966,7 @@ if (typeof module !== 'undefined' && module.exports) {
10239
11966
  return 10 + depth * 0.1;
10240
11967
  }
10241
11968
 
10242
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
11969
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
10243
11970
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10244
11971
  if (onProgress) {
10245
11972
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -10321,8 +12048,9 @@ if (typeof module !== 'undefined' && module.exports) {
10321
12048
  }
10322
12049
  }
10323
12050
  }
10324
- } catch (_) {
12051
+ } catch (err) {
10325
12052
  // Network or rate limit error on api.github.com; proceed to Strategy B
12053
+ _shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
10326
12054
  }
10327
12055
 
10328
12056
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -10349,7 +12077,9 @@ if (typeof module !== 'undefined' && module.exports) {
10349
12077
  }
10350
12078
  }
10351
12079
  }
10352
- } catch (_) {}
12080
+ } catch (err) {
12081
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
12082
+ }
10353
12083
  }
10354
12084
 
10355
12085
  if (repoNotFound || !rawTreeEntries) {
@@ -10497,7 +12227,9 @@ if (typeof module !== 'undefined' && module.exports) {
10497
12227
  }));
10498
12228
  }
10499
12229
  }
10500
- } catch (_) {}
12230
+ } catch (err) {
12231
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
12232
+ }
10501
12233
 
10502
12234
  if (commits.length === 0) {
10503
12235
  commits = [
@@ -10529,6 +12261,23 @@ if (typeof module !== 'undefined' && module.exports) {
10529
12261
  };
10530
12262
  }
10531
12263
 
12264
+ // Public wrapper: guarantee an `error` progress event when the clone fails
12265
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
12266
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
12267
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
12268
+ try {
12269
+ return await _cloneGitHubRepository(repoInput, vfs, options);
12270
+ } catch (err) {
12271
+ if (onProgress) {
12272
+ onProgress({
12273
+ phase: 'error',
12274
+ message: err && err.message ? err.message : String(err)
12275
+ });
12276
+ }
12277
+ throw err;
12278
+ }
12279
+ }
12280
+
10532
12281
  // =========================================================================
10533
12282
  // Package Management Helpers (npm / bun virtual modules & scripts)
10534
12283
  // =========================================================================
@@ -10546,7 +12295,9 @@ if (typeof module !== 'undefined' && module.exports) {
10546
12295
  try {
10547
12296
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
10548
12297
  return { path: p, data: parsed };
10549
- } catch (_) {}
12298
+ } catch (err) {
12299
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
12300
+ }
10550
12301
  }
10551
12302
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
10552
12303
  }
@@ -10587,13 +12338,20 @@ if (typeof module !== 'undefined' && module.exports) {
10587
12338
  vfs.rmdirSync(dirPath);
10588
12339
  }
10589
12340
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
10590
- } catch (_) {}
12341
+ } catch (err) {
12342
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
12343
+ }
10591
12344
  }
10592
12345
 
10593
12346
  // ---------------------------------------------------------------------------
10594
12347
  // Real npm package installation via the jsDelivr CDN
10595
12348
  // ---------------------------------------------------------------------------
10596
12349
  const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
12350
+ const CDN_NPM_BASES = [
12351
+ 'https://cdn.jsdelivr.net/npm',
12352
+ 'https://unpkg.com',
12353
+ 'https://esm.sh'
12354
+ ];
10597
12355
 
10598
12356
  // Minimal offline registry, used only when the CDN is unreachable so common
10599
12357
  // demos still resolve without network access.
@@ -10739,16 +12497,23 @@ if (typeof module !== 'undefined' && module.exports) {
10739
12497
  }
10740
12498
 
10741
12499
  async function resolvePackageMetadata(fetchImpl, name, range) {
10742
- const urls = range
10743
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10744
- : [`${CDN_NPM_BASE}/${name}/package.json`];
10745
- for (const url of urls) {
10746
- const text = await fetchTextFromCdn(fetchImpl, url);
10747
- if (!text) continue;
10748
- try {
10749
- const parsed = JSON.parse(text);
10750
- if (parsed && parsed.version) return parsed;
10751
- } catch (_) {}
12500
+ for (const base of CDN_NPM_BASES) {
12501
+ const urls = range
12502
+ ? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
12503
+ : [`${base}/${name}/package.json`];
12504
+ for (const url of urls) {
12505
+ const text = await fetchTextFromCdn(fetchImpl, url);
12506
+ if (!text) continue;
12507
+ try {
12508
+ const parsed = JSON.parse(text);
12509
+ if (parsed && parsed.version) {
12510
+ parsed._resolvedCdnBase = base;
12511
+ return parsed;
12512
+ }
12513
+ } catch (err) {
12514
+ _shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
12515
+ }
12516
+ }
10752
12517
  }
10753
12518
  return null;
10754
12519
  }
@@ -10766,6 +12531,7 @@ if (typeof module !== 'undefined' && module.exports) {
10766
12531
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10767
12532
  }
10768
12533
 
12534
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
10769
12535
  const version = meta.version;
10770
12536
  const key = `${name}@${version}`;
10771
12537
  if (seen.has(key)) {
@@ -10813,7 +12579,7 @@ if (typeof module !== 'undefined' && module.exports) {
10813
12579
  frontier = [];
10814
12580
  if (batch.length === 0) break;
10815
12581
  const texts = await Promise.all(
10816
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
12582
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
10817
12583
  );
10818
12584
  for (let idx = 0; idx < batch.length; idx++) {
10819
12585
  const rel = batch[idx];
@@ -10837,7 +12603,7 @@ if (typeof module !== 'undefined' && module.exports) {
10837
12603
  }
10838
12604
  // The declared entry may be missing on the CDN; fall back to index.js.
10839
12605
  if (!files.some(f => f.rel === entry)) {
10840
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
12606
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
10841
12607
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10842
12608
  }
10843
12609
 
@@ -10884,7 +12650,9 @@ if (typeof module !== 'undefined' && module.exports) {
10884
12650
  // directory target would otherwise raise EISDIR).
10885
12651
  try {
10886
12652
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10887
- } catch (_) {}
12653
+ } catch (err) {
12654
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
12655
+ }
10888
12656
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10889
12657
  ctx.vfs.writeFileSync(full, f.content);
10890
12658
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10962,6 +12730,32 @@ if (typeof module !== 'undefined' && module.exports) {
10962
12730
  pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10963
12731
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10964
12732
 
12733
+ // Also maintain package-lock.json in the same directory for deterministic lockfile verification
12734
+ try {
12735
+ const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
12736
+ let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
12737
+ if (ctx.vfs.existsSync(lockPath)) {
12738
+ const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
12739
+ const parsedLock = JSON.parse(rawLock);
12740
+ if (parsedLock && typeof parsedLock === 'object') {
12741
+ lockData = parsedLock;
12742
+ if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
12743
+ }
12744
+ }
12745
+ for (const inst of installed) {
12746
+ if (inst && inst.name) {
12747
+ lockData.packages[`node_modules/${inst.name}`] = {
12748
+ version: inst.version || '1.0.0',
12749
+ resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
12750
+ };
12751
+ }
12752
+ }
12753
+ ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
12754
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
12755
+ } catch (err) {
12756
+ _shellLogger.debug('Could not write package-lock.json during installPackage.', err);
12757
+ }
12758
+
10965
12759
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10966
12760
  }
10967
12761
 
@@ -11159,7 +12953,9 @@ if (typeof module !== 'undefined' && module.exports) {
11159
12953
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
11160
12954
  if (parsed && parsed.version) return parsed.version;
11161
12955
  }
11162
- } catch (_) {}
12956
+ } catch (err) {
12957
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
12958
+ }
11163
12959
  try {
11164
12960
  for (const dir of [rootDir, '/workspace']) {
11165
12961
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -11168,7 +12964,9 @@ if (typeof module !== 'undefined' && module.exports) {
11168
12964
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
11169
12965
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
11170
12966
  }
11171
- } catch (_) {}
12967
+ } catch (err) {
12968
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
12969
+ }
11172
12970
  return 'latest';
11173
12971
  }
11174
12972
 
@@ -11206,7 +13004,7 @@ if (typeof module !== 'undefined' && module.exports) {
11206
13004
  if (dirFlag) {
11207
13005
  walk(full, depth + 1);
11208
13006
  } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
11209
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
13007
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
11210
13008
  }
11211
13009
  }
11212
13010
  };
@@ -11253,7 +13051,7 @@ if (typeof module !== 'undefined' && module.exports) {
11253
13051
 
11254
13052
  const handler = async (request) => {
11255
13053
  let pathname = '/';
11256
- try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
13054
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
11257
13055
  const rel = pathname.replace(/^\/+/, '');
11258
13056
  let target = PosixPath.join(rootDir, rel);
11259
13057
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -11292,7 +13090,9 @@ if (typeof module !== 'undefined' && module.exports) {
11292
13090
  if (rm && typeof rm.transpileForBrowser === 'function') {
11293
13091
  body = rm.transpileForBrowser(body, target);
11294
13092
  }
11295
- } catch (_) {}
13093
+ } catch (err) {
13094
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
13095
+ }
11296
13096
  }
11297
13097
 
11298
13098
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -11300,7 +13100,7 @@ if (typeof module !== 'undefined' && module.exports) {
11300
13100
 
11301
13101
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
11302
13102
  return portTable.registerServer(port, {
11303
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
13103
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
11304
13104
  fetch: handler,
11305
13105
  name: 'code-lab-serve',
11306
13106
  pid,
@@ -11413,7 +13213,9 @@ if (typeof module !== 'undefined' && module.exports) {
11413
13213
  let isDir = false;
11414
13214
  try {
11415
13215
  isDir = ctx.vfs.statSync(resolved).isDirectory();
11416
- } catch (_) {}
13216
+ } catch (err) {
13217
+ _shellLogger.debug('cd statSync failed.', resolved, err);
13218
+ }
11417
13219
 
11418
13220
  if (!isDir) {
11419
13221
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -11513,7 +13315,9 @@ if (typeof module !== 'undefined' && module.exports) {
11513
13315
  isDirectory = st.isDirectory();
11514
13316
  size = st.size;
11515
13317
  mtimeMs = st.mtimeMs || Date.now();
11516
- } catch (_) {}
13318
+ } catch (err) {
13319
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
13320
+ }
11517
13321
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
11518
13322
  });
11519
13323
 
@@ -11933,7 +13737,9 @@ if (typeof module !== 'undefined' && module.exports) {
11933
13737
  if (st.isDirectory()) walk(full);
11934
13738
  else targets.push(full);
11935
13739
  }
11936
- } catch (_) {}
13740
+ } catch (err) {
13741
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
13742
+ }
11937
13743
  }
11938
13744
  if (ctx.vfs.existsSync(absRoot)) {
11939
13745
  const st = ctx.vfs.statSync(absRoot);
@@ -12057,7 +13863,9 @@ if (typeof module !== 'undefined' && module.exports) {
12057
13863
  let isDir = false;
12058
13864
  try {
12059
13865
  isDir = ctx.vfs.statSync(full).isDirectory();
12060
- } catch (_) {}
13866
+ } catch (err) {
13867
+ _shellLogger.debug('find statSync skipped.', full, err);
13868
+ }
12061
13869
 
12062
13870
  const relPath = root === '.'
12063
13871
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -12076,7 +13884,7 @@ if (typeof module !== 'undefined' && module.exports) {
12076
13884
  // Root itself check
12077
13885
  if (ctx.vfs.existsSync(absRoot)) {
12078
13886
  let isDir = false;
12079
- try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (_) {}
13887
+ try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
12080
13888
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
12081
13889
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
12082
13890
  results.push(root);
@@ -12988,7 +14796,7 @@ if (typeof module !== 'undefined' && module.exports) {
12988
14796
  const isLast = i === entries.length - 1;
12989
14797
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
12990
14798
  let isDir = false;
12991
- try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (_) {}
14799
+ try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
12992
14800
 
12993
14801
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
12994
14802
 
@@ -13216,10 +15024,10 @@ if (typeof module !== 'undefined' && module.exports) {
13216
15024
  for (const s of ctx.shell.portTable.listServers()) {
13217
15025
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
13218
15026
  if (s.server && typeof s.server.close === 'function') {
13219
- try { s.server.close(); } catch (_) {}
15027
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
13220
15028
  }
13221
15029
  if (typeof s.stop === 'function') {
13222
- try { s.stop(); } catch (_) {}
15030
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
13223
15031
  }
13224
15032
  ctx.shell.portTable.unregisterServer(s.port);
13225
15033
  killedPort = true;
@@ -15510,10 +17318,12 @@ if (typeof module !== 'undefined' && module.exports) {
15510
17318
  };
15511
17319
  });
15512
17320
 
17321
+
15513
17322
  })();
15514
17323
 
15515
17324
  // --- Module 3: PTY Terminal Engine ---
15516
17325
  (function () {
17326
+ // @ts-nocheck
15517
17327
  /**
15518
17328
  * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
15519
17329
  *
@@ -15548,6 +17358,16 @@ if (typeof module !== 'undefined' && module.exports) {
15548
17358
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
15549
17359
  'use strict';
15550
17360
 
17361
+ const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
17362
+ const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
17363
+ ? _termRoot.CodeLabLogger.createLogger()
17364
+ : {
17365
+ debug() {},
17366
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
17367
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
17368
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
17369
+ };
17370
+
15551
17371
  const ANSI_CODE_MAP = {
15552
17372
  1: 'cl-ansi-bold',
15553
17373
  2: 'cl-ansi-dim',
@@ -16088,7 +17908,7 @@ if (typeof module !== 'undefined' && module.exports) {
16088
17908
  if (!this.container || typeof this.container.querySelector !== 'function') return;
16089
17909
  const input = this.container.querySelector('#cl-repl-input');
16090
17910
  if (input && typeof input.focus === 'function') {
16091
- try { input.focus(); } catch (_) {}
17911
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
16092
17912
  }
16093
17913
  }
16094
17914
 
@@ -16112,9 +17932,9 @@ if (typeof module !== 'undefined' && module.exports) {
16112
17932
  }
16113
17933
  for (const entry of this._listeners) {
16114
17934
  if (typeof entry === 'function') {
16115
- try { entry(); } catch (_) {}
17935
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
16116
17936
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
16117
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
17937
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
16118
17938
  }
16119
17939
  }
16120
17940
  this._listeners = [];
@@ -16183,7 +18003,9 @@ if (typeof module !== 'undefined' && module.exports) {
16183
18003
  try {
16184
18004
  const res = this.onKey(e);
16185
18005
  if (res === false) return;
16186
- } catch (_) {}
18006
+ } catch (err) {
18007
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
18008
+ }
16187
18009
  }
16188
18010
 
16189
18011
  const key = e.key;
@@ -16336,7 +18158,7 @@ if (typeof module !== 'undefined' && module.exports) {
16336
18158
  this.replMode = false;
16337
18159
  }
16338
18160
  if (this.onInterrupt) {
16339
- try { this.onInterrupt(); } catch (_) {}
18161
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
16340
18162
  }
16341
18163
  this.render();
16342
18164
  return;
@@ -16537,7 +18359,9 @@ if (typeof module !== 'undefined' && module.exports) {
16537
18359
  if (typeof nextInput.setSelectionRange === 'function') {
16538
18360
  nextInput.setSelectionRange(this.cursor, this.cursor);
16539
18361
  }
16540
- } catch (_) {}
18362
+ } catch (err) {
18363
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
18364
+ }
16541
18365
  }
16542
18366
  }
16543
18367
  }
@@ -16561,10 +18385,12 @@ if (typeof module !== 'undefined' && module.exports) {
16561
18385
  };
16562
18386
  });
16563
18387
 
18388
+
16564
18389
  })();
16565
18390
 
16566
18391
  // --- Module 4: IDE Workbench & Web Component ---
16567
18392
  (function () {
18393
+ // @ts-nocheck
16568
18394
  /* ═══════════════════════════════════════════════════════════════════════════
16569
18395
  @innovatorved/code-lab — Interactive Monaco IDE Workbench & Guided Lab UI
16570
18396
  Supports <code-lab> Custom Element + window.CodeLab.mount() API
@@ -16573,13 +18399,26 @@ if (typeof module !== 'undefined' && module.exports) {
16573
18399
  (function (root) {
16574
18400
  'use strict';
16575
18401
 
16576
- let terminalModule = null;
16577
- let shellModule = null;
16578
- let runtimeModule = null;
18402
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
18403
+ (root && root.CodeLabLogger) ||
18404
+ null;
18405
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
18406
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
18407
+ : () => {};
18408
+
18409
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18410
+ let shellModule = (root && root.CodeLabShell) || null;
18411
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
16579
18412
  if (typeof require === 'function') {
16580
- try { terminalModule = require('./terminal.js'); } catch (_) {}
16581
- try { shellModule = require('./shell.js'); } catch (_) {}
16582
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
18413
+ if (!terminalModule) {
18414
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
18415
+ }
18416
+ if (!shellModule) {
18417
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
18418
+ }
18419
+ if (!runtimeModule) {
18420
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
18421
+ }
16583
18422
  }
16584
18423
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
16585
18424
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -16608,6 +18447,10 @@ if (typeof module !== 'undefined' && module.exports) {
16608
18447
  const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
16609
18448
  const STORAGE_PREFIX = 'sd-codelab-v1:';
16610
18449
 
18450
+ // The bundler rewrites this literal from package.json at build time. Keeping
18451
+ // the fallback in sync lets tests require src/workbench.js directly.
18452
+ const CODELAB_VERSION = '0.1.8';
18453
+
16611
18454
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16612
18455
  const NODE_AMBIENT_DTS = `
16613
18456
  declare var require: (id: string) => any;
@@ -16934,7 +18777,14 @@ declare module 'bun:sqlite' {
16934
18777
  }
16935
18778
  `;
16936
18779
 
18780
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
18781
+ (root && root.CodeLabHtml) ||
18782
+ null;
18783
+
16937
18784
  function escapeHtml(str) {
18785
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
18786
+ return _sharedHtmlMod.escapeHtml(str);
18787
+ }
16938
18788
  if (str == null) return '';
16939
18789
  return String(str)
16940
18790
  .replace(/&/g, '&amp;')
@@ -16944,6 +18794,45 @@ declare module 'bun:sqlite' {
16944
18794
  .replace(/'/g, '&#39;');
16945
18795
  }
16946
18796
 
18797
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
18798
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
18799
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
18800
+ let out = strings[0] || '';
18801
+ for (let i = 0; i < values.length; i++) {
18802
+ const val = values[i];
18803
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
18804
+ out += strings[i + 1] || '';
18805
+ }
18806
+ return raw(out);
18807
+ });
18808
+
18809
+ // Schemes that may appear in a rendered href. Everything else
18810
+ // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
18811
+ const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
18812
+
18813
+ function sanitizeUrl(raw) {
18814
+ if (raw === null || raw === undefined) return '#';
18815
+ const trimmed = String(raw).trim();
18816
+ if (!trimmed) return '#';
18817
+
18818
+ // Browsers ignore C0 controls and zero-width characters while resolving a
18819
+ // scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
18820
+ // them before deciding what the scheme is, but return the original value
18821
+ // when it is safe.
18822
+ const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
18823
+ const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
18824
+
18825
+ if (!schemeMatch) {
18826
+ // No scheme: a fragment, an absolute path, or a relative path.
18827
+ // Backslashes are treated as slashes by the URL parser and can turn a
18828
+ // "relative" URL into a protocol-relative one, so reject those.
18829
+ if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
18830
+ return trimmed;
18831
+ }
18832
+
18833
+ return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
18834
+ }
18835
+
16947
18836
  function formatErrorText(err) {
16948
18837
  if (!err) return '';
16949
18838
  if (typeof err === 'string') return err;
@@ -17135,16 +19024,11 @@ declare module 'bun:sqlite' {
17135
19024
  if (!str) return '';
17136
19025
  let text = String(str);
17137
19026
 
17138
- // Markdown Links: [label](url "title") or [label](url)
17139
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17140
- const cleanUrl = url.trim();
17141
- 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>`;
19027
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
19028
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
19029
+ const cleanUrl = sanitizeUrl(url);
19030
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
19031
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
17148
19032
  });
17149
19033
 
17150
19034
  // Strikethrough: ~~del~~
@@ -17339,8 +19223,9 @@ declare module 'bun:sqlite' {
17339
19223
  // Normalize CRLF to LF
17340
19224
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
17341
19225
 
17342
- // Prevent raw custom elements from executing within markdown previews
17343
- text = text.replace(/<\/?code-lab(\s[^>]*)?>/gi, (m) => escapeHtml(m));
19226
+ // NUL delimits internal placeholders. Strip author-supplied NULs so
19227
+ // markdown cannot forge a code-block or autolink placeholder.
19228
+ text = text.replace(/\u0000/g, '');
17344
19229
 
17345
19230
  // Phase 1: Fenced Code Block Extraction
17346
19231
  const codeBlocks = [];
@@ -17363,6 +19248,25 @@ declare module 'bun:sqlite' {
17363
19248
  return `\x00INLINECODE_${idx}\x00`;
17364
19249
  });
17365
19250
 
19251
+ // Phase 2b: Autolinks are the only inline construct that uses angle
19252
+ // brackets. Extract them before raw HTML is neutralized, then restore the
19253
+ // anchors in Phase 7.
19254
+ const autolinks = [];
19255
+ text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
19256
+ const idx = autolinks.length;
19257
+ const safe = sanitizeUrl(url);
19258
+ autolinks.push(
19259
+ `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
19260
+ );
19261
+ return `\x00AUTOLINK_${idx}\x00`;
19262
+ });
19263
+
19264
+ // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
19265
+ // escaping that one character turns any author-supplied markup into text
19266
+ // without disturbing `>` blockquote syntax. From here on, every real tag
19267
+ // in the output is generated by this renderer.
19268
+ text = text.replace(/</g, '&lt;');
19269
+
17366
19270
  // Phase 3: GitHub Callout Alerts & Blockquotes
17367
19271
  const calloutBlocks = [];
17368
19272
  text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
@@ -17440,7 +19344,8 @@ declare module 'bun:sqlite' {
17440
19344
  .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
17441
19345
  .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
17442
19346
  .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
17443
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '');
19347
+ .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
19348
+ .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
17444
19349
 
17445
19350
  return finalHtml;
17446
19351
  }
@@ -17647,27 +19552,124 @@ declare module 'bun:sqlite' {
17647
19552
  x: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
17648
19553
  };
17649
19554
 
17650
- let _workbenchInstanceCounter = 0;
17651
- const _fallbackStorage = new Map();
19555
+ let _workbenchInstanceCounter = 0;
19556
+ const _fallbackStorage = new Map();
19557
+
19558
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
19559
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
19560
+ // there is exactly one policy implementation shared by both sides.
19561
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
19562
+ (root && root.CodeLabCsp) ||
19563
+ null;
19564
+
19565
+ function normalizePreviewCspOption(raw) {
19566
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
19567
+ return PreviewCsp.normalizePreviewCspConfig(raw);
19568
+ }
19569
+ return { mode: 'balanced', allow: {} };
19570
+ }
19571
+
19572
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
19573
+ // that ships, using it would silently *pretend* to isolate previews while the
19574
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
19575
+ const PREVIEW_RELAY_AVAILABLE = false;
19576
+
19577
+ function normalizePreviewOrigin(raw) {
19578
+ if (raw === null || raw === undefined || raw === '') return null;
19579
+ try {
19580
+ const parsed = new URL(String(raw));
19581
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
19582
+ return parsed.origin;
19583
+ } catch (_) {
19584
+ return null;
19585
+ }
19586
+ }
19587
+
19588
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
19589
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
19590
+ constructor(code, message, options = {}) {
19591
+ super(message);
19592
+ this.name = 'CodeLabError';
19593
+ this.code = code || 'E_CODELAB';
19594
+ this.module = options.module || 'workbench';
19595
+ this.context = options.context || {};
19596
+ if (options.cause !== undefined) this.cause = options.cause;
19597
+ }
19598
+ };
19599
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
19600
+
19601
+ // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
19602
+ // into their own telemetry; `options.debug` enables verbose output. Errors
19603
+ // are never silently discarded.
19604
+ function createLogger(options = {}) {
19605
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
19606
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
19607
+ }
19608
+ const sink = options.logger;
19609
+ const debugEnabled = options.debug === true;
19610
+
19611
+ const write = (level, args) => {
19612
+ if (level === 'debug' && !debugEnabled) return;
19613
+ if (sink && typeof sink[level] === 'function') {
19614
+ try {
19615
+ sink[level](...args);
19616
+ return;
19617
+ } catch (sinkErr) {
19618
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
19619
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
19620
+ }
19621
+ }
19622
+ const fn = typeof console !== 'undefined' ? console[level] : null;
19623
+ if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
19624
+ };
19625
+
19626
+ return {
19627
+ debug: (...args) => write('debug', args),
19628
+ info: (...args) => write('info', args),
19629
+ warn: (...args) => write('warn', args),
19630
+ error: (...args) => write('error', args)
19631
+ };
19632
+ }
19633
+
19634
+ const DEFAULT_LOGGER = createLogger();
17652
19635
 
17653
- function safeStorageGet(key) {
19636
+ function safeStorageGet(key, logger = DEFAULT_LOGGER) {
17654
19637
  try {
17655
19638
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17656
- return localStorage.getItem(key);
19639
+ const value = localStorage.getItem(key);
19640
+ if (value !== null && value !== undefined) return value;
17657
19641
  }
17658
- } catch (_) {}
19642
+ } catch (err) {
19643
+ logger.warn(
19644
+ `localStorage.getItem("${key}") failed; using in-memory state.`,
19645
+ err && err.message ? err.message : err
19646
+ );
19647
+ }
17659
19648
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17660
19649
  }
17661
19650
 
17662
- function safeStorageSet(key, value) {
19651
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
17663
19652
  const str = String(value);
17664
19653
  try {
17665
19654
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17666
19655
  localStorage.setItem(key, str);
17667
- return;
19656
+ return true;
19657
+ }
19658
+ } catch (err) {
19659
+ if (typeof onError === 'function') {
19660
+ onError(err);
19661
+ }
19662
+ if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
19663
+ if (!safeStorageSet._warnedKeys.has(key)) {
19664
+ safeStorageSet._warnedKeys.add(key);
19665
+ logger.warn(
19666
+ `localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
19667
+ err && err.message ? err.message : err
19668
+ );
17668
19669
  }
17669
- } catch (_) {}
19670
+ }
17670
19671
  _fallbackStorage.set(key, str);
19672
+ return false;
17671
19673
  }
17672
19674
 
17673
19675
  // ── CodeLabWorkbench Instance Class ──────────────────────────────────────
@@ -17678,12 +19680,25 @@ declare module 'bun:sqlite' {
17678
19680
  throw new Error('CodeLabWorkbench requires a valid DOM container element.');
17679
19681
  }
17680
19682
  this.options = options || {};
19683
+ this.logger = createLogger({ logger: options.logger, debug: options.debug });
19684
+ this._persistenceFailureReported = false;
19685
+ this.saveStatusState = 'saved';
19686
+ this.saveStatusError = null;
17681
19687
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17682
19688
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17683
19689
  this.title = options.title || this.labId;
17684
19690
  this.summary = options.summary || '';
17685
19691
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17686
19692
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
19693
+ this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
19694
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
19695
+ this._previewIsolationWarned = false;
19696
+ if (options.previewOrigin && !this.previewOrigin) {
19697
+ this.logger.warn(
19698
+ 'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
19699
+ 'such as "https://preview.example.com".'
19700
+ );
19701
+ }
17687
19702
  this.explicitEntry = options.entry || null;
17688
19703
  this.explicitTestEntry = options.testEntry || options.testFile || null;
17689
19704
  this.backLabel = options.backLabel || 'Back to Build Guide';
@@ -17755,12 +19770,15 @@ declare module 'bun:sqlite' {
17755
19770
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
17756
19771
  loading: false,
17757
19772
  error: null,
17758
- srcdoc: ''
19773
+ srcdoc: '',
19774
+ violations: []
17759
19775
  };
17760
19776
  this.previewHistory = [];
17761
19777
  this.previewHistoryIdx = -1;
17762
19778
  this._previewSwReady = false;
17763
19779
  this._previewSwRegistration = null;
19780
+ this._previewViolationHandler = null;
19781
+ this._swMessageHandler = null;
17764
19782
  this._portToasts = new Map();
17765
19783
  this.isFullscreen = false;
17766
19784
  this.isRunning = false;
@@ -17860,7 +19878,9 @@ declare module 'bun:sqlite' {
17860
19878
  onCommand: (cmd) => this._handleReplCommand(cmd),
17861
19879
  onInterrupt: () => this._handleInterrupt()
17862
19880
  });
17863
- } catch (_) {}
19881
+ } catch (err) {
19882
+ this.logger.debug('PTY engine initialization skipped.', err);
19883
+ }
17864
19884
  }
17865
19885
 
17866
19886
  this.shell = null;
@@ -17886,7 +19906,7 @@ declare module 'bun:sqlite' {
17886
19906
  intoRoot: options.cloneIntoRoot !== false,
17887
19907
  branch: options.branch || undefined,
17888
19908
  fetchImpl: options.fetchImpl || undefined
17889
- }).catch(() => {});
19909
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
17890
19910
  }
17891
19911
  }
17892
19912
 
@@ -17911,7 +19931,9 @@ declare module 'bun:sqlite' {
17911
19931
  }
17912
19932
  });
17913
19933
  this._syncFilesToShellVfs();
17914
- } catch (_) {}
19934
+ } catch (err) {
19935
+ this.logger.debug('POSIX shell initialization skipped.', err);
19936
+ }
17915
19937
  }
17916
19938
  }
17917
19939
 
@@ -17937,7 +19959,9 @@ declare module 'bun:sqlite' {
17937
19959
  const u = new URL(fullUrl);
17938
19960
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
17939
19961
  reqPath = u.pathname + (u.search || '');
17940
- } catch (_) {}
19962
+ } catch (err) {
19963
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
19964
+ }
17941
19965
  const method = String((init && init.method) || 'GET').toUpperCase();
17942
19966
  try {
17943
19967
  const res = await origDispatch(url, init);
@@ -17949,7 +19973,9 @@ declare module 'bun:sqlite' {
17949
19973
  } else if (res && res.body !== undefined) {
17950
19974
  bodyText = String(res.body);
17951
19975
  }
17952
- } catch (_) {}
19976
+ } catch (err) {
19977
+ this.logger.debug('Could not read response body for HTTP trace.', err);
19978
+ }
17953
19979
  const responseHeaders = {};
17954
19980
  if (res && res.headers) {
17955
19981
  if (typeof res.headers.forEach === 'function') {
@@ -17961,7 +19987,9 @@ declare module 'bun:sqlite' {
17961
19987
  let formattedBody = bodyText;
17962
19988
  try {
17963
19989
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
17964
- } catch (_) {}
19990
+ } catch (err) {
19991
+ void err;
19992
+ }
17965
19993
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
17966
19994
  this.lastHttpTrace.push({
17967
19995
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -18010,7 +20038,9 @@ declare module 'bun:sqlite' {
18010
20038
  vfs.writeFileSync(absPath, String(content ?? ''));
18011
20039
  }
18012
20040
  }
18013
- } catch (_) {}
20041
+ } catch (err) {
20042
+ this.logger.debug('Could not sync files to shell VFS.', err);
20043
+ }
18014
20044
  }
18015
20045
 
18016
20046
  _emitEvent(name, detail) {
@@ -18021,7 +20051,7 @@ declare module 'bun:sqlite' {
18021
20051
  const handlers = this._eventListeners.get(key);
18022
20052
  if (handlers) {
18023
20053
  for (const fn of Array.from(handlers)) {
18024
- try { fn(detail); } catch (_) {}
20054
+ try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
18025
20055
  }
18026
20056
  }
18027
20057
  }
@@ -18032,7 +20062,9 @@ declare module 'bun:sqlite' {
18032
20062
  if (shortName !== fullName) {
18033
20063
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
18034
20064
  }
18035
- } catch (_) {}
20065
+ } catch (err) {
20066
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
20067
+ }
18036
20068
  }
18037
20069
 
18038
20070
  _resolvedTheme() {
@@ -18055,13 +20087,39 @@ declare module 'bun:sqlite' {
18055
20087
  return {};
18056
20088
  }
18057
20089
  try {
18058
- const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
20090
+ const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
18059
20091
  return raw ? JSON.parse(raw) : {};
18060
- } catch {
20092
+ } catch (err) {
20093
+ this.logger.warn(
20094
+ `Ignoring unreadable saved state for "${this.labId}".`,
20095
+ err && err.message ? err.message : err
20096
+ );
18061
20097
  return {};
18062
20098
  }
18063
20099
  }
18064
20100
 
20101
+ _reportPersistenceFailure(cause) {
20102
+ const error = isCodeLabError(cause)
20103
+ ? cause
20104
+ : new CodeLabError(
20105
+ 'E_SAVE',
20106
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
20107
+ { cause, recoverable: true, details: { labId: this.labId } }
20108
+ );
20109
+ this.saveStatusState = 'failed';
20110
+ this.saveStatusError = error;
20111
+ this._updateStatusBar();
20112
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
20113
+ if (this._persistenceFailureReported) return error;
20114
+ this._persistenceFailureReported = true;
20115
+ this.logger.warn(
20116
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
20117
+ );
20118
+ this._emitEvent('persistence-error', { labId: this.labId, error });
20119
+ this._emitEvent('error', error);
20120
+ return error;
20121
+ }
20122
+
18065
20123
  _saveState() {
18066
20124
  try {
18067
20125
  const key = `${this.mode}:${this.lang}`;
@@ -18083,14 +20141,36 @@ declare module 'bun:sqlite' {
18083
20141
  };
18084
20142
  this.savedState = state;
18085
20143
  if (this.options && this.options.persistState === false) {
20144
+ this.saveStatusState = 'saved';
20145
+ this.saveStatusError = null;
20146
+ this._updateStatusBar();
18086
20147
  return;
18087
20148
  }
20149
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
18088
20150
  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 {}
20151
+ safeStorageSet._lastError = null;
20152
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
20153
+ const persisted = [
20154
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
20155
+ // Sync with host app sidebar & build overview progress trackers
20156
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20157
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
20158
+ ];
20159
+ if (persisted.includes(false)) {
20160
+ this._reportPersistenceFailure(safeStorageSet._lastError);
20161
+ } else {
20162
+ this.saveStatusState = 'saved';
20163
+ this.saveStatusError = null;
20164
+ this._updateStatusBar();
20165
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
20166
+ }
20167
+ } catch (err) {
20168
+ this.logger.error(
20169
+ 'Failed to save workbench state.',
20170
+ err && err.message ? err.message : err
20171
+ );
20172
+ this._reportPersistenceFailure(err);
20173
+ }
18094
20174
  }
18095
20175
 
18096
20176
  _detectPackages() {
@@ -18112,7 +20192,9 @@ declare module 'bun:sqlite' {
18112
20192
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
18113
20193
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
18114
20194
  }
18115
- } catch (_) {}
20195
+ } catch (err) {
20196
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
20197
+ }
18116
20198
  }
18117
20199
 
18118
20200
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -18159,6 +20241,7 @@ declare module 'bun:sqlite' {
18159
20241
  const dotEl = this.container.querySelector('#cl-status-dot');
18160
20242
  const textEl = this.container.querySelector('#cl-status-text');
18161
20243
  const fileEl = this.container.querySelector('#cl-status-file');
20244
+ const saveEl = this.container.querySelector('#cl-status-save');
18162
20245
  const durEl = this.container.querySelector('#cl-status-duration');
18163
20246
  const curEl = this.container.querySelector('#cl-status-cursor');
18164
20247
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -18170,6 +20253,24 @@ declare module 'bun:sqlite' {
18170
20253
  }
18171
20254
  if (textEl) textEl.textContent = this.runtimeStatusText;
18172
20255
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
20256
+ if (saveEl) {
20257
+ if (this.saveStatusState === 'failed') {
20258
+ saveEl.style.display = 'inline-flex';
20259
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
20260
+ saveEl.textContent = '⚠ Save failed (session-only)';
20261
+ const reason = this.saveStatusError && this.saveStatusError.message
20262
+ ? this.saveStatusError.message
20263
+ : 'localStorage is unavailable or quota exceeded';
20264
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
20265
+ saveEl.setAttribute('data-save-state', 'failed');
20266
+ } else {
20267
+ saveEl.style.display = 'none';
20268
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
20269
+ saveEl.textContent = '';
20270
+ saveEl.removeAttribute('title');
20271
+ saveEl.setAttribute('data-save-state', 'saved');
20272
+ }
20273
+ }
18173
20274
  if (durEl) {
18174
20275
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
18175
20276
  durEl.style.display = 'inline-flex';
@@ -18477,6 +20578,7 @@ declare module 'bun:sqlite' {
18477
20578
  </span>
18478
20579
  <span class="codelab-statusbar__sep">·</span>
18479
20580
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
20581
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
18480
20582
  </div>
18481
20583
  <div class="codelab-statusbar__right">
18482
20584
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -19731,7 +21833,9 @@ declare module 'bun:sqlite' {
19731
21833
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
19732
21834
  try {
19733
21835
  this.ptyEngine.writeStreamChunk(rawText, type);
19734
- } catch (_) {}
21836
+ } catch (err) {
21837
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
21838
+ }
19735
21839
  }
19736
21840
 
19737
21841
  this._activeStreamType = type;
@@ -19863,14 +21967,18 @@ declare module 'bun:sqlite' {
19863
21967
  if (this._activeCommandAbortController) {
19864
21968
  try {
19865
21969
  this._activeCommandAbortController.abort('SIGINT');
19866
- } catch (_) {}
21970
+ } catch (err) {
21971
+ this.logger.debug('AbortController.abort failed.', err);
21972
+ }
19867
21973
  this._activeCommandAbortController = null;
19868
21974
  }
19869
21975
 
19870
21976
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
19871
21977
  try {
19872
21978
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
19873
- } catch (_) {}
21979
+ } catch (err) {
21980
+ this.logger.debug('cancelWorkerExecution failed.', err);
21981
+ }
19874
21982
  }
19875
21983
 
19876
21984
  this.isRunning = false;
@@ -20439,7 +22547,9 @@ declare module 'bun:sqlite' {
20439
22547
  try {
20440
22548
  const parsed = JSON.parse(responseBody);
20441
22549
  formattedBody = JSON.stringify(parsed, null, 2);
20442
- } catch (_) {}
22550
+ } catch (_) {
22551
+ formattedBody = responseBody;
22552
+ }
20443
22553
 
20444
22554
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
20445
22555
  const traceItem = {
@@ -20512,7 +22622,9 @@ declare module 'bun:sqlite' {
20512
22622
  if (this.drawerTab === 'ports') this._renderDrawerBody();
20513
22623
  this._dismissPortToast(port);
20514
22624
  }));
20515
- } catch (_) {}
22625
+ } catch (err) {
22626
+ this.logger.warn('Failed to attach portTable event listeners.', err);
22627
+ }
20516
22628
  }
20517
22629
 
20518
22630
  _updatePortsPill() {
@@ -20586,16 +22698,55 @@ declare module 'bun:sqlite' {
20586
22698
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
20587
22699
  try {
20588
22700
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
22701
+ this._swMessageHandler = onMessage;
20589
22702
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
20590
22703
  navigator.serviceWorker.addEventListener('message', onMessage);
20591
22704
  } else {
20592
22705
  navigator.serviceWorker.onmessage = onMessage;
20593
22706
  }
20594
22707
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
20595
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
20596
- .catch(() => { this._previewSwReady = false; });
20597
- } catch (_) {
22708
+ .then((reg) => {
22709
+ this._previewSwRegistration = reg;
22710
+ this._previewSwReady = true;
22711
+ this._pushPreviewCsp(reg);
22712
+ })
22713
+ .catch((err) => {
22714
+ this._previewSwReady = false;
22715
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
22716
+ });
22717
+ } catch (err) {
20598
22718
  this._previewSwReady = false;
22719
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
22720
+ }
22721
+ }
22722
+
22723
+ /**
22724
+ * The service worker cannot read workbench options, so the resolved policy
22725
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
22726
+ * the srcdoc fallback and silently not the served previews.
22727
+ */
22728
+ _pushPreviewCsp(registration) {
22729
+ const policy = this._previewPolicy();
22730
+ const send = (worker) => {
22731
+ if (!worker || typeof worker.postMessage !== 'function') return;
22732
+ try {
22733
+ worker.postMessage({ type: 'codelab:config', csp: policy });
22734
+ } catch (err) {
22735
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
22736
+ }
22737
+ };
22738
+
22739
+ if (registration) {
22740
+ send(registration.active);
22741
+ send(registration.installing);
22742
+ send(registration.waiting);
22743
+ }
22744
+
22745
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
22746
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
22747
+ sw.ready
22748
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
22749
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
20599
22750
  }
20600
22751
  }
20601
22752
 
@@ -20628,11 +22779,15 @@ declare module 'bun:sqlite' {
20628
22779
  } else if (res && res.headers) {
20629
22780
  Object.assign(outHeaders, res.headers);
20630
22781
  }
20631
- } catch (_) {}
22782
+ } catch (err) {
22783
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
22784
+ }
20632
22785
  let bodyText = '';
20633
22786
  try {
20634
22787
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
20635
- } catch (_) {}
22788
+ } catch (err) {
22789
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
22790
+ }
20636
22791
  return {
20637
22792
  status: (res && res.status) || 200,
20638
22793
  statusText: (res && res.statusText) || 'OK',
@@ -20655,12 +22810,174 @@ declare module 'bun:sqlite' {
20655
22810
  return `http://127.0.0.1:${port}${path}`;
20656
22811
  }
20657
22812
 
22813
+ _previewFrameUrl(port, pathAndQuery = '/') {
22814
+ const p = Number(port) || 3000;
22815
+ const rawPath = pathAndQuery || '/';
22816
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
22817
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
22818
+ // relay exists on that origin; pretending otherwise yields a 503.
22819
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
22820
+ return `${base}/__preview/${p}${path}`;
22821
+ }
22822
+
22823
+ /** Resolved CSP for preview documents served by this workbench. */
22824
+ _previewPolicy() {
22825
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
22826
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
22827
+ return "default-src 'self'; object-src 'none'";
22828
+ }
22829
+ return PreviewCsp.buildPreviewPolicy(
22830
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
22831
+ );
22832
+ }
22833
+
22834
+ /** Remote origins the current policy allows, for the preview toolbar. */
22835
+ _previewNetworkHosts() {
22836
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
22837
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
22838
+ }
22839
+
22840
+ _warnPreviewIsolation() {
22841
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
22842
+ this._previewIsolationWarned = true;
22843
+ if (PREVIEW_RELAY_AVAILABLE) return;
22844
+ this.logger.warn(
22845
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
22846
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
22847
+ 'the host origin: no host DOM, no host storage.'
22848
+ );
22849
+ }
22850
+
22851
+ _injectPreviewCsp(html, port) {
22852
+ if (typeof html !== 'string' || !html) return html;
22853
+
22854
+ const tags = [];
22855
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
22856
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
22857
+ }
22858
+ if (!/<base\b/i.test(html)) {
22859
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
22860
+ }
22861
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
22862
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
22863
+ tags.push(PreviewCsp.buildPreviewShims());
22864
+ }
22865
+ if (tags.length === 0) return html;
22866
+
22867
+ const injection = tags.join('');
22868
+ if (/<head\b[^>]*>/i.test(html)) {
22869
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
22870
+ }
22871
+ if (/<html\b[^>]*>/i.test(html)) {
22872
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
22873
+ }
22874
+ return `<head>${injection}</head>${html}`;
22875
+ }
22876
+
22877
+ /**
22878
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
22879
+ * string `"null"` and cannot be used to authenticate the sender. Match the
22880
+ * message source against the preview frame instead.
22881
+ */
22882
+ _installPreviewViolationListener() {
22883
+ if (this._previewViolationHandler) return;
22884
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
22885
+
22886
+ this._previewViolationHandler = (event) => {
22887
+ const data = event && event.data;
22888
+ if (!data || typeof data.type !== 'string') return;
22889
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
22890
+ if (!iframe) return;
22891
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
22892
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
22893
+
22894
+ if (data.type === 'codelab:preview-violation') {
22895
+ this._reportPreviewViolation(data);
22896
+ } else if (data.type === 'codelab:preview-console') {
22897
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
22898
+ const args = Array.isArray(data.args) ? data.args : [data.args];
22899
+ const text = args.map((a) => String(a ?? '')).join(' ');
22900
+ this.terminalLogs.push({
22901
+ type: level === 'error' ? 'stderr' : 'stdout',
22902
+ text: `[Preview ${level.toUpperCase()}] ${text}`
22903
+ });
22904
+ this._emitEvent('preview-console', { level, text, args });
22905
+ } else if (data.type === 'codelab:preview-error') {
22906
+ const msg = String(data.message || 'Uncaught runtime error');
22907
+ this.previewState.runtimeError = {
22908
+ message: msg,
22909
+ file: data.file ? String(data.file) : null,
22910
+ line: typeof data.line === 'number' ? data.line : null,
22911
+ col: typeof data.col === 'number' ? data.col : null,
22912
+ stack: data.stack ? String(data.stack) : null
22913
+ };
22914
+ this.terminalLogs.push({
22915
+ type: 'stderr',
22916
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
22917
+ });
22918
+ this._emitEvent('preview-error', this.previewState.runtimeError);
22919
+ } else if (data.type === 'codelab:preview-error-clear') {
22920
+ this.previewState.runtimeError = null;
22921
+ }
22922
+ };
22923
+ window.addEventListener('message', this._previewViolationHandler);
22924
+ }
22925
+
22926
+ _reportPreviewViolation(violation) {
22927
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
22928
+ const directive = String((violation && violation.directive) || '');
22929
+ const key = `${directive}|${blockedURI}`;
22930
+ const state = this.previewState;
22931
+ state.violations = state.violations || [];
22932
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
22933
+ state.violations.push({ key, directive, blockedURI });
22934
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
22935
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
22936
+ }
22937
+ this._updatePreviewCspStatus();
22938
+ }
22939
+
22940
+ _shortPreviewUrl(raw) {
22941
+ const value = String(raw || '');
22942
+ try {
22943
+ const parsed = new URL(value);
22944
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
22945
+ return `${parsed.host}${path === '/' ? '' : path}`;
22946
+ } catch (_) {
22947
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
22948
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
22949
+ }
22950
+ }
22951
+
22952
+ /** Update (or create) the CSP status chip in the preview toolbar. */
22953
+ _updatePreviewCspStatus() {
22954
+ if (!this.container) return;
22955
+ const chip = this.container.querySelector('#cl-preview-csp-status');
22956
+ if (!chip) return;
22957
+ const violations = (this.previewState && this.previewState.violations) || [];
22958
+ if (!violations.length) {
22959
+ chip.hidden = true;
22960
+ chip.textContent = '';
22961
+ chip.removeAttribute('title');
22962
+ return;
22963
+ }
22964
+ const last = violations[violations.length - 1];
22965
+ chip.hidden = false;
22966
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
22967
+ chip.title = violations
22968
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
22969
+ .join('\n');
22970
+ }
22971
+
20658
22972
  _openWebPreview(port, path = '/') {
20659
22973
  const p = Number(port) || this._firstListeningPort() || 3000;
22974
+ this._warnPreviewIsolation();
22975
+ this._installPreviewViolationListener();
20660
22976
  this.previewState.port = p;
20661
22977
  this.previewState.path = path || '/';
20662
22978
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
20663
22979
  this.previewState.error = null;
22980
+ this.previewState.violations = [];
20664
22981
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20665
22982
  this.previewHistory.push(this.previewState.url);
20666
22983
  this.previewHistoryIdx = this.previewHistory.length - 1;
@@ -20751,7 +23068,7 @@ declare module 'bun:sqlite' {
20751
23068
  try {
20752
23069
  const win = window.open(url, '_blank');
20753
23070
  if (win) {
20754
- try { win.opener = null; } catch (_) {}
23071
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
20755
23072
  opened = true;
20756
23073
  }
20757
23074
  } catch (_) { opened = false; }
@@ -20773,7 +23090,9 @@ declare module 'bun:sqlite' {
20773
23090
  const u = new URL(url);
20774
23091
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
20775
23092
  path = u.pathname + (u.search || '') + (u.hash || '');
20776
- } catch (_) {}
23093
+ } catch (err) {
23094
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
23095
+ }
20777
23096
  this.previewState.port = port;
20778
23097
  this.previewState.path = path;
20779
23098
  this.previewState.url = url;
@@ -20805,7 +23124,9 @@ declare module 'bun:sqlite' {
20805
23124
  const u = new URL(url);
20806
23125
  this.previewState.port = Number(u.port || 80);
20807
23126
  this.previewState.path = u.pathname + (u.search || '');
20808
- } catch (_) {}
23127
+ } catch (err) {
23128
+ this.logger.debug('Failed to parse preview history URL.', err);
23129
+ }
20809
23130
  const input = this.container.querySelector('#cl-preview-url-input');
20810
23131
  if (input) input.value = url;
20811
23132
  this._renderWebPreviewControls();
@@ -20835,19 +23156,22 @@ declare module 'bun:sqlite' {
20835
23156
 
20836
23157
  _popoutPreview() {
20837
23158
  const url = this._previewUrl();
20838
- let popout = '/__preview/';
23159
+ let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
20839
23160
  try {
20840
23161
  const u = new URL(url);
20841
- popout = `/__preview/${u.port}${u.pathname}${u.search || ''}`;
20842
- } catch (_) {}
23162
+ popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
23163
+ } catch (err) {
23164
+ this.logger.debug('Failed to parse popout preview URL.', err);
23165
+ }
20843
23166
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
20844
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
23167
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
20845
23168
  }
20846
23169
  return popout;
20847
23170
  }
20848
23171
 
20849
23172
  _renderWebPreview(bodyEl) {
20850
23173
  if (!bodyEl) return;
23174
+ this._warnPreviewIsolation();
20851
23175
  const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
20852
23176
  if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
20853
23177
  this._renderWebPreviewControls();
@@ -20867,6 +23191,19 @@ declare module 'bun:sqlite' {
20867
23191
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
20868
23192
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
20869
23193
 
23194
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
23195
+ const cspHosts = this._previewNetworkHosts();
23196
+ const cspBadge = cspMode === 'strict'
23197
+ ? 'CSP: strict'
23198
+ : !cspHosts.length
23199
+ ? 'CSP: custom'
23200
+ : cspHosts.length === 1
23201
+ ? `CSP: ${cspHosts[0]}`
23202
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
23203
+ const cspBadgeTitle = cspMode === 'strict'
23204
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23205
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23206
+
20870
23207
  bodyEl.innerHTML = `
20871
23208
  <div class="codelab-preview">
20872
23209
  <div class="codelab-preview-chrome">
@@ -20882,10 +23219,12 @@ declare module 'bun:sqlite' {
20882
23219
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'tablet' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="tablet" title="Tablet">${CL_ICONS.tablet || '▢'}</button>
20883
23220
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'mobile' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="mobile" title="Mobile">${CL_ICONS.smartphone || '▯'}</button>
20884
23221
  </div>
23222
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23223
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
20885
23224
  <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
23225
  </div>
20887
23226
  <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>
23227
+ <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>
20889
23228
  </div>
20890
23229
  ${servers.length
20891
23230
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -20898,6 +23237,7 @@ declare module 'bun:sqlite' {
20898
23237
  </div>`}
20899
23238
  </div>
20900
23239
  `;
23240
+ this._updatePreviewCspStatus();
20901
23241
  this._loadPreviewFrame();
20902
23242
  }
20903
23243
 
@@ -20922,10 +23262,12 @@ declare module 'bun:sqlite' {
20922
23262
  try {
20923
23263
  const u = new URL(fullUrl);
20924
23264
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
20925
- iframe.setAttribute('src', `/__preview/${u.port}${u.pathname}${u.search || ''}`);
23265
+ iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
20926
23266
  this.previewState.loading = false;
20927
23267
  return Promise.resolve();
20928
- } catch (_) {}
23268
+ } catch (err) {
23269
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
23270
+ }
20929
23271
  }
20930
23272
 
20931
23273
  // Fallback (no Service Worker): dispatch via the virtual port table and
@@ -20934,8 +23276,8 @@ declare module 'bun:sqlite' {
20934
23276
  .then((res) => {
20935
23277
  let body = res.body || '';
20936
23278
  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}/">`);
23279
+ if (/text\/html/i.test(contentType)) {
23280
+ body = this._injectPreviewCsp(body, port);
20939
23281
  }
20940
23282
  this.previewState.srcdoc = body;
20941
23283
  this.previewState.loading = false;
@@ -20947,7 +23289,7 @@ declare module 'bun:sqlite' {
20947
23289
  this.previewState.loading = false;
20948
23290
  this.previewState.error = String((err && err.message) || err);
20949
23291
  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);
23292
+ iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
20951
23293
  });
20952
23294
  }
20953
23295
 
@@ -20991,7 +23333,7 @@ declare module 'bun:sqlite' {
20991
23333
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
20992
23334
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
20993
23335
  let isDir = false;
20994
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
23336
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
20995
23337
  if (isDir) {
20996
23338
  shellWorkspaceFolders.add(rel);
20997
23339
  walk(full, rel);
@@ -20999,7 +23341,9 @@ declare module 'bun:sqlite' {
20999
23341
  try {
21000
23342
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
21001
23343
  shellWorkspaceFiles.set(rel, content);
21002
- } catch (_) {}
23344
+ } catch (err) {
23345
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
23346
+ }
21003
23347
  }
21004
23348
  }
21005
23349
  };
@@ -21301,8 +23645,29 @@ declare module 'bun:sqlite' {
21301
23645
  }
21302
23646
 
21303
23647
  _notifyCodeChange(filename, code) {
23648
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
23649
+ try {
23650
+ const clean = String(filename).replace(/^\/+/, '');
23651
+ const parts = clean.split('/');
23652
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
23653
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
23654
+ }
23655
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
23656
+ } catch (err) {
23657
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
23658
+ }
23659
+ }
23660
+ if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
23661
+ if (this._previewReloadTimer) {
23662
+ clearTimeout(this._previewReloadTimer);
23663
+ }
23664
+ this._previewReloadTimer = setTimeout(() => {
23665
+ this._previewReloadTimer = null;
23666
+ this._previewReload();
23667
+ }, 300);
23668
+ }
21304
23669
  if (this.onCodeChange) {
21305
- try { this.onCodeChange(filename, code); } catch (_) {}
23670
+ try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21306
23671
  }
21307
23672
  const detail = { labId: this.labId, filename, path: filename, code, content: code };
21308
23673
  this._emitEvent('codelab:change', detail);
@@ -21358,7 +23723,7 @@ declare module 'bun:sqlite' {
21358
23723
  if (fallbackWrap) fallbackWrap.style.display = 'none';
21359
23724
  if (mdPreview) mdPreview.style.display = 'none';
21360
23725
  if (this.editor) {
21361
- try { this.editor.setModel(null); } catch (_) {}
23726
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
21362
23727
  }
21363
23728
  if (emptyEl) {
21364
23729
  emptyEl.style.display = 'flex';
@@ -21670,7 +24035,9 @@ declare module 'bun:sqlite' {
21670
24035
  textarea.select();
21671
24036
  document.execCommand('copy');
21672
24037
  document.body.removeChild(textarea);
21673
- } catch (_) {}
24038
+ } catch (err) {
24039
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
24040
+ }
21674
24041
  };
21675
24042
 
21676
24043
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -22028,6 +24395,7 @@ declare module 'bun:sqlite' {
22028
24395
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
22029
24396
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
22030
24397
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
24398
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
22031
24399
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
22032
24400
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
22033
24401
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -22038,6 +24406,9 @@ declare module 'bun:sqlite' {
22038
24406
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
22039
24407
  } },
22040
24408
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
24409
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
24410
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
24411
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
22041
24412
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
22042
24413
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
22043
24414
  ];
@@ -22070,7 +24441,9 @@ declare module 'bun:sqlite' {
22070
24441
  input.focus();
22071
24442
  try {
22072
24443
  input.setSelectionRange(initialVal.length, initialVal.length);
22073
- } catch (_) {}
24444
+ } catch (err) {
24445
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
24446
+ }
22074
24447
 
22075
24448
  input.addEventListener('input', () => {
22076
24449
  this.paletteSelectedIndex = 0;
@@ -22343,7 +24716,7 @@ declare module 'bun:sqlite' {
22343
24716
  const onUp = ev => {
22344
24717
  vSplitter.classList.remove('is-dragging');
22345
24718
  shell.classList.remove('is-resizing');
22346
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24719
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22347
24720
  vSplitter.removeEventListener('pointermove', onMove);
22348
24721
  vSplitter.removeEventListener('pointerup', onUp);
22349
24722
  };
@@ -22384,7 +24757,7 @@ declare module 'bun:sqlite' {
22384
24757
  const onUp = ev => {
22385
24758
  hSplitter.classList.remove('is-dragging');
22386
24759
  shell.classList.remove('is-resizing-row');
22387
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24760
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22388
24761
  hSplitter.removeEventListener('pointermove', onMove);
22389
24762
  hSplitter.removeEventListener('pointerup', onUp);
22390
24763
  };
@@ -22411,7 +24784,7 @@ declare module 'bun:sqlite' {
22411
24784
  e.preventDefault();
22412
24785
  fSplitter.classList.add('is-dragging');
22413
24786
  shell.classList.add('is-resizing');
22414
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
24787
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
22415
24788
 
22416
24789
  const onMove = ev => {
22417
24790
  const ws = this.container.querySelector('.codelab-workspace');
@@ -22425,7 +24798,7 @@ declare module 'bun:sqlite' {
22425
24798
  const onUp = ev => {
22426
24799
  fSplitter.classList.remove('is-dragging');
22427
24800
  shell.classList.remove('is-resizing');
22428
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24801
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22429
24802
  fSplitter.removeEventListener('pointermove', onMove);
22430
24803
  fSplitter.removeEventListener('pointerup', onUp);
22431
24804
  this._saveState();
@@ -22768,7 +25141,9 @@ declare module 'bun:sqlite' {
22768
25141
  if (this.files['package.json']) {
22769
25142
  try {
22770
25143
  pkgJson = JSON.parse(this.files['package.json']);
22771
- } catch (_) {}
25144
+ } catch (err) {
25145
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
25146
+ }
22772
25147
  }
22773
25148
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
22774
25149
  pkgJson.dependencies = {};
@@ -22941,7 +25316,7 @@ declare module 'bun:sqlite' {
22941
25316
  }
22942
25317
 
22943
25318
  if (this.onRun) {
22944
- try { this.onRun(res); } catch (_) {}
25319
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
22945
25320
  }
22946
25321
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
22947
25322
  } catch (err) {
@@ -23016,10 +25391,10 @@ declare module 'bun:sqlite' {
23016
25391
  }
23017
25392
 
23018
25393
  if (this.onTestResult) {
23019
- try { this.onTestResult(res); } catch (_) {}
25394
+ try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
23020
25395
  }
23021
25396
  if (this.onRun) {
23022
- try { this.onRun(res); } catch (_) {}
25397
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
23023
25398
  }
23024
25399
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
23025
25400
 
@@ -23033,7 +25408,7 @@ declare module 'bun:sqlite' {
23033
25408
  this.completedSteps.add(step.id);
23034
25409
  newlyCompleted = true;
23035
25410
  if (this.onStepComplete) {
23036
- try { this.onStepComplete(step, sIdx); } catch (_) {}
25411
+ try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
23037
25412
  }
23038
25413
  const stepDetail = {
23039
25414
  labId: this.labId,
@@ -23052,7 +25427,7 @@ declare module 'bun:sqlite' {
23052
25427
  this._saveState();
23053
25428
  if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
23054
25429
  if (this.onLabComplete) {
23055
- try { this.onLabComplete(this.labId); } catch (_) {}
25430
+ try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
23056
25431
  }
23057
25432
  this._emitEvent('codelab:lab-complete', {
23058
25433
  labId: this.labId,
@@ -23357,7 +25732,12 @@ declare module 'bun:sqlite' {
23357
25732
  a.click();
23358
25733
  setTimeout(() => URL.revokeObjectURL(url), 500);
23359
25734
  }
23360
- } catch (_) {}
25735
+ } catch (err) {
25736
+ this.logger.error(
25737
+ `Failed to start download for "${filename}".`,
25738
+ err && err.message ? err.message : err
25739
+ );
25740
+ }
23361
25741
  return content;
23362
25742
  }
23363
25743
 
@@ -23385,7 +25765,12 @@ declare module 'bun:sqlite' {
23385
25765
  a.click();
23386
25766
  setTimeout(() => URL.revokeObjectURL(url), 500);
23387
25767
  }
23388
- } catch (_) {}
25768
+ } catch (err) {
25769
+ this.logger.error(
25770
+ 'Failed to download workspace export.',
25771
+ err && err.message ? err.message : err
25772
+ );
25773
+ }
23389
25774
  }
23390
25775
  return snapshot;
23391
25776
  }
@@ -23419,6 +25804,219 @@ declare module 'bun:sqlite' {
23419
25804
  return true;
23420
25805
  }
23421
25806
 
25807
+ exportProjectZip(options = {}) {
25808
+ const zipMod = root.CodeLabZip;
25809
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
25810
+ throw new Error('CodeLabZip engine is not loaded');
25811
+ }
25812
+ const bytes = zipMod.createZip(this.files || {});
25813
+ if (options && options.download) {
25814
+ try {
25815
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
25816
+ const blob = new Blob([bytes], { type: 'application/zip' });
25817
+ const url = URL.createObjectURL(blob);
25818
+ const a = document.createElement('a');
25819
+ a.href = url;
25820
+ a.download = `${this.labId || 'workspace'}.zip`;
25821
+ a.click();
25822
+ setTimeout(() => URL.revokeObjectURL(url), 500);
25823
+ }
25824
+ } catch (err) {
25825
+ this.logger.error('Failed to download project ZIP export.', err);
25826
+ }
25827
+ }
25828
+ return bytes;
25829
+ }
25830
+
25831
+ importProjectZip(zipBytes) {
25832
+ const zipMod = root.CodeLabZip;
25833
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
25834
+ throw new Error('CodeLabZip engine is not loaded');
25835
+ }
25836
+ const extracted = zipMod.extractZip(zipBytes);
25837
+ if (!extracted || typeof extracted !== 'object') return false;
25838
+ this.setFiles(extracted);
25839
+ this._syncFilesToShellVfs();
25840
+ return true;
25841
+ }
25842
+
25843
+ searchWorkspace(options) {
25844
+ const searchMod = root.CodeLabSearch;
25845
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
25846
+ throw new Error('CodeLabSearch engine is not loaded');
25847
+ }
25848
+ return searchMod.searchInFiles(this.files || {}, options);
25849
+ }
25850
+
25851
+ replaceInWorkspace(options) {
25852
+ const searchMod = root.CodeLabSearch;
25853
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
25854
+ throw new Error('CodeLabSearch engine is not loaded');
25855
+ }
25856
+ const res = searchMod.replaceInFiles(this.files || {}, options);
25857
+ if (res && res.files && res.filesModified > 0) {
25858
+ this.setFiles(res.files);
25859
+ this._syncFilesToShellVfs();
25860
+ }
25861
+ return res;
25862
+ }
25863
+
25864
+ getGitStatus() {
25865
+ const scmMod = root.CodeLabScm;
25866
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
25867
+ return [];
25868
+ }
25869
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
25870
+ return scmMod.computeGitStatus(gs, this.files || {});
25871
+ }
25872
+
25873
+ getDiagnostics() {
25874
+ const diagMod = root.CodeLabDiagnostics;
25875
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
25876
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
25877
+ }
25878
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
25879
+ return this._diagnosticsStore.getAll();
25880
+ }
25881
+ return [];
25882
+ }
25883
+
25884
+ showSearchModal(initialQuery = '') {
25885
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25886
+ if (!slot) return;
25887
+ const q = String(initialQuery || '');
25888
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
25889
+ const rowsHtml = (results.matches || []).map((m) => `
25890
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
25891
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
25892
+ </div>
25893
+ `).join('');
25894
+ slot.innerHTML = `
25895
+ <div class="codelab-modal-backdrop">
25896
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
25897
+ <div class="codelab-modal__header">
25898
+ <span>Search &amp; Replace Across Workspace</span>
25899
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25900
+ </div>
25901
+ <div class="codelab-modal__body">
25902
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
25903
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
25904
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
25905
+ </div>
25906
+ <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
25907
+ </div>
25908
+ </div>
25909
+ </div>
25910
+ `;
25911
+ }
25912
+
25913
+ showScmModal() {
25914
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25915
+ if (!slot) return;
25916
+ const statusList = this.getGitStatus();
25917
+ const rowsHtml = statusList.map((entry) => `
25918
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
25919
+ <span>${escapeHtml(entry.path)}</span>
25920
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
25921
+ </div>
25922
+ `).join('');
25923
+ slot.innerHTML = `
25924
+ <div class="codelab-modal-backdrop">
25925
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
25926
+ <div class="codelab-modal__header">
25927
+ <span>Source Control (Git Status)</span>
25928
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25929
+ </div>
25930
+ <div class="codelab-modal__body">
25931
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
25932
+ </div>
25933
+ </div>
25934
+ </div>
25935
+ `;
25936
+ }
25937
+
25938
+ showProblemsModal() {
25939
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25940
+ if (!slot) return;
25941
+ const items = this.getDiagnostics();
25942
+ const rowsHtml = items.map((d) => `
25943
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
25944
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
25945
+ </div>
25946
+ `).join('');
25947
+ slot.innerHTML = `
25948
+ <div class="codelab-modal-backdrop">
25949
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
25950
+ <div class="codelab-modal__header">
25951
+ <span>Problems (${items.length})</span>
25952
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25953
+ </div>
25954
+ <div class="codelab-modal__body">
25955
+ <div id="cl-problems-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">No problems have been detected in the workspace.</div>'}</div>
25956
+ </div>
25957
+ </div>
25958
+ </div>
25959
+ `;
25960
+ }
25961
+
25962
+ _ensureTerminalSessions() {
25963
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
25964
+ this._terminalSessions = [
25965
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
25966
+ ];
25967
+ this._activeTerminalSessionId = 'session-1';
25968
+ }
25969
+ return this._terminalSessions;
25970
+ }
25971
+
25972
+ listTerminalSessions() {
25973
+ const sessions = this._ensureTerminalSessions();
25974
+ return sessions.map((s) => ({
25975
+ id: s.id,
25976
+ name: s.name,
25977
+ active: s.id === this._activeTerminalSessionId,
25978
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
25979
+ }));
25980
+ }
25981
+
25982
+ createTerminalSession(name) {
25983
+ const sessions = this._ensureTerminalSessions();
25984
+ const nextNum = sessions.length + 1;
25985
+ const id = `session-${Date.now()}-${nextNum}`;
25986
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
25987
+ const newLogs = [];
25988
+ sessions.push({ id, name: label, logs: newLogs });
25989
+ this._activeTerminalSessionId = id;
25990
+ this.terminalLogs = newLogs;
25991
+ this._renderDrawerBody();
25992
+ return id;
25993
+ }
25994
+
25995
+ switchTerminalSession(id) {
25996
+ const sessions = this._ensureTerminalSessions();
25997
+ const target = sessions.find((s) => s.id === id || s.name === id);
25998
+ if (!target) return false;
25999
+ this._activeTerminalSessionId = target.id;
26000
+ this.terminalLogs = target.logs;
26001
+ this._renderDrawerBody();
26002
+ return true;
26003
+ }
26004
+
26005
+ closeTerminalSession(id) {
26006
+ const sessions = this._ensureTerminalSessions();
26007
+ if (sessions.length <= 1) return false;
26008
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
26009
+ if (idx === -1) return false;
26010
+ const removed = sessions.splice(idx, 1)[0];
26011
+ if (this._activeTerminalSessionId === removed.id) {
26012
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
26013
+ this._activeTerminalSessionId = next.id;
26014
+ this.terminalLogs = next.logs;
26015
+ }
26016
+ this._renderDrawerBody();
26017
+ return true;
26018
+ }
26019
+
23422
26020
  getFiles() {
23423
26021
  return { ...this.files };
23424
26022
  }
@@ -23426,7 +26024,7 @@ declare module 'bun:sqlite' {
23426
26024
  setFiles(filesMap) {
23427
26025
  if (!filesMap || typeof filesMap !== 'object') return;
23428
26026
  for (const model of this.models.values()) {
23429
- try { model.dispose(); } catch (_) {}
26027
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
23430
26028
  }
23431
26029
  this.models.clear();
23432
26030
  this.files = {};
@@ -23516,7 +26114,9 @@ declare module 'bun:sqlite' {
23516
26114
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
23517
26115
  try {
23518
26116
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
23519
- } catch (_) {}
26117
+ } catch (err) {
26118
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
26119
+ }
23520
26120
  }
23521
26121
  this._notifyCodeChange(clean, updated);
23522
26122
  }
@@ -23736,9 +26336,22 @@ declare module 'bun:sqlite' {
23736
26336
 
23737
26337
  destroy() {
23738
26338
  this.stopExecution();
26339
+ if (this._previewReloadTimer) {
26340
+ clearTimeout(this._previewReloadTimer);
26341
+ this._previewReloadTimer = null;
26342
+ }
23739
26343
  if (this._escHandler && typeof document !== 'undefined') {
23740
26344
  document.removeEventListener('keydown', this._escHandler);
23741
26345
  }
26346
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26347
+ window.removeEventListener('message', this._previewViolationHandler);
26348
+ }
26349
+ this._previewViolationHandler = null;
26350
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
26351
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
26352
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
26353
+ }
26354
+ this._swMessageHandler = null;
23742
26355
  if (this._themeObserver) {
23743
26356
  this._themeObserver.disconnect();
23744
26357
  }
@@ -23799,7 +26412,9 @@ declare module 'bun:sqlite' {
23799
26412
  if (jsonScript && jsonScript.textContent) {
23800
26413
  try {
23801
26414
  inlineConfig = JSON.parse(jsonScript.textContent);
23802
- } catch (_) {}
26415
+ } catch (err) {
26416
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
26417
+ }
23803
26418
  }
23804
26419
 
23805
26420
  // Parse optional files JSON attribute
@@ -23808,7 +26423,9 @@ declare module 'bun:sqlite' {
23808
26423
  if (filesAttr) {
23809
26424
  try {
23810
26425
  attrFiles = JSON.parse(filesAttr);
23811
- } catch (_) {}
26426
+ } catch (err) {
26427
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
26428
+ }
23812
26429
  }
23813
26430
 
23814
26431
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -23851,6 +26468,19 @@ declare module 'bun:sqlite' {
23851
26468
  reset() { if (this._instance) this._instance.reset(); }
23852
26469
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
23853
26470
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
26471
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
26472
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
26473
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
26474
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
26475
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
26476
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
26477
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
26478
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
26479
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
26480
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
26481
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
26482
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
26483
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
23854
26484
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
23855
26485
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
23856
26486
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -23881,13 +26511,46 @@ declare module 'bun:sqlite' {
23881
26511
  }
23882
26512
 
23883
26513
  const CodeLabSDK = {
23884
- version: '2.0.0',
26514
+ version: CODELAB_VERSION,
23885
26515
  Workbench: CodeLabWorkbench,
23886
26516
  CodeLabWorkbench,
23887
26517
  CodeLabElement: CodeLabElementClass,
26518
+ CodeLabError,
26519
+ isCodeLabError,
26520
+ createLogger,
26521
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
26522
+ html,
26523
+ raw,
26524
+ isSafeHtml,
26525
+ escapeHtml,
26526
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
23888
26527
  Runtime: root.CodeLabRuntime,
23889
26528
  Shell: root.CodeLabShell,
23890
26529
  Terminal: root.CodeLabTerminal,
26530
+ zip: root.CodeLabZip || null,
26531
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
26532
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
26533
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
26534
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
26535
+ storage: root.CodeLabStorage || null,
26536
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
26537
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
26538
+ search: root.CodeLabSearch || null,
26539
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
26540
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
26541
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
26542
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
26543
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
26544
+ diagnostics: root.CodeLabDiagnostics || null,
26545
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
26546
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
26547
+ scm: root.CodeLabScm || null,
26548
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
26549
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
26550
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
26551
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
26552
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
26553
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
23891
26554
  renderMarkdown: renderSimpleMarkdown,
23892
26555
  renderSimpleMarkdown: renderSimpleMarkdown,
23893
26556
  extensions: {
@@ -23938,6 +26601,7 @@ const createVirtualFs = CodeLabRuntime.createVirtualFs;
23938
26601
  const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
23939
26602
  const createVirtualNet = CodeLabRuntime.createVirtualNet;
23940
26603
  const createVirtualPortTable = CodeLabRuntime.createVirtualPortTable;
26604
+ const createWorkerRuntimeSource = CodeLabRuntime.createWorkerRuntimeSource;
23941
26605
  const createPosixShell = CodeLabShell ? CodeLabShell.createPosixShell : null;
23942
26606
  const cloneGitHubRepository = CodeLabShell ? CodeLabShell.cloneGitHubRepository : null;
23943
26607
  const parseGitHubRepoUrl = CodeLabShell ? CodeLabShell.parseGitHubRepoUrl : null;
@@ -23948,11 +26612,46 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
23948
26612
  const mount = CodeLab ? CodeLab.mount : null;
23949
26613
  const create = CodeLab ? CodeLab.create : null;
23950
26614
  const unmount = CodeLab ? CodeLab.unmount : null;
23951
- const version = CodeLab ? CodeLab.version : '2.0.0';
26615
+ const version = CodeLab ? CodeLab.version : '0.1.8';
23952
26616
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
23953
26617
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
23954
26618
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
23955
26619
  const extensions = CodeLab ? CodeLab.extensions : null;
26620
+ const CodeLabError = CodeLabLogger.CodeLabError;
26621
+ const isCodeLabError = CodeLabLogger.isCodeLabError;
26622
+ const createLogger = CodeLabLogger.createLogger;
26623
+ const DEFAULT_LOGGER = CodeLabLogger.DEFAULT_LOGGER;
26624
+ const LOG_PREFIX = CodeLabLogger.LOG_PREFIX;
26625
+ const Logger = CodeLab ? CodeLab.Logger : CodeLabLogger;
26626
+ const html = CodeLabHtml.html;
26627
+ const raw = CodeLabHtml.raw;
26628
+ const isSafeHtml = CodeLabHtml.isSafeHtml;
26629
+ const escapeHtml = CodeLabHtml.escapeHtml;
26630
+ const Html = CodeLab ? CodeLab.Html : CodeLabHtml;
26631
+ const zip = CodeLabZip;
26632
+ const createZip = CodeLabZip.createZip;
26633
+ const extractZip = CodeLabZip.extractZip;
26634
+ const computeCrc32 = CodeLabZip.computeCrc32;
26635
+ const sanitizeZipPath = CodeLabZip.sanitizeZipPath;
26636
+ const storage = CodeLabStorage;
26637
+ const WorkspaceStorage = CodeLabStorage.WorkspaceStorage;
26638
+ const createWorkspaceStorage = CodeLabStorage.createWorkspaceStorage;
26639
+ const search = CodeLabSearch;
26640
+ const searchInFiles = CodeLabSearch.searchInFiles;
26641
+ const replaceInFiles = CodeLabSearch.replaceInFiles;
26642
+ const matchesGlob = CodeLabSearch.matchesGlob;
26643
+ const escapeRegex = CodeLabSearch.escapeRegex;
26644
+ const normalizeSearchPath = CodeLabSearch.normalizeSearchPath;
26645
+ const diagnostics = CodeLabDiagnostics;
26646
+ const DiagnosticsStore = CodeLabDiagnostics.DiagnosticsStore;
26647
+ const createDiagnosticsStore = CodeLabDiagnostics.createDiagnosticsStore;
26648
+ const scm = CodeLabScm;
26649
+ const createGitState = CodeLabScm.createGitState;
26650
+ const computeGitStatus = CodeLabScm.computeGitStatus;
26651
+ const stageFile = CodeLabScm.stageFile;
26652
+ const unstageFile = CodeLabScm.unstageFile;
26653
+ const commitChanges = CodeLabScm.commitChanges;
26654
+ const computeShortCommitHash = CodeLabScm.computeShortCommitHash;
23956
26655
 
23957
26656
  export {
23958
26657
  CodeLab,
@@ -23973,6 +26672,49 @@ export {
23973
26672
  renderSimpleMarkdown,
23974
26673
  cloneRepo,
23975
26674
  extensions,
26675
+ CodeLabCsp,
26676
+ CodeLabLogger,
26677
+ Logger,
26678
+ CodeLabHtml,
26679
+ Html,
26680
+ html,
26681
+ raw,
26682
+ isSafeHtml,
26683
+ escapeHtml,
26684
+ CodeLabError,
26685
+ isCodeLabError,
26686
+ createLogger,
26687
+ DEFAULT_LOGGER,
26688
+ LOG_PREFIX,
26689
+ CodeLabZip,
26690
+ zip,
26691
+ createZip,
26692
+ extractZip,
26693
+ computeCrc32,
26694
+ sanitizeZipPath,
26695
+ CodeLabStorage,
26696
+ storage,
26697
+ WorkspaceStorage,
26698
+ createWorkspaceStorage,
26699
+ CodeLabSearch,
26700
+ search,
26701
+ searchInFiles,
26702
+ replaceInFiles,
26703
+ matchesGlob,
26704
+ escapeRegex,
26705
+ normalizeSearchPath,
26706
+ CodeLabDiagnostics,
26707
+ diagnostics,
26708
+ DiagnosticsStore,
26709
+ createDiagnosticsStore,
26710
+ CodeLabScm,
26711
+ scm,
26712
+ createGitState,
26713
+ computeGitStatus,
26714
+ stageFile,
26715
+ unstageFile,
26716
+ commitChanges,
26717
+ computeShortCommitHash,
23976
26718
  createPosixShell,
23977
26719
  cloneGitHubRepository,
23978
26720
  parseGitHubRepoUrl,
@@ -23988,6 +26730,7 @@ export {
23988
26730
  createVirtualFs,
23989
26731
  createVirtualHttp,
23990
26732
  createVirtualNet,
23991
- createVirtualPortTable
26733
+ createVirtualPortTable,
26734
+ createWorkerRuntimeSource
23992
26735
  };
23993
26736
  export default CodeLab;