@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
package/dist/code-lab.js CHANGED
@@ -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
@@ -17,8 +17,1681 @@
17
17
  (function (root) {
18
18
  'use strict';
19
19
 
20
+ // --- Module 0: Preview CSP, Structured Logger, Safe HTML & Leaf Engines ---
21
+ var CodeLabCsp = (() => {
22
+ var __defProp = Object.defineProperty;
23
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
24
+ var __getOwnPropNames = Object.getOwnPropertyNames;
25
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
26
+ var __export = (target, all) => {
27
+ for (var name in all)
28
+ __defProp(target, name, { get: all[name], enumerable: true });
29
+ };
30
+ var __copyProps = (to, from, except, desc) => {
31
+ if (from && typeof from === "object" || typeof from === "function") {
32
+ for (let key of __getOwnPropNames(from))
33
+ if (!__hasOwnProp.call(to, key) && key !== except)
34
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
35
+ }
36
+ return to;
37
+ };
38
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
39
+
40
+ // src/csp.ts
41
+ var csp_exports = {};
42
+ __export(csp_exports, {
43
+ PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
44
+ buildPreviewPolicy: () => buildPreviewPolicy,
45
+ buildPreviewShims: () => buildPreviewShims,
46
+ default: () => csp_default,
47
+ describePreviewNetwork: () => describePreviewNetwork,
48
+ normalizeOrigin: () => normalizeOrigin,
49
+ normalizePreviewCspConfig: () => normalizePreviewCspConfig
50
+ });
51
+ var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
52
+ var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
53
+ var PRESETS = {
54
+ strict: {},
55
+ balanced: {
56
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
57
+ styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
58
+ fontSrc: FONT_CDNS.slice(),
59
+ connectSrc: IMPORT_MAP_CDNS.slice(),
60
+ imgSrc: ["https://cdn.jsdelivr.net"]
61
+ }
62
+ };
63
+ var SOURCE_KEYS = [
64
+ "scriptSrc",
65
+ "styleSrc",
66
+ "imgSrc",
67
+ "fontSrc",
68
+ "connectSrc",
69
+ "mediaSrc",
70
+ "workerSrc",
71
+ "frameSrc"
72
+ ];
73
+ var MAX_SOURCES = 64;
74
+ var MAX_SOURCE_LENGTH = 512;
75
+ var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
76
+ function normalizeOrigin(raw) {
77
+ if (raw === null || raw === void 0 || raw === "") return null;
78
+ try {
79
+ const parsed = new URL(String(raw));
80
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
81
+ return parsed.origin;
82
+ } catch (_) {
83
+ return null;
84
+ }
85
+ }
86
+ function normalizeMode(raw) {
87
+ if (raw === "strict" || raw === "custom") return raw;
88
+ return "balanced";
89
+ }
90
+ var ALLOWED_KEYWORDS = [
91
+ "'self'",
92
+ "'none'",
93
+ "'unsafe-inline'",
94
+ "'unsafe-eval'",
95
+ "'wasm-unsafe-eval'",
96
+ "'strict-dynamic'",
97
+ "'unsafe-hashes'"
98
+ ];
99
+ var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
100
+ function isSafeSource(source) {
101
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
102
+ }
103
+ function cleanSources(raw) {
104
+ if (!Array.isArray(raw)) return [];
105
+ const out = [];
106
+ for (const value of raw.slice(0, MAX_SOURCES)) {
107
+ if (typeof value !== "string") continue;
108
+ const source = value.trim();
109
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
110
+ if (!isSafeSource(source)) continue;
111
+ if (out.indexOf(source) === -1) out.push(source);
112
+ }
113
+ return out;
114
+ }
115
+ function unique(...lists) {
116
+ const out = [];
117
+ for (const list of lists) {
118
+ if (!list) continue;
119
+ for (const value of list) {
120
+ if (value && out.indexOf(value) === -1) out.push(value);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ function normalizePreviewCspConfig(raw) {
126
+ if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
127
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
128
+ return { mode: "balanced", allow: {} };
129
+ }
130
+ const input = raw;
131
+ const nested = input.allow;
132
+ const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
133
+ const allow = {};
134
+ for (const key of SOURCE_KEYS) {
135
+ const list = cleanSources(sources[key]);
136
+ if (list.length) allow[key] = list;
137
+ }
138
+ return { mode: normalizeMode(input.mode), allow };
139
+ }
140
+ function sourcesFor(mode, allow, key) {
141
+ const preset = mode === "custom" ? {} : PRESETS[mode];
142
+ return unique(preset[key], cleanSources(allow[key]));
143
+ }
144
+ function buildPreviewPolicy(options = {}) {
145
+ const mode = normalizeMode(options.mode);
146
+ const allow = options;
147
+ const host = normalizeOrigin(options.hostOrigin);
148
+ const self = host || "'self'";
149
+ const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
150
+ const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
151
+ const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
152
+ const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
153
+ return [
154
+ directive("default-src", [self, "data:", "blob:"]),
155
+ directive("base-uri", [self]),
156
+ "object-src 'none'",
157
+ directive("script-src", script()),
158
+ directive("style-src", style()),
159
+ directive("img-src", withData("imgSrc")),
160
+ directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
161
+ directive("connect-src", withData("connectSrc")),
162
+ directive("media-src", withData("mediaSrc")),
163
+ directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
164
+ directive("frame-src", withData("frameSrc")),
165
+ directive("form-action", [self]),
166
+ directive("frame-ancestors", [options.frameAncestors || "'self'"])
167
+ ].join("; ");
168
+ }
169
+ function describePreviewNetwork(config) {
170
+ const normalized = normalizePreviewCspConfig(config);
171
+ if (normalized.mode === "strict") return [];
172
+ const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
173
+ const hosts = [];
174
+ for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
175
+ for (const source of unique(preset[key], normalized.allow[key])) {
176
+ if (!/^https?:\/\//i.test(source)) continue;
177
+ let host;
178
+ try {
179
+ host = new URL(source).host;
180
+ } catch (_) {
181
+ continue;
182
+ }
183
+ if (hosts.indexOf(host) === -1) hosts.push(host);
184
+ }
185
+ }
186
+ return hosts;
187
+ }
188
+ function buildPreviewShims() {
189
+ return `<script ${PREVIEW_SHIM_MARKER}>
190
+ (function () {
191
+ 'use strict';
192
+ function memoryStorage() {
193
+ var data = new Map();
194
+ return {
195
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
196
+ setItem: function (k, v) { data.set(String(k), String(v)); },
197
+ removeItem: function (k) { data.delete(String(k)); },
198
+ clear: function () { data.clear(); },
199
+ key: function (i) { return Array.from(data.keys())[i] || null; },
200
+ get length() { return data.size; }
201
+ };
202
+ }
203
+ function shim(name) {
204
+ var blocked = false;
205
+ try {
206
+ var existing = window[name];
207
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
208
+ } catch (err) {
209
+ // Expected on an opaque origin: the accessor itself throws.
210
+ blocked = Boolean(err);
211
+ }
212
+ void blocked;
213
+ try {
214
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
215
+ } catch (err) {
216
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
217
+ }
218
+ }
219
+ shim('localStorage');
220
+ shim('sessionStorage');
221
+ document.addEventListener('securitypolicyviolation', function (event) {
222
+ try {
223
+ parent.postMessage({
224
+ type: 'codelab:preview-violation',
225
+ directive: event.effectiveDirective || event.violatedDirective || '',
226
+ blockedURI: event.blockedURI || '',
227
+ sourceFile: event.sourceFile || '',
228
+ line: event.lineNumber || 0
229
+ }, '*');
230
+ } catch (err) {
231
+ console.warn('[code-lab] preview: could not report CSP violation', err);
232
+ }
233
+ });
234
+ function serializeArg(arg) {
235
+ if (typeof arg !== 'object' || arg === null) return String(arg);
236
+ try {
237
+ return JSON.stringify(arg);
238
+ } catch (err) {
239
+ void err;
240
+ return '[Circular/Unserializable]';
241
+ }
242
+ }
243
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
244
+ var orig = console[level];
245
+ if (typeof orig !== 'function') return;
246
+ console[level] = function () {
247
+ var args = Array.prototype.slice.call(arguments);
248
+ try {
249
+ parent.postMessage({
250
+ type: 'codelab:preview-console',
251
+ level: level,
252
+ args: args.map(serializeArg)
253
+ }, '*');
254
+ } catch (err) {
255
+ void err;
256
+ }
257
+ return orig.apply(console, args);
258
+ };
259
+ });
260
+ function showPreviewErrorOverlay(msg, stack) {
261
+ try {
262
+ if (!document || !document.body) return;
263
+ var existing = document.getElementById('codelab-preview-error-overlay');
264
+ if (!existing) {
265
+ existing = document.createElement('div');
266
+ existing.id = 'codelab-preview-error-overlay';
267
+ 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;';
268
+ document.body.appendChild(existing);
269
+ }
270
+ existing.textContent = '';
271
+ var header = document.createElement('div');
272
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
273
+ header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
274
+ var pre = document.createElement('pre');
275
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
276
+ pre.textContent = String(stack || msg || '');
277
+ existing.appendChild(header);
278
+ existing.appendChild(pre);
279
+ } catch (err) {
280
+ void err;
281
+ }
282
+ }
283
+ window.addEventListener('error', function (event) {
284
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
285
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
286
+ showPreviewErrorOverlay(msg, stack);
287
+ try {
288
+ parent.postMessage({
289
+ type: 'codelab:preview-error',
290
+ message: msg,
291
+ file: (event && event.filename) || null,
292
+ line: (event && event.lineno) || null,
293
+ col: (event && event.colno) || null,
294
+ stack: stack || null
295
+ }, '*');
296
+ } catch (err) {
297
+ void err;
298
+ }
299
+ });
300
+ window.addEventListener('unhandledrejection', function (event) {
301
+ var reason = event ? event.reason : null;
302
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
303
+ var stack = reason && reason.stack ? String(reason.stack) : '';
304
+ showPreviewErrorOverlay(msg, stack);
305
+ try {
306
+ parent.postMessage({
307
+ type: 'codelab:preview-error',
308
+ message: msg,
309
+ file: null,
310
+ line: null,
311
+ col: null,
312
+ stack: stack || null
313
+ }, '*');
314
+ } catch (err) {
315
+ void err;
316
+ }
317
+ });
318
+ })();
319
+ <\/script>`;
320
+ }
321
+ var csp_default = {
322
+ buildPreviewPolicy,
323
+ buildPreviewShims,
324
+ describePreviewNetwork,
325
+ normalizePreviewCspConfig,
326
+ normalizeOrigin,
327
+ PREVIEW_SHIM_MARKER
328
+ };
329
+ return __toCommonJS(csp_exports);
330
+ })();
331
+
332
+ var CodeLabLogger = (() => {
333
+ var __defProp = Object.defineProperty;
334
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
335
+ var __getOwnPropNames = Object.getOwnPropertyNames;
336
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
337
+ var __export = (target, all) => {
338
+ for (var name in all)
339
+ __defProp(target, name, { get: all[name], enumerable: true });
340
+ };
341
+ var __copyProps = (to, from, except, desc) => {
342
+ if (from && typeof from === "object" || typeof from === "function") {
343
+ for (let key of __getOwnPropNames(from))
344
+ if (!__hasOwnProp.call(to, key) && key !== except)
345
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
346
+ }
347
+ return to;
348
+ };
349
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
350
+
351
+ // src/logger.ts
352
+ var logger_exports = {};
353
+ __export(logger_exports, {
354
+ CodeLabError: () => CodeLabError,
355
+ DEFAULT_LOGGER: () => DEFAULT_LOGGER,
356
+ LOG_PREFIX: () => LOG_PREFIX,
357
+ createLogger: () => createLogger,
358
+ default: () => logger_default,
359
+ isCodeLabError: () => isCodeLabError
360
+ });
361
+ var LOG_PREFIX = "[code-lab]";
362
+ var CodeLabError = class extends Error {
363
+ code;
364
+ options;
365
+ cause;
366
+ recoverable;
367
+ details;
368
+ context;
369
+ constructor(code, message, options = {}) {
370
+ super(message);
371
+ this.name = "CodeLabError";
372
+ this.code = code;
373
+ this.options = options;
374
+ this.cause = options.cause;
375
+ this.recoverable = options.recoverable !== false;
376
+ const meta = options.details ?? options.context;
377
+ if (meta !== void 0) {
378
+ this.details = meta;
379
+ this.context = meta;
380
+ }
381
+ Object.setPrototypeOf(this, new.target.prototype);
382
+ }
383
+ };
384
+ function isCodeLabError(value) {
385
+ return Boolean(
386
+ value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
387
+ );
388
+ }
389
+ function createLogger(options = {}) {
390
+ const sink = options.logger ?? null;
391
+ const debugEnabled = options.debug === true;
392
+ const prefix = options.prefix || LOG_PREFIX;
393
+ const write = (level, args) => {
394
+ if (level === "debug" && !debugEnabled) return;
395
+ if (sink && typeof sink[level] === "function") {
396
+ let sinkError = null;
397
+ try {
398
+ sink[level](...args);
399
+ return;
400
+ } catch (err) {
401
+ sinkError = err;
402
+ }
403
+ }
404
+ const consoleObj = typeof console !== "undefined" ? console : null;
405
+ const fn = consoleObj ? consoleObj[level] : null;
406
+ if (typeof fn === "function") {
407
+ fn.call(consoleObj, prefix, ...args);
408
+ }
409
+ };
410
+ return {
411
+ debug: (...args) => write("debug", args),
412
+ info: (...args) => write("info", args),
413
+ warn: (...args) => write("warn", args),
414
+ error: (...args) => write("error", args)
415
+ };
416
+ }
417
+ var DEFAULT_LOGGER = createLogger();
418
+ var _loggerNamespace = {
419
+ LOG_PREFIX,
420
+ CodeLabError,
421
+ isCodeLabError,
422
+ createLogger,
423
+ DEFAULT_LOGGER
424
+ };
425
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
426
+ if (_globalRoot && !_globalRoot.CodeLabLogger) {
427
+ _globalRoot.CodeLabLogger = _loggerNamespace;
428
+ }
429
+ var logger_default = _loggerNamespace;
430
+ return __toCommonJS(logger_exports);
431
+ })();
432
+
433
+ var CodeLabHtml = (() => {
434
+ var __defProp = Object.defineProperty;
435
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
436
+ var __getOwnPropNames = Object.getOwnPropertyNames;
437
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
438
+ var __export = (target, all) => {
439
+ for (var name in all)
440
+ __defProp(target, name, { get: all[name], enumerable: true });
441
+ };
442
+ var __copyProps = (to, from, except, desc) => {
443
+ if (from && typeof from === "object" || typeof from === "function") {
444
+ for (let key of __getOwnPropNames(from))
445
+ if (!__hasOwnProp.call(to, key) && key !== except)
446
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
447
+ }
448
+ return to;
449
+ };
450
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
451
+
452
+ // src/html.ts
453
+ var html_exports = {};
454
+ __export(html_exports, {
455
+ default: () => html_default,
456
+ escapeHtml: () => escapeHtml,
457
+ html: () => html,
458
+ isSafeHtml: () => isSafeHtml,
459
+ raw: () => raw
460
+ });
461
+ var SAFE_HTML_BRAND = Symbol.for("codelab.SafeHtml");
462
+ var SafeHtmlImpl = class {
463
+ [SAFE_HTML_BRAND] = true;
464
+ __html;
465
+ constructor(trusted) {
466
+ this.__html = String(trusted);
467
+ }
468
+ toString() {
469
+ return this.__html;
470
+ }
471
+ };
472
+ function isSafeHtml(value) {
473
+ return Boolean(
474
+ value && typeof value === "object" && value[SAFE_HTML_BRAND] === true && typeof value.__html === "string"
475
+ );
476
+ }
477
+ function escapeHtml(value) {
478
+ if (value === null || value === void 0) return "";
479
+ if (isSafeHtml(value)) return value.__html;
480
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
481
+ }
482
+ function raw(trustedHtml) {
483
+ return new SafeHtmlImpl(trustedHtml);
484
+ }
485
+ function renderInterpolation(value) {
486
+ if (value === null || value === void 0 || value === false) return "";
487
+ if (isSafeHtml(value)) return value.__html;
488
+ if (Array.isArray(value)) {
489
+ let out = "";
490
+ for (let i = 0; i < value.length; i++) {
491
+ out += renderInterpolation(value[i]);
492
+ }
493
+ return out;
494
+ }
495
+ return escapeHtml(value);
496
+ }
497
+ function html(strings, ...values) {
498
+ let out = strings[0] ?? "";
499
+ for (let i = 0; i < values.length; i++) {
500
+ out += renderInterpolation(values[i]);
501
+ out += strings[i + 1] ?? "";
502
+ }
503
+ return new SafeHtmlImpl(out);
504
+ }
505
+ var _htmlNamespace = {
506
+ escapeHtml,
507
+ raw,
508
+ isSafeHtml,
509
+ html
510
+ };
511
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
512
+ if (_globalRoot && !_globalRoot.CodeLabHtml) {
513
+ _globalRoot.CodeLabHtml = _htmlNamespace;
514
+ }
515
+ var html_default = _htmlNamespace;
516
+ return __toCommonJS(html_exports);
517
+ })();
518
+
519
+ var CodeLabZip = (() => {
520
+ var __defProp = Object.defineProperty;
521
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
522
+ var __getOwnPropNames = Object.getOwnPropertyNames;
523
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
524
+ var __export = (target, all) => {
525
+ for (var name in all)
526
+ __defProp(target, name, { get: all[name], enumerable: true });
527
+ };
528
+ var __copyProps = (to, from, except, desc) => {
529
+ if (from && typeof from === "object" || typeof from === "function") {
530
+ for (let key of __getOwnPropNames(from))
531
+ if (!__hasOwnProp.call(to, key) && key !== except)
532
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
533
+ }
534
+ return to;
535
+ };
536
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
537
+
538
+ // src/zip.ts
539
+ var zip_exports = {};
540
+ __export(zip_exports, {
541
+ computeCrc32: () => computeCrc32,
542
+ createZip: () => createZip,
543
+ default: () => zip_default,
544
+ extractZip: () => extractZip,
545
+ sanitizeZipPath: () => sanitizeZipPath,
546
+ toUint8Array: () => toUint8Array
547
+ });
548
+ var LOCAL_FILE_HEADER_SIG = 67324752;
549
+ var CENTRAL_DIR_HEADER_SIG = 33639248;
550
+ var END_OF_CENTRAL_DIR_SIG = 101010256;
551
+ var UTF8_FLAG = 2048;
552
+ var CRC32_TABLE = new Uint32Array(256);
553
+ for (let i = 0; i < 256; i++) {
554
+ let c = i;
555
+ for (let k = 0; k < 8; k++) {
556
+ c = (c & 1) !== 0 ? 3988292384 ^ c >>> 1 : c >>> 1;
557
+ }
558
+ CRC32_TABLE[i] = c >>> 0;
559
+ }
560
+ var textEncoder = new TextEncoder();
561
+ var textDecoder = new TextDecoder("utf-8");
562
+ function toUint8Array(input) {
563
+ if (typeof input === "string") {
564
+ return textEncoder.encode(input);
565
+ }
566
+ if (input instanceof Uint8Array) {
567
+ return input;
568
+ }
569
+ if (input instanceof ArrayBuffer) {
570
+ return new Uint8Array(input);
571
+ }
572
+ return new Uint8Array(0);
573
+ }
574
+ function computeCrc32(data) {
575
+ const bytes = toUint8Array(data);
576
+ let crc = 4294967295;
577
+ for (let i = 0; i < bytes.length; i++) {
578
+ const index = (crc ^ bytes[i]) & 255;
579
+ crc = crc >>> 8 ^ CRC32_TABLE[index];
580
+ }
581
+ return (crc ^ 4294967295) >>> 0;
582
+ }
583
+ function sanitizeZipPath(rawPath) {
584
+ const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
585
+ const parts = normalized.split("/");
586
+ const safeParts = [];
587
+ for (const part of parts) {
588
+ const trimmed = part.trim();
589
+ if (!trimmed || trimmed === ".") continue;
590
+ if (trimmed === "..") {
591
+ if (safeParts.length > 0) {
592
+ safeParts.pop();
593
+ }
594
+ continue;
595
+ }
596
+ safeParts.push(trimmed);
597
+ }
598
+ return safeParts.join("/");
599
+ }
600
+ function writeUInt16LE(buf, offset, value) {
601
+ buf[offset] = value & 255;
602
+ buf[offset + 1] = value >>> 8 & 255;
603
+ }
604
+ function writeUInt32LE(buf, offset, value) {
605
+ buf[offset] = value & 255;
606
+ buf[offset + 1] = value >>> 8 & 255;
607
+ buf[offset + 2] = value >>> 16 & 255;
608
+ buf[offset + 3] = value >>> 24 & 255;
609
+ }
610
+ function readUInt16LE(buf, offset) {
611
+ return (buf[offset] | buf[offset + 1] << 8) >>> 0;
612
+ }
613
+ function readUInt32LE(buf, offset) {
614
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
615
+ }
616
+ async function createZip(files) {
617
+ const entries = [];
618
+ let localSectionSize = 0;
619
+ let centralDirSize = 0;
620
+ const rawKeys = Object.keys(files || {});
621
+ for (const rawKey of rawKeys) {
622
+ const safePath = sanitizeZipPath(rawKey);
623
+ if (!safePath) continue;
624
+ const rawContent = files[rawKey];
625
+ const dataBytes = toUint8Array(rawContent);
626
+ const nameBytes = textEncoder.encode(safePath);
627
+ const crc = computeCrc32(dataBytes);
628
+ entries.push({
629
+ nameBytes,
630
+ dataBytes,
631
+ crc32: crc,
632
+ offset: localSectionSize
633
+ });
634
+ localSectionSize += 30 + nameBytes.length + dataBytes.length;
635
+ centralDirSize += 46 + nameBytes.length;
636
+ }
637
+ const totalSize = localSectionSize + centralDirSize + 22;
638
+ const out = new Uint8Array(totalSize);
639
+ let cursor = 0;
640
+ for (const entry of entries) {
641
+ writeUInt32LE(out, cursor, LOCAL_FILE_HEADER_SIG);
642
+ writeUInt16LE(out, cursor + 4, 20);
643
+ writeUInt16LE(out, cursor + 6, UTF8_FLAG);
644
+ writeUInt16LE(out, cursor + 8, 0);
645
+ writeUInt16LE(out, cursor + 10, 0);
646
+ writeUInt16LE(out, cursor + 12, 8448);
647
+ writeUInt32LE(out, cursor + 14, entry.crc32);
648
+ writeUInt32LE(out, cursor + 18, entry.dataBytes.length);
649
+ writeUInt32LE(out, cursor + 22, entry.dataBytes.length);
650
+ writeUInt16LE(out, cursor + 26, entry.nameBytes.length);
651
+ writeUInt16LE(out, cursor + 28, 0);
652
+ cursor += 30;
653
+ out.set(entry.nameBytes, cursor);
654
+ cursor += entry.nameBytes.length;
655
+ out.set(entry.dataBytes, cursor);
656
+ cursor += entry.dataBytes.length;
657
+ }
658
+ const centralDirOffset = cursor;
659
+ for (const entry of entries) {
660
+ writeUInt32LE(out, cursor, CENTRAL_DIR_HEADER_SIG);
661
+ writeUInt16LE(out, cursor + 4, 20);
662
+ writeUInt16LE(out, cursor + 6, 20);
663
+ writeUInt16LE(out, cursor + 8, UTF8_FLAG);
664
+ writeUInt16LE(out, cursor + 10, 0);
665
+ writeUInt16LE(out, cursor + 12, 0);
666
+ writeUInt16LE(out, cursor + 14, 8448);
667
+ writeUInt32LE(out, cursor + 16, entry.crc32);
668
+ writeUInt32LE(out, cursor + 20, entry.dataBytes.length);
669
+ writeUInt32LE(out, cursor + 24, entry.dataBytes.length);
670
+ writeUInt16LE(out, cursor + 28, entry.nameBytes.length);
671
+ writeUInt16LE(out, cursor + 30, 0);
672
+ writeUInt16LE(out, cursor + 32, 0);
673
+ writeUInt16LE(out, cursor + 34, 0);
674
+ writeUInt16LE(out, cursor + 36, 0);
675
+ writeUInt32LE(out, cursor + 38, 0);
676
+ writeUInt32LE(out, cursor + 42, entry.offset);
677
+ cursor += 46;
678
+ out.set(entry.nameBytes, cursor);
679
+ cursor += entry.nameBytes.length;
680
+ }
681
+ writeUInt32LE(out, cursor, END_OF_CENTRAL_DIR_SIG);
682
+ writeUInt16LE(out, cursor + 4, 0);
683
+ writeUInt16LE(out, cursor + 6, 0);
684
+ writeUInt16LE(out, cursor + 8, entries.length);
685
+ writeUInt16LE(out, cursor + 10, entries.length);
686
+ writeUInt32LE(out, cursor + 12, centralDirSize);
687
+ writeUInt32LE(out, cursor + 16, centralDirOffset);
688
+ writeUInt16LE(out, cursor + 20, 0);
689
+ return out;
690
+ }
691
+ async function extractZip(data) {
692
+ const bytes = toUint8Array(data);
693
+ if (bytes.length < 22) {
694
+ throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
695
+ }
696
+ let eocdOffset = -1;
697
+ const minSearchOffset = Math.max(0, bytes.length - 65557);
698
+ for (let i = bytes.length - 22; i >= minSearchOffset; i--) {
699
+ if (readUInt32LE(bytes, i) === END_OF_CENTRAL_DIR_SIG) {
700
+ eocdOffset = i;
701
+ break;
702
+ }
703
+ }
704
+ if (eocdOffset === -1) {
705
+ throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
706
+ }
707
+ const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
708
+ const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
709
+ const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
710
+ if (centralDirOffset + centralDirSize > bytes.length) {
711
+ throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
712
+ }
713
+ const result = {};
714
+ let cdCursor = centralDirOffset;
715
+ for (let i = 0; i < totalEntries; i++) {
716
+ if (cdCursor + 46 > bytes.length) {
717
+ throw new Error("Corrupted ZIP archive: truncated Central Directory header");
718
+ }
719
+ const sig = readUInt32LE(bytes, cdCursor);
720
+ if (sig !== CENTRAL_DIR_HEADER_SIG) {
721
+ throw new Error(`Corrupted ZIP archive: invalid Central Directory signature 0x${sig.toString(16)}`);
722
+ }
723
+ const compressionMethod = readUInt16LE(bytes, cdCursor + 10);
724
+ const expectedCrc = readUInt32LE(bytes, cdCursor + 16);
725
+ const compressedSize = readUInt32LE(bytes, cdCursor + 20);
726
+ const fileNameLen = readUInt16LE(bytes, cdCursor + 28);
727
+ const extraLen = readUInt16LE(bytes, cdCursor + 30);
728
+ const commentLen = readUInt16LE(bytes, cdCursor + 32);
729
+ const localHeaderOffset = readUInt32LE(bytes, cdCursor + 42);
730
+ const nameStart = cdCursor + 46;
731
+ const nameEnd = nameStart + fileNameLen;
732
+ if (nameEnd > bytes.length) {
733
+ throw new Error("Corrupted ZIP archive: file name exceeds buffer");
734
+ }
735
+ const rawName = textDecoder.decode(bytes.subarray(nameStart, nameEnd));
736
+ cdCursor = nameEnd + extraLen + commentLen;
737
+ if (rawName.endsWith("/")) continue;
738
+ const safeName = sanitizeZipPath(rawName);
739
+ if (!safeName) continue;
740
+ if (localHeaderOffset + 30 > bytes.length) {
741
+ throw new Error(`Corrupted ZIP archive: local header offset out of bounds for ${safeName}`);
742
+ }
743
+ const localSig = readUInt32LE(bytes, localHeaderOffset);
744
+ if (localSig !== LOCAL_FILE_HEADER_SIG) {
745
+ throw new Error(`Corrupted ZIP archive: invalid Local File Header signature for ${safeName}`);
746
+ }
747
+ const localNameLen = readUInt16LE(bytes, localHeaderOffset + 26);
748
+ const localExtraLen = readUInt16LE(bytes, localHeaderOffset + 28);
749
+ const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
750
+ const dataEnd = dataStart + compressedSize;
751
+ if (dataEnd > bytes.length) {
752
+ throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
753
+ }
754
+ const rawFileBytes = bytes.subarray(dataStart, dataEnd);
755
+ if (compressionMethod !== 0) {
756
+ throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
757
+ }
758
+ const actualCrc = computeCrc32(rawFileBytes);
759
+ if (actualCrc !== expectedCrc) {
760
+ throw new Error(
761
+ `CRC32 integrity mismatch for ${safeName}: expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)}`
762
+ );
763
+ }
764
+ result[safeName] = textDecoder.decode(rawFileBytes);
765
+ }
766
+ return result;
767
+ }
768
+ var zip_default = {
769
+ createZip,
770
+ extractZip,
771
+ computeCrc32,
772
+ sanitizeZipPath,
773
+ toUint8Array
774
+ };
775
+ return __toCommonJS(zip_exports);
776
+ })();
777
+
778
+ var CodeLabStorage = (() => {
779
+ var __defProp = Object.defineProperty;
780
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
781
+ var __getOwnPropNames = Object.getOwnPropertyNames;
782
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
783
+ var __export = (target, all) => {
784
+ for (var name in all)
785
+ __defProp(target, name, { get: all[name], enumerable: true });
786
+ };
787
+ var __copyProps = (to, from, except, desc) => {
788
+ if (from && typeof from === "object" || typeof from === "function") {
789
+ for (let key of __getOwnPropNames(from))
790
+ if (!__hasOwnProp.call(to, key) && key !== except)
791
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
792
+ }
793
+ return to;
794
+ };
795
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
796
+
797
+ // src/storage.ts
798
+ var storage_exports = {};
799
+ __export(storage_exports, {
800
+ WorkspaceStorage: () => WorkspaceStorage,
801
+ createWorkspaceStorage: () => createWorkspaceStorage,
802
+ default: () => storage_default
803
+ });
804
+ var DEFAULT_DB_NAME = "codelab_workspace_db";
805
+ var DEFAULT_STORE_NAME = "projects";
806
+ var DEFAULT_LS_PREFIX = "codelab:project:";
807
+ function cloneProject(project) {
808
+ const filesCopy = {};
809
+ if (project.files && typeof project.files === "object") {
810
+ for (const [k, v] of Object.entries(project.files)) {
811
+ filesCopy[k] = String(v);
812
+ }
813
+ }
814
+ return {
815
+ id: String(project.id),
816
+ name: String(project.name || project.id),
817
+ files: filesCopy,
818
+ updatedAt: typeof project.updatedAt === "number" ? project.updatedAt : Date.now(),
819
+ ...project.createdAt !== void 0 ? { createdAt: project.createdAt } : {},
820
+ ...project.entry !== void 0 ? { entry: project.entry } : {},
821
+ ...project.testEntry !== void 0 ? { testEntry: project.testEntry } : {},
822
+ ...project.version !== void 0 ? { version: project.version } : {}
823
+ };
824
+ }
825
+ function isLocalStorageAvailable(prefix) {
826
+ try {
827
+ if (typeof globalThis === "undefined" || !("localStorage" in globalThis)) {
828
+ return false;
829
+ }
830
+ const ls = globalThis.localStorage;
831
+ if (!ls || typeof ls.getItem !== "function" || typeof ls.setItem !== "function") {
832
+ return false;
833
+ }
834
+ const probeKey = `${prefix}__probe__`;
835
+ ls.setItem(probeKey, "1");
836
+ ls.removeItem(probeKey);
837
+ return true;
838
+ } catch (err) {
839
+ const _ignored = err;
840
+ return false;
841
+ }
842
+ }
843
+ function isIndexedDbAvailable() {
844
+ try {
845
+ if (typeof globalThis === "undefined" || !("indexedDB" in globalThis)) {
846
+ return false;
847
+ }
848
+ return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === "function");
849
+ } catch (err) {
850
+ const _ignored = err;
851
+ return false;
852
+ }
853
+ }
854
+ var WorkspaceStorage = class {
855
+ dbName;
856
+ storeName;
857
+ storagePrefix;
858
+ backendType;
859
+ memoryStore = /* @__PURE__ */ new Map();
860
+ dbPromise = null;
861
+ constructor(options = {}) {
862
+ this.dbName = options.dbName || DEFAULT_DB_NAME;
863
+ this.storeName = options.storeName || DEFAULT_STORE_NAME;
864
+ this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
865
+ if (options.preferredBackend) {
866
+ this.backendType = options.preferredBackend;
867
+ } else if (isIndexedDbAvailable()) {
868
+ this.backendType = "indexeddb";
869
+ } else if (isLocalStorageAvailable(this.storagePrefix)) {
870
+ this.backendType = "localstorage";
871
+ } else {
872
+ this.backendType = "memory";
873
+ }
874
+ }
875
+ getBackendType() {
876
+ return this.backendType;
877
+ }
878
+ openIdb() {
879
+ if (this.dbPromise) return this.dbPromise;
880
+ this.dbPromise = new Promise((resolve) => {
881
+ try {
882
+ const req = globalThis.indexedDB.open(this.dbName, 1);
883
+ req.onupgradeneeded = () => {
884
+ const db = req.result;
885
+ if (!db.objectStoreNames.contains(this.storeName)) {
886
+ db.createObjectStore(this.storeName, { keyPath: "id" });
887
+ }
888
+ };
889
+ req.onsuccess = () => {
890
+ resolve(req.result);
891
+ };
892
+ req.onerror = () => {
893
+ resolve(null);
894
+ };
895
+ } catch (err) {
896
+ const _ignored = err;
897
+ resolve(null);
898
+ }
899
+ });
900
+ return this.dbPromise;
901
+ }
902
+ downgradeFromIdb() {
903
+ if (isLocalStorageAvailable(this.storagePrefix)) {
904
+ this.backendType = "localstorage";
905
+ } else {
906
+ this.backendType = "memory";
907
+ }
908
+ }
909
+ async saveProject(project) {
910
+ if (!project || typeof project.id !== "string" || !project.id.trim()) {
911
+ return false;
912
+ }
913
+ const normalized = cloneProject(project);
914
+ this.memoryStore.set(normalized.id, normalized);
915
+ if (this.backendType === "indexeddb") {
916
+ const db = await this.openIdb();
917
+ if (!db) {
918
+ this.downgradeFromIdb();
919
+ } else {
920
+ const ok = await new Promise((resolve) => {
921
+ try {
922
+ const tx = db.transaction(this.storeName, "readwrite");
923
+ const store = tx.objectStore(this.storeName);
924
+ const req = store.put(normalized);
925
+ req.onsuccess = () => resolve(true);
926
+ req.onerror = () => resolve(false);
927
+ } catch (err) {
928
+ const _ignored = err;
929
+ resolve(false);
930
+ }
931
+ });
932
+ if (ok) return true;
933
+ this.downgradeFromIdb();
934
+ }
935
+ }
936
+ if (this.backendType === "localstorage") {
937
+ try {
938
+ const key = `${this.storagePrefix}${normalized.id}`;
939
+ globalThis.localStorage.setItem(key, JSON.stringify(normalized));
940
+ return true;
941
+ } catch (err) {
942
+ const _ignored = err;
943
+ this.backendType = "memory";
944
+ }
945
+ }
946
+ return true;
947
+ }
948
+ async loadProject(id) {
949
+ if (!id || typeof id !== "string") return null;
950
+ if (this.backendType === "indexeddb") {
951
+ const db = await this.openIdb();
952
+ if (!db) {
953
+ this.downgradeFromIdb();
954
+ } else {
955
+ const found = await new Promise((resolve) => {
956
+ try {
957
+ const tx = db.transaction(this.storeName, "readonly");
958
+ const store = tx.objectStore(this.storeName);
959
+ const req = store.get(id);
960
+ req.onsuccess = () => {
961
+ const res = req.result;
962
+ resolve(res ? cloneProject(res) : null);
963
+ };
964
+ req.onerror = () => resolve(null);
965
+ } catch (err) {
966
+ const _ignored = err;
967
+ resolve(null);
968
+ }
969
+ });
970
+ if (found) return found;
971
+ }
972
+ }
973
+ if (this.backendType === "localstorage") {
974
+ try {
975
+ const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
976
+ if (raw) {
977
+ const parsed = JSON.parse(raw);
978
+ if (parsed && typeof parsed.id === "string" && parsed.files && typeof parsed.files === "object") {
979
+ return cloneProject(parsed);
980
+ }
981
+ }
982
+ } catch (err) {
983
+ const _ignored = err;
984
+ }
985
+ }
986
+ const fromMem = this.memoryStore.get(id);
987
+ return fromMem ? cloneProject(fromMem) : null;
988
+ }
989
+ async listProjects() {
990
+ const byId = /* @__PURE__ */ new Map();
991
+ const recordSummary = (proj) => {
992
+ if (!proj || typeof proj.id !== "string") return;
993
+ byId.set(proj.id, {
994
+ id: proj.id,
995
+ name: proj.name || proj.id,
996
+ updatedAt: typeof proj.updatedAt === "number" ? proj.updatedAt : Date.now(),
997
+ fileCount: proj.files && typeof proj.files === "object" ? Object.keys(proj.files).length : 0
998
+ });
999
+ };
1000
+ for (const p of this.memoryStore.values()) {
1001
+ recordSummary(p);
1002
+ }
1003
+ if (this.backendType === "indexeddb") {
1004
+ const db = await this.openIdb();
1005
+ if (db) {
1006
+ await new Promise((resolve) => {
1007
+ try {
1008
+ const tx = db.transaction(this.storeName, "readonly");
1009
+ const store = tx.objectStore(this.storeName);
1010
+ const req = store.getAll();
1011
+ req.onsuccess = () => {
1012
+ const items = Array.isArray(req.result) ? req.result : [];
1013
+ for (const item of items) {
1014
+ recordSummary(item);
1015
+ }
1016
+ resolve();
1017
+ };
1018
+ req.onerror = () => resolve();
1019
+ } catch (err) {
1020
+ const _ignored = err;
1021
+ resolve();
1022
+ }
1023
+ });
1024
+ }
1025
+ } else if (this.backendType === "localstorage") {
1026
+ try {
1027
+ const ls = globalThis.localStorage;
1028
+ for (let i = 0; i < ls.length; i++) {
1029
+ const key = ls.key(i);
1030
+ if (key && key.startsWith(this.storagePrefix)) {
1031
+ const raw = ls.getItem(key);
1032
+ if (raw) {
1033
+ try {
1034
+ const parsed = JSON.parse(raw);
1035
+ recordSummary(parsed);
1036
+ } catch (parseErr) {
1037
+ const _ignored = parseErr;
1038
+ }
1039
+ }
1040
+ }
1041
+ }
1042
+ } catch (err) {
1043
+ const _ignored = err;
1044
+ }
1045
+ }
1046
+ return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
1047
+ }
1048
+ async deleteProject(id) {
1049
+ if (!id || typeof id !== "string") return false;
1050
+ let existed = this.memoryStore.delete(id);
1051
+ if (this.backendType === "indexeddb") {
1052
+ const db = await this.openIdb();
1053
+ if (db) {
1054
+ const idbDeleted = await new Promise((resolve) => {
1055
+ try {
1056
+ const tx = db.transaction(this.storeName, "readwrite");
1057
+ const store = tx.objectStore(this.storeName);
1058
+ const checkReq = store.get(id);
1059
+ checkReq.onsuccess = () => {
1060
+ if (!checkReq.result) {
1061
+ resolve(false);
1062
+ return;
1063
+ }
1064
+ const delReq = store.delete(id);
1065
+ delReq.onsuccess = () => resolve(true);
1066
+ delReq.onerror = () => resolve(false);
1067
+ };
1068
+ checkReq.onerror = () => resolve(false);
1069
+ } catch (err) {
1070
+ const _ignored = err;
1071
+ resolve(false);
1072
+ }
1073
+ });
1074
+ existed = existed || idbDeleted;
1075
+ }
1076
+ }
1077
+ if (this.backendType === "localstorage") {
1078
+ try {
1079
+ const key = `${this.storagePrefix}${id}`;
1080
+ if (globalThis.localStorage.getItem(key) !== null) {
1081
+ globalThis.localStorage.removeItem(key);
1082
+ existed = true;
1083
+ }
1084
+ } catch (err) {
1085
+ const _ignored = err;
1086
+ }
1087
+ }
1088
+ return existed;
1089
+ }
1090
+ };
1091
+ function createWorkspaceStorage(options = {}) {
1092
+ return new WorkspaceStorage(options);
1093
+ }
1094
+ var storage_default = {
1095
+ WorkspaceStorage,
1096
+ createWorkspaceStorage
1097
+ };
1098
+ return __toCommonJS(storage_exports);
1099
+ })();
1100
+
1101
+ var CodeLabSearch = (() => {
1102
+ var __defProp = Object.defineProperty;
1103
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1104
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1105
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1106
+ var __export = (target, all) => {
1107
+ for (var name in all)
1108
+ __defProp(target, name, { get: all[name], enumerable: true });
1109
+ };
1110
+ var __copyProps = (to, from, except, desc) => {
1111
+ if (from && typeof from === "object" || typeof from === "function") {
1112
+ for (let key of __getOwnPropNames(from))
1113
+ if (!__hasOwnProp.call(to, key) && key !== except)
1114
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1115
+ }
1116
+ return to;
1117
+ };
1118
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1119
+
1120
+ // src/search.ts
1121
+ var search_exports = {};
1122
+ __export(search_exports, {
1123
+ escapeRegex: () => escapeRegex,
1124
+ matchesGlob: () => matchesGlob,
1125
+ normalizeSearchPath: () => normalizeSearchPath,
1126
+ replaceInFiles: () => replaceInFiles,
1127
+ searchInFiles: () => searchInFiles
1128
+ });
1129
+ function escapeRegex(text) {
1130
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1131
+ }
1132
+ function normalizeSearchPath(filePath) {
1133
+ let p = filePath.replace(/\\/g, "/");
1134
+ while (p.startsWith("./")) {
1135
+ p = p.slice(2);
1136
+ }
1137
+ while (p.startsWith("/")) {
1138
+ p = p.slice(1);
1139
+ }
1140
+ return p;
1141
+ }
1142
+ function matchesGlob(filePath, pattern) {
1143
+ if (!pattern || pattern === "*" || pattern === "**") return true;
1144
+ const normPath = normalizeSearchPath(filePath);
1145
+ const normPattern = normalizeSearchPath(pattern);
1146
+ if (normPattern === normPath) return true;
1147
+ if (!normPattern.includes("*") && !normPattern.includes("?")) {
1148
+ return normPath.includes(normPattern) || normPath.endsWith(normPattern);
1149
+ }
1150
+ let regexStr = "^";
1151
+ let i = 0;
1152
+ while (i < normPattern.length) {
1153
+ const c = normPattern[i];
1154
+ if (c === "*") {
1155
+ if (normPattern[i + 1] === "*") {
1156
+ regexStr += ".*";
1157
+ i += 2;
1158
+ if (normPattern[i] === "/") {
1159
+ i++;
1160
+ }
1161
+ continue;
1162
+ } else {
1163
+ regexStr += "[^/]*";
1164
+ i++;
1165
+ continue;
1166
+ }
1167
+ } else if (c === "?") {
1168
+ regexStr += "[^/]";
1169
+ i++;
1170
+ continue;
1171
+ } else if ("./+^$()|[]{}\\".includes(c)) {
1172
+ regexStr += "\\" + c;
1173
+ i++;
1174
+ continue;
1175
+ } else {
1176
+ regexStr += c;
1177
+ i++;
1178
+ }
1179
+ }
1180
+ regexStr += "$";
1181
+ try {
1182
+ const re = new RegExp(regexStr);
1183
+ return re.test(normPath);
1184
+ } catch (err) {
1185
+ return normPath.includes(normPattern.replace(/[*?]/g, ""));
1186
+ }
1187
+ }
1188
+ function checkFilter(path, filter) {
1189
+ if (!filter) return true;
1190
+ if (Array.isArray(filter)) {
1191
+ return filter.some((f) => matchesGlob(path, f));
1192
+ }
1193
+ return matchesGlob(path, filter);
1194
+ }
1195
+ function createSearchResult(groups, totalMatches, fileCount, query, error) {
1196
+ const arr = [...groups];
1197
+ const result = Object.assign(arr, {
1198
+ matches: groups,
1199
+ totalMatches,
1200
+ fileCount,
1201
+ filesCount: fileCount,
1202
+ query,
1203
+ durationMs: 0,
1204
+ error
1205
+ });
1206
+ return result;
1207
+ }
1208
+ function searchInFiles(files, queryOrOptions, optionsOrUndefined) {
1209
+ let query = "";
1210
+ let opts = {};
1211
+ if (typeof queryOrOptions === "string") {
1212
+ query = queryOrOptions;
1213
+ opts = optionsOrUndefined || {};
1214
+ } else if (queryOrOptions && typeof queryOrOptions === "object") {
1215
+ opts = queryOrOptions;
1216
+ query = opts.query || "";
1217
+ }
1218
+ if (!query) {
1219
+ return createSearchResult([], 0, 0, query);
1220
+ }
1221
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1222
+ const isWholeWord = Boolean(opts.wholeWord);
1223
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1224
+ const maxMatches = opts.maxMatches ?? 1e4;
1225
+ const maxMatchesPerFile = opts.maxMatchesPerFile ?? 1e3;
1226
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1227
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1228
+ let patternStr = isRegex ? query : escapeRegex(query);
1229
+ if (isWholeWord) {
1230
+ patternStr = `\\b${patternStr}\\b`;
1231
+ }
1232
+ let regex = /(?:)/;
1233
+ try {
1234
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1235
+ } catch (err) {
1236
+ const _err = err;
1237
+ const msg = typeof _err === "object" && _err && "message" in _err ? String(_err.message) : "Invalid regular expression";
1238
+ return createSearchResult([], 0, 0, query, msg);
1239
+ }
1240
+ const matchedGroups = [];
1241
+ let totalMatches = 0;
1242
+ for (const [filePath, content] of Object.entries(files)) {
1243
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1244
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1245
+ if (opts.targetFiles && !opts.targetFiles.includes(filePath)) continue;
1246
+ const fileMatches = [];
1247
+ const lines = content.split("\n");
1248
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1249
+ const lineText = lines[lineIndex];
1250
+ regex.lastIndex = 0;
1251
+ let m = null;
1252
+ while ((m = regex.exec(lineText)) !== null) {
1253
+ const matchLen = m[0].length;
1254
+ const col = m.index + 1;
1255
+ fileMatches.push({
1256
+ line: lineIndex + 1,
1257
+ col,
1258
+ column: col,
1259
+ length: matchLen,
1260
+ matchText: m[0],
1261
+ lineText,
1262
+ beforeSnippet: lineText.slice(0, m.index),
1263
+ afterSnippet: lineText.slice(m.index + matchLen),
1264
+ matchIndex: m.index,
1265
+ matchEndIndex: m.index + matchLen
1266
+ });
1267
+ totalMatches++;
1268
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1269
+ break;
1270
+ }
1271
+ if (matchLen === 0) {
1272
+ regex.lastIndex++;
1273
+ if (regex.lastIndex > lineText.length) {
1274
+ break;
1275
+ }
1276
+ }
1277
+ }
1278
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1279
+ break;
1280
+ }
1281
+ }
1282
+ if (fileMatches.length > 0) {
1283
+ matchedGroups.push({
1284
+ file: filePath,
1285
+ matches: fileMatches
1286
+ });
1287
+ }
1288
+ if (totalMatches >= maxMatches) {
1289
+ break;
1290
+ }
1291
+ }
1292
+ return createSearchResult(matchedGroups, totalMatches, matchedGroups.length, query);
1293
+ }
1294
+ function replaceInFiles(files, arg2, arg3, arg4) {
1295
+ let query = "";
1296
+ const replacement = typeof arg3 === "string" ? arg3 : "";
1297
+ let opts = {};
1298
+ let targetFiles = void 0;
1299
+ if (typeof arg2 === "string") {
1300
+ query = arg2;
1301
+ if (Array.isArray(arg4)) {
1302
+ targetFiles = arg4;
1303
+ } else if (arg4 && typeof arg4 === "object") {
1304
+ opts = arg4;
1305
+ targetFiles = opts.targetFiles;
1306
+ }
1307
+ } else if (arg2 && typeof arg2 === "object") {
1308
+ opts = arg2;
1309
+ query = opts.query || "";
1310
+ if (Array.isArray(arg4)) {
1311
+ targetFiles = arg4;
1312
+ } else {
1313
+ targetFiles = opts.targetFiles;
1314
+ }
1315
+ }
1316
+ if (!query) {
1317
+ return {
1318
+ updatedFiles: { ...files },
1319
+ replacedCount: 0,
1320
+ filesAffected: []
1321
+ };
1322
+ }
1323
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1324
+ const isWholeWord = Boolean(opts.wholeWord);
1325
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1326
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1327
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1328
+ let patternStr = isRegex ? query : escapeRegex(query);
1329
+ if (isWholeWord) {
1330
+ patternStr = `\\b${patternStr}\\b`;
1331
+ }
1332
+ let regex = /(?:)/;
1333
+ try {
1334
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1335
+ } catch (err) {
1336
+ return {
1337
+ updatedFiles: { ...files },
1338
+ replacedCount: 0,
1339
+ filesAffected: []
1340
+ };
1341
+ }
1342
+ const updatedFiles = { ...files };
1343
+ const filesAffected = [];
1344
+ let replacedCount = 0;
1345
+ for (const [filePath, content] of Object.entries(files)) {
1346
+ if (targetFiles && !targetFiles.includes(filePath)) continue;
1347
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1348
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1349
+ regex.lastIndex = 0;
1350
+ let countInFile = 0;
1351
+ let m;
1352
+ while ((m = regex.exec(content)) !== null) {
1353
+ countInFile++;
1354
+ if (m[0].length === 0) {
1355
+ regex.lastIndex++;
1356
+ if (regex.lastIndex > content.length) {
1357
+ break;
1358
+ }
1359
+ }
1360
+ }
1361
+ if (countInFile > 0) {
1362
+ regex.lastIndex = 0;
1363
+ let newContent;
1364
+ if (isRegex) {
1365
+ newContent = content.replace(regex, replacement);
1366
+ } else {
1367
+ newContent = content.replace(regex, () => replacement);
1368
+ }
1369
+ updatedFiles[filePath] = newContent;
1370
+ filesAffected.push(filePath);
1371
+ replacedCount += countInFile;
1372
+ }
1373
+ }
1374
+ return {
1375
+ updatedFiles,
1376
+ replacedCount,
1377
+ filesAffected
1378
+ };
1379
+ }
1380
+ return __toCommonJS(search_exports);
1381
+ })();
1382
+
1383
+ var CodeLabDiagnostics = (() => {
1384
+ var __defProp = Object.defineProperty;
1385
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1386
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1387
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1388
+ var __export = (target, all) => {
1389
+ for (var name in all)
1390
+ __defProp(target, name, { get: all[name], enumerable: true });
1391
+ };
1392
+ var __copyProps = (to, from, except, desc) => {
1393
+ if (from && typeof from === "object" || typeof from === "function") {
1394
+ for (let key of __getOwnPropNames(from))
1395
+ if (!__hasOwnProp.call(to, key) && key !== except)
1396
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1397
+ }
1398
+ return to;
1399
+ };
1400
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1401
+
1402
+ // src/diagnostics.ts
1403
+ var diagnostics_exports = {};
1404
+ __export(diagnostics_exports, {
1405
+ DiagnosticsStore: () => DiagnosticsStore,
1406
+ createDiagnosticsStore: () => createDiagnosticsStore,
1407
+ default: () => diagnostics_default
1408
+ });
1409
+ var DiagnosticsStore = class {
1410
+ items = /* @__PURE__ */ new Map();
1411
+ listeners = /* @__PURE__ */ new Set();
1412
+ add(item) {
1413
+ if (!item || typeof item.id !== "string" || !item.id) return;
1414
+ const normalized = {
1415
+ ...item,
1416
+ file: String(item.file || ""),
1417
+ line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
1418
+ col: typeof item.col === "number" && item.col > 0 ? Math.floor(item.col) : typeof item.column === "number" && item.column > 0 ? Math.floor(item.column) : 1,
1419
+ message: String(item.message || ""),
1420
+ severity: item.severity || "error"
1421
+ };
1422
+ this.items.set(normalized.id, normalized);
1423
+ this.notify();
1424
+ }
1425
+ remove(id) {
1426
+ if (this.items.delete(id)) {
1427
+ this.notify();
1428
+ }
1429
+ }
1430
+ clear(source) {
1431
+ if (source !== void 0 && source !== "") {
1432
+ let changed = false;
1433
+ for (const [id, item] of this.items.entries()) {
1434
+ if (item.source === source) {
1435
+ this.items.delete(id);
1436
+ changed = true;
1437
+ }
1438
+ }
1439
+ if (changed) {
1440
+ this.notify();
1441
+ }
1442
+ } else if (this.items.size > 0) {
1443
+ this.items.clear();
1444
+ this.notify();
1445
+ }
1446
+ }
1447
+ getAll() {
1448
+ return Array.from(this.items.values());
1449
+ }
1450
+ getByFile(file) {
1451
+ const out = [];
1452
+ for (const item of this.items.values()) {
1453
+ if (item.file === file) {
1454
+ out.push(item);
1455
+ }
1456
+ }
1457
+ return out;
1458
+ }
1459
+ subscribe(listener) {
1460
+ this.listeners.add(listener);
1461
+ return () => {
1462
+ this.listeners.delete(listener);
1463
+ };
1464
+ }
1465
+ notify() {
1466
+ if (this.listeners.size === 0) return;
1467
+ const snapshot = this.getAll();
1468
+ for (const listener of this.listeners) {
1469
+ try {
1470
+ listener(snapshot);
1471
+ } catch (err) {
1472
+ console.warn("[code-lab] diagnostics subscriber error:", err);
1473
+ }
1474
+ }
1475
+ }
1476
+ };
1477
+ function createDiagnosticsStore() {
1478
+ return new DiagnosticsStore();
1479
+ }
1480
+ var diagnostics_default = {
1481
+ DiagnosticsStore,
1482
+ createDiagnosticsStore
1483
+ };
1484
+ return __toCommonJS(diagnostics_exports);
1485
+ })();
1486
+
1487
+ var CodeLabScm = (() => {
1488
+ var __defProp = Object.defineProperty;
1489
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1490
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1491
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1492
+ var __export = (target, all) => {
1493
+ for (var name in all)
1494
+ __defProp(target, name, { get: all[name], enumerable: true });
1495
+ };
1496
+ var __copyProps = (to, from, except, desc) => {
1497
+ if (from && typeof from === "object" || typeof from === "function") {
1498
+ for (let key of __getOwnPropNames(from))
1499
+ if (!__hasOwnProp.call(to, key) && key !== except)
1500
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1501
+ }
1502
+ return to;
1503
+ };
1504
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1505
+
1506
+ // src/scm.ts
1507
+ var scm_exports = {};
1508
+ __export(scm_exports, {
1509
+ commitChanges: () => commitChanges,
1510
+ computeGitStatus: () => computeGitStatus,
1511
+ computeShortCommitHash: () => computeShortCommitHash,
1512
+ createGitState: () => createGitState,
1513
+ default: () => scm_default,
1514
+ stageFile: () => stageFile,
1515
+ unstageFile: () => unstageFile
1516
+ });
1517
+ function computeShortCommitHash(input) {
1518
+ let h1 = 3735928559 ^ input.length;
1519
+ let h2 = 1103547991 ^ input.length;
1520
+ for (let i = 0; i < input.length; i++) {
1521
+ const ch = input.charCodeAt(i);
1522
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1523
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1524
+ }
1525
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1526
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1527
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
1528
+ return combined.toString(16).padStart(7, "0").slice(0, 7);
1529
+ }
1530
+ function createGitState(initialFiles = {}, branch = "main") {
1531
+ const headFiles = { ...initialFiles };
1532
+ const initialHash = computeShortCommitHash(JSON.stringify(headFiles) + ":init");
1533
+ return {
1534
+ branch,
1535
+ branches: [branch],
1536
+ headCommit: initialHash,
1537
+ headFiles,
1538
+ staged: /* @__PURE__ */ new Map(),
1539
+ commits: [
1540
+ {
1541
+ hash: initialHash,
1542
+ message: "Initial commit",
1543
+ timestamp: Date.now(),
1544
+ files: { ...headFiles }
1545
+ }
1546
+ ]
1547
+ };
1548
+ }
1549
+ function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1550
+ const state = gitState || createGitState({});
1551
+ const headFiles = state.headFiles || {};
1552
+ const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1553
+ const untracked = [];
1554
+ const modified = [];
1555
+ const deleted = [];
1556
+ const staged = [];
1557
+ for (const [filePath, stagedContent] of currentStaged.entries()) {
1558
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1559
+ if (stagedContent === null) {
1560
+ staged.push({
1561
+ path: filePath,
1562
+ status: "deleted",
1563
+ staged: true,
1564
+ oldContent: headFiles[filePath]
1565
+ });
1566
+ } else {
1567
+ staged.push({
1568
+ path: filePath,
1569
+ status: inHead ? "modified" : "added",
1570
+ staged: true,
1571
+ oldContent: inHead ? headFiles[filePath] : void 0,
1572
+ newContent: stagedContent
1573
+ });
1574
+ }
1575
+ }
1576
+ for (const [filePath, content] of Object.entries(vfsFiles || {})) {
1577
+ if (currentStaged.has(filePath)) {
1578
+ const stagedVal = currentStaged.get(filePath);
1579
+ if (stagedVal !== content) {
1580
+ modified.push({
1581
+ path: filePath,
1582
+ status: "modified",
1583
+ staged: false,
1584
+ oldContent: stagedVal ?? void 0,
1585
+ newContent: content
1586
+ });
1587
+ }
1588
+ } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
1589
+ if (headFiles[filePath] !== content) {
1590
+ modified.push({
1591
+ path: filePath,
1592
+ status: "modified",
1593
+ staged: false,
1594
+ oldContent: headFiles[filePath],
1595
+ newContent: content
1596
+ });
1597
+ }
1598
+ } else {
1599
+ untracked.push({
1600
+ path: filePath,
1601
+ status: "untracked",
1602
+ staged: false,
1603
+ newContent: content
1604
+ });
1605
+ }
1606
+ }
1607
+ for (const filePath of Object.keys(headFiles)) {
1608
+ if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath) && !currentStaged.has(filePath)) {
1609
+ deleted.push({
1610
+ path: filePath,
1611
+ status: "deleted",
1612
+ staged: false,
1613
+ oldContent: headFiles[filePath]
1614
+ });
1615
+ }
1616
+ }
1617
+ const unstaged = [...modified, ...deleted];
1618
+ const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1619
+ return {
1620
+ branch: state.branch || "main",
1621
+ headCommit: state.headCommit || "",
1622
+ untracked,
1623
+ modified,
1624
+ deleted,
1625
+ staged,
1626
+ unstaged,
1627
+ hasChanges: !isClean,
1628
+ isClean
1629
+ };
1630
+ }
1631
+ function stageFile(gitState, relativePath, currentContent) {
1632
+ if (!gitState) return;
1633
+ if (!(gitState.staged instanceof Map)) {
1634
+ gitState.staged = /* @__PURE__ */ new Map();
1635
+ }
1636
+ gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1637
+ }
1638
+ function unstageFile(gitState, relativePath) {
1639
+ if (!gitState || !(gitState.staged instanceof Map)) return;
1640
+ gitState.staged.delete(relativePath);
1641
+ }
1642
+ function commitChanges(gitState, message) {
1643
+ const trimmed = typeof message === "string" ? message.trim() : "";
1644
+ if (!trimmed) {
1645
+ throw new Error("Commit message cannot be empty");
1646
+ }
1647
+ if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1648
+ throw new Error("Nothing to commit (staging area is empty)");
1649
+ }
1650
+ const newHeadFiles = { ...gitState.headFiles || {} };
1651
+ for (const [filePath, content] of gitState.staged.entries()) {
1652
+ if (content === null) {
1653
+ delete newHeadFiles[filePath];
1654
+ } else {
1655
+ newHeadFiles[filePath] = content;
1656
+ }
1657
+ }
1658
+ const timestamp = Date.now();
1659
+ const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1660
+ const commit = {
1661
+ hash,
1662
+ message: trimmed,
1663
+ timestamp,
1664
+ files: newHeadFiles
1665
+ };
1666
+ if (!Array.isArray(gitState.commits)) {
1667
+ gitState.commits = [];
1668
+ }
1669
+ gitState.commits.push(commit);
1670
+ gitState.headCommit = hash;
1671
+ gitState.headFiles = newHeadFiles;
1672
+ gitState.staged.clear();
1673
+ return hash;
1674
+ }
1675
+ var scm_default = {
1676
+ createGitState,
1677
+ computeGitStatus,
1678
+ stageFile,
1679
+ unstageFile,
1680
+ commitChanges,
1681
+ computeShortCommitHash
1682
+ };
1683
+ return __toCommonJS(scm_exports);
1684
+ })();
1685
+
1686
+ root.CodeLabZip = CodeLabZip;
1687
+ root.CodeLabStorage = CodeLabStorage;
1688
+ root.CodeLabSearch = CodeLabSearch;
1689
+ root.CodeLabDiagnostics = CodeLabDiagnostics;
1690
+ root.CodeLabScm = CodeLabScm;
1691
+
20
1692
  // --- Module 1: Runtime Engine ---
21
1693
  (function () {
1694
+ // @ts-nocheck
22
1695
  'use strict';
23
1696
  if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined') {
24
1697
  globalThis.Bun = { version: '1.1.20' };
@@ -40,6 +1713,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
40
1713
  */
41
1714
 
42
1715
  function __initVirtualRuntime(rootScope) {
1716
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
1717
+ ? rootScope.CodeLabLogger.createLogger()
1718
+ : {
1719
+ debug() {},
1720
+ info() {},
1721
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
1722
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
1723
+ };
43
1724
  // =========================================================================
44
1725
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
45
1726
  // =========================================================================
@@ -1599,7 +3280,7 @@ function __initVirtualRuntime(rootScope) {
1599
3280
  },
1600
3281
  final(cb) {
1601
3282
  if (fd !== null) {
1602
- try { fsShim.closeSync(fd); } catch (_) {}
3283
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1603
3284
  fd = null;
1604
3285
  }
1605
3286
  cb(null);
@@ -2119,7 +3800,9 @@ function __initVirtualRuntime(rootScope) {
2119
3800
  return pathname + search + hash;
2120
3801
  }
2121
3802
  return resolvedUrl.href;
2122
- } catch (_) {}
3803
+ } catch (err) {
3804
+ _runtimeLogger.debug('url.resolve fallback used', err);
3805
+ }
2123
3806
  }
2124
3807
  if (toStr.startsWith('/')) {
2125
3808
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2558,10 +4241,10 @@ function __initVirtualRuntime(rootScope) {
2558
4241
  for (const [port, entry] of Array.from(table.entries())) {
2559
4242
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2560
4243
  if (entry.server && typeof entry.server.close === 'function') {
2561
- try { entry.server.close(); } catch (_) {}
4244
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2562
4245
  }
2563
4246
  if (typeof entry.stop === 'function') {
2564
- try { entry.stop(); } catch (_) {}
4247
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2565
4248
  }
2566
4249
  // Avoid a double 'close' emission when entry.server.close() already
2567
4250
  // unregistered the port through unregisterServer().
@@ -3198,7 +4881,7 @@ function __initVirtualRuntime(rootScope) {
3198
4881
  },
3199
4882
  closeAllServers() {
3200
4883
  for (const s of Array.from(activeServers.values())) {
3201
- try { s.close(); } catch (_) {}
4884
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3202
4885
  }
3203
4886
  activeServers.clear();
3204
4887
  }
@@ -4024,7 +5707,7 @@ function __initVirtualRuntime(rootScope) {
4024
5707
 
4025
5708
  function closeAllServers() {
4026
5709
  for (const srv of servers.values()) {
4027
- try { srv.close(); } catch (_) {}
5710
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4028
5711
  }
4029
5712
  servers.clear();
4030
5713
  }
@@ -5104,7 +6787,9 @@ function __initVirtualRuntime(rootScope) {
5104
6787
  try {
5105
6788
  const pkgJson = JSON.parse(content);
5106
6789
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5107
- } catch (_) {}
6790
+ } catch (err) {
6791
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
6792
+ }
5108
6793
  continue;
5109
6794
  }
5110
6795
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5133,7 +6818,9 @@ function __initVirtualRuntime(rootScope) {
5133
6818
  const meta = await res.json();
5134
6819
  deps = Object.keys((meta && meta.dependencies) || {});
5135
6820
  }
5136
- } catch (_) {}
6821
+ } catch (err) {
6822
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
6823
+ }
5137
6824
  _npmMetadataCache.set(pkg, deps);
5138
6825
  }));
5139
6826
  for (const pkg of pending) {
@@ -5151,7 +6838,7 @@ function __initVirtualRuntime(rootScope) {
5151
6838
  continue;
5152
6839
  }
5153
6840
  if (typeof onProgress === 'function') {
5154
- try { onProgress(pkg); } catch (_) {}
6841
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5155
6842
  }
5156
6843
  if (typeof fetch === 'function') {
5157
6844
  try {
@@ -5161,7 +6848,9 @@ function __initVirtualRuntime(rootScope) {
5161
6848
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5162
6849
  loaded[pkg] = text;
5163
6850
  }
5164
- } catch (_) {}
6851
+ } catch (err) {
6852
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
6853
+ }
5165
6854
  }
5166
6855
  }
5167
6856
  return loaded;
@@ -5353,7 +7042,9 @@ function __initVirtualRuntime(rootScope) {
5353
7042
  const dir = VirtualPath.dirname(abs);
5354
7043
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5355
7044
  vfs.writeFileSync(abs, content);
5356
- } catch (_) {}
7045
+ } catch (err) {
7046
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
7047
+ }
5357
7048
  }
5358
7049
  }
5359
7050
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5798,7 +7489,7 @@ function __initVirtualRuntime(rootScope) {
5798
7489
  exitCode = Number(code) || 0;
5799
7490
  if (!hasExited) {
5800
7491
  hasExited = true;
5801
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7492
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5802
7493
  }
5803
7494
  if (syncExecDepth > 0) {
5804
7495
  throw new ProcessExitSignal(exitCode);
@@ -5831,8 +7522,8 @@ function __initVirtualRuntime(rootScope) {
5831
7522
  resourceTracker.inFlightHttp.clear();
5832
7523
 
5833
7524
  if (!isBackground) {
5834
- try { vhttp.closeAllServers(); } catch (_) {}
5835
- try { vnet.closeAllServers(); } catch (_) {}
7525
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
7526
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5836
7527
  }
5837
7528
  };
5838
7529
 
@@ -5942,10 +7633,10 @@ function __initVirtualRuntime(rootScope) {
5942
7633
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5943
7634
  } finally {
5944
7635
  for (const ae of hooksSnapshot.afterEachList) {
5945
- try { await ae(); } catch (_) {}
7636
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5946
7637
  }
5947
7638
  for (const af of hooksSnapshot.afterToRun) {
5948
- try { await af(); } catch (_) {}
7639
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5949
7640
  }
5950
7641
  hooksSnapshot.afterToRun.length = 0;
5951
7642
  }
@@ -5993,7 +7684,7 @@ function __initVirtualRuntime(rootScope) {
5993
7684
  const afters = [...suiteCtx.afterCallbacks];
5994
7685
  const cleanupTask = nodeTestChain.then(async () => {
5995
7686
  for (const af of afters) {
5996
- try { await af(); } catch (_) {}
7687
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5997
7688
  }
5998
7689
  });
5999
7690
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6039,7 +7730,7 @@ function __initVirtualRuntime(rootScope) {
6039
7730
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6040
7731
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6041
7732
  };
6042
- try { obs._cb(list, obs); } catch (_) {}
7733
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6043
7734
  }
6044
7735
  }
6045
7736
  }
@@ -6144,7 +7835,7 @@ function __initVirtualRuntime(rootScope) {
6144
7835
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6145
7836
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6146
7837
  };
6147
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
7838
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6148
7839
  }
6149
7840
  }
6150
7841
  }
@@ -7415,7 +9106,9 @@ function __initVirtualRuntime(rootScope) {
7415
9106
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7416
9107
  if (resolvedEntry) return resolvedEntry;
7417
9108
  }
7418
- } catch (_) {}
9109
+ } catch (err) {
9110
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
9111
+ }
7419
9112
  }
7420
9113
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7421
9114
  for (const idx of indexCandidates) {
@@ -7485,7 +9178,9 @@ function __initVirtualRuntime(rootScope) {
7485
9178
  if (found) return found;
7486
9179
  }
7487
9180
  }
7488
- } catch (_) {}
9181
+ } catch (err) {
9182
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
9183
+ }
7489
9184
  }
7490
9185
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7491
9186
  if (foundSub) return foundSub;
@@ -7527,7 +9222,9 @@ function __initVirtualRuntime(rootScope) {
7527
9222
  if (isLocal && activePortTable) {
7528
9223
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7529
9224
  }
7530
- } catch (_) {}
9225
+ } catch (err) {
9226
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
9227
+ }
7531
9228
 
7532
9229
  if (typeof globalThis.fetch === 'function') {
7533
9230
  return await globalThis.fetch(urlOrReq, init);
@@ -7694,7 +9391,9 @@ function __initVirtualRuntime(rootScope) {
7694
9391
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7695
9392
  try {
7696
9393
  return new AsyncFunction(...argNames, body);
7697
- } catch (_) {}
9394
+ } catch (asyncErr) {
9395
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
9396
+ }
7698
9397
  }
7699
9398
  if (
7700
9399
  err &&
@@ -7748,7 +9447,9 @@ function __initVirtualRuntime(rootScope) {
7748
9447
  if (signal && onAbort) {
7749
9448
  try {
7750
9449
  signal.removeEventListener('abort', onAbort);
7751
- } catch (_) {}
9450
+ } catch (err) {
9451
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
9452
+ }
7752
9453
  }
7753
9454
  };
7754
9455
 
@@ -7907,11 +9608,11 @@ function __initVirtualRuntime(rootScope) {
7907
9608
  }
7908
9609
  } finally {
7909
9610
  if (signal && signalListener) {
7910
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
9611
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7911
9612
  }
7912
9613
  if (!hasExited) {
7913
9614
  hasExited = true;
7914
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
9615
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7915
9616
  }
7916
9617
  for (const rawId of resourceTracker.allTimers) {
7917
9618
  clearTimeout(rawId);
@@ -8019,7 +9720,16 @@ function createWorkerRuntimeSource() {
8019
9720
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8020
9721
  }
8021
9722
 
8022
- const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
9723
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
9724
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
9725
+ ? _hostScope.CodeLabLogger.createLogger()
9726
+ : {
9727
+ debug() {},
9728
+ info() {},
9729
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
9730
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
9731
+ };
9732
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8023
9733
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8024
9734
 
8025
9735
  let _cachedWorkerUrl = null;
@@ -8043,7 +9753,7 @@ function _ensureWarmWorker() {
8043
9753
 
8044
9754
  function _destroyWarmWorker() {
8045
9755
  if (_warmWorker) {
8046
- try { _warmWorker.terminate(); } catch (_) {}
9756
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8047
9757
  _warmWorker = null;
8048
9758
  }
8049
9759
  _warmWorkerBusy = false;
@@ -8098,7 +9808,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8098
9808
 
8099
9809
  function releaseWorker(terminateWorker) {
8100
9810
  if (options.signal && abortListener) {
8101
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
9811
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8102
9812
  abortListener = null;
8103
9813
  }
8104
9814
  _activeWorkerJobs.delete(requestId);
@@ -8113,7 +9823,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8113
9823
  }
8114
9824
  }
8115
9825
  } else {
8116
- try { worker.terminate(); } catch (_) {}
9826
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8117
9827
  }
8118
9828
  }
8119
9829
 
@@ -8249,12 +9959,14 @@ if (typeof module !== 'undefined' && module.exports) {
8249
9959
  }
8250
9960
 
8251
9961
 
9962
+
8252
9963
  })();
8253
9964
 
8254
9965
  const CodeLabRuntime = root.CodeLabRuntime;
8255
9966
 
8256
9967
  // --- Module 2: POSIX Shell & Coreutils ---
8257
9968
  (function () {
9969
+ // @ts-nocheck
8258
9970
  /**
8259
9971
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
8260
9972
  *
@@ -8301,12 +10013,23 @@ if (typeof module !== 'undefined' && module.exports) {
8301
10013
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
8302
10014
  'use strict';
8303
10015
 
10016
+ const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
10017
+ ? root.CodeLabLogger.createLogger()
10018
+ : {
10019
+ debug() {},
10020
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
10021
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
10022
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
10023
+ };
10024
+
8304
10025
  function getRuntimeModule() {
8305
10026
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
8306
10027
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
8307
10028
  try {
8308
10029
  if (typeof require !== 'undefined') return require('./runtime.js');
8309
- } catch (_) {}
10030
+ } catch (err) {
10031
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
10032
+ }
8310
10033
  return null;
8311
10034
  }
8312
10035
 
@@ -8898,7 +10621,9 @@ if (typeof module !== 'undefined' && module.exports) {
8898
10621
  if (typeof vfs.statSync === 'function') {
8899
10622
  isDir = vfs.statSync(full).isDirectory();
8900
10623
  }
8901
- } catch (_) {}
10624
+ } catch (err) {
10625
+ _shellLogger.debug('Glob statSync failed.', full, err);
10626
+ }
8902
10627
 
8903
10628
  if (isDir) {
8904
10629
  traverse(full, rel);
@@ -10220,7 +11945,9 @@ if (typeof module !== 'undefined' && module.exports) {
10220
11945
  : name;
10221
11946
  try {
10222
11947
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
10223
- } catch (_) {}
11948
+ } catch (err) {
11949
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
11950
+ }
10224
11951
  }
10225
11952
  }
10226
11953
  }
@@ -10242,7 +11969,7 @@ if (typeof module !== 'undefined' && module.exports) {
10242
11969
  return 10 + depth * 0.1;
10243
11970
  }
10244
11971
 
10245
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
11972
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
10246
11973
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10247
11974
  if (onProgress) {
10248
11975
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -10324,8 +12051,9 @@ if (typeof module !== 'undefined' && module.exports) {
10324
12051
  }
10325
12052
  }
10326
12053
  }
10327
- } catch (_) {
12054
+ } catch (err) {
10328
12055
  // Network or rate limit error on api.github.com; proceed to Strategy B
12056
+ _shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
10329
12057
  }
10330
12058
 
10331
12059
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -10352,7 +12080,9 @@ if (typeof module !== 'undefined' && module.exports) {
10352
12080
  }
10353
12081
  }
10354
12082
  }
10355
- } catch (_) {}
12083
+ } catch (err) {
12084
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
12085
+ }
10356
12086
  }
10357
12087
 
10358
12088
  if (repoNotFound || !rawTreeEntries) {
@@ -10500,7 +12230,9 @@ if (typeof module !== 'undefined' && module.exports) {
10500
12230
  }));
10501
12231
  }
10502
12232
  }
10503
- } catch (_) {}
12233
+ } catch (err) {
12234
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
12235
+ }
10504
12236
 
10505
12237
  if (commits.length === 0) {
10506
12238
  commits = [
@@ -10532,6 +12264,23 @@ if (typeof module !== 'undefined' && module.exports) {
10532
12264
  };
10533
12265
  }
10534
12266
 
12267
+ // Public wrapper: guarantee an `error` progress event when the clone fails
12268
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
12269
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
12270
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
12271
+ try {
12272
+ return await _cloneGitHubRepository(repoInput, vfs, options);
12273
+ } catch (err) {
12274
+ if (onProgress) {
12275
+ onProgress({
12276
+ phase: 'error',
12277
+ message: err && err.message ? err.message : String(err)
12278
+ });
12279
+ }
12280
+ throw err;
12281
+ }
12282
+ }
12283
+
10535
12284
  // =========================================================================
10536
12285
  // Package Management Helpers (npm / bun virtual modules & scripts)
10537
12286
  // =========================================================================
@@ -10549,7 +12298,9 @@ if (typeof module !== 'undefined' && module.exports) {
10549
12298
  try {
10550
12299
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
10551
12300
  return { path: p, data: parsed };
10552
- } catch (_) {}
12301
+ } catch (err) {
12302
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
12303
+ }
10553
12304
  }
10554
12305
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
10555
12306
  }
@@ -10590,13 +12341,20 @@ if (typeof module !== 'undefined' && module.exports) {
10590
12341
  vfs.rmdirSync(dirPath);
10591
12342
  }
10592
12343
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
10593
- } catch (_) {}
12344
+ } catch (err) {
12345
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
12346
+ }
10594
12347
  }
10595
12348
 
10596
12349
  // ---------------------------------------------------------------------------
10597
12350
  // Real npm package installation via the jsDelivr CDN
10598
12351
  // ---------------------------------------------------------------------------
10599
12352
  const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
12353
+ const CDN_NPM_BASES = [
12354
+ 'https://cdn.jsdelivr.net/npm',
12355
+ 'https://unpkg.com',
12356
+ 'https://esm.sh'
12357
+ ];
10600
12358
 
10601
12359
  // Minimal offline registry, used only when the CDN is unreachable so common
10602
12360
  // demos still resolve without network access.
@@ -10742,16 +12500,23 @@ if (typeof module !== 'undefined' && module.exports) {
10742
12500
  }
10743
12501
 
10744
12502
  async function resolvePackageMetadata(fetchImpl, name, range) {
10745
- const urls = range
10746
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10747
- : [`${CDN_NPM_BASE}/${name}/package.json`];
10748
- for (const url of urls) {
10749
- const text = await fetchTextFromCdn(fetchImpl, url);
10750
- if (!text) continue;
10751
- try {
10752
- const parsed = JSON.parse(text);
10753
- if (parsed && parsed.version) return parsed;
10754
- } catch (_) {}
12503
+ for (const base of CDN_NPM_BASES) {
12504
+ const urls = range
12505
+ ? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
12506
+ : [`${base}/${name}/package.json`];
12507
+ for (const url of urls) {
12508
+ const text = await fetchTextFromCdn(fetchImpl, url);
12509
+ if (!text) continue;
12510
+ try {
12511
+ const parsed = JSON.parse(text);
12512
+ if (parsed && parsed.version) {
12513
+ parsed._resolvedCdnBase = base;
12514
+ return parsed;
12515
+ }
12516
+ } catch (err) {
12517
+ _shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
12518
+ }
12519
+ }
10755
12520
  }
10756
12521
  return null;
10757
12522
  }
@@ -10769,6 +12534,7 @@ if (typeof module !== 'undefined' && module.exports) {
10769
12534
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10770
12535
  }
10771
12536
 
12537
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
10772
12538
  const version = meta.version;
10773
12539
  const key = `${name}@${version}`;
10774
12540
  if (seen.has(key)) {
@@ -10816,7 +12582,7 @@ if (typeof module !== 'undefined' && module.exports) {
10816
12582
  frontier = [];
10817
12583
  if (batch.length === 0) break;
10818
12584
  const texts = await Promise.all(
10819
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
12585
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
10820
12586
  );
10821
12587
  for (let idx = 0; idx < batch.length; idx++) {
10822
12588
  const rel = batch[idx];
@@ -10840,7 +12606,7 @@ if (typeof module !== 'undefined' && module.exports) {
10840
12606
  }
10841
12607
  // The declared entry may be missing on the CDN; fall back to index.js.
10842
12608
  if (!files.some(f => f.rel === entry)) {
10843
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
12609
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
10844
12610
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10845
12611
  }
10846
12612
 
@@ -10887,7 +12653,9 @@ if (typeof module !== 'undefined' && module.exports) {
10887
12653
  // directory target would otherwise raise EISDIR).
10888
12654
  try {
10889
12655
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10890
- } catch (_) {}
12656
+ } catch (err) {
12657
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
12658
+ }
10891
12659
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10892
12660
  ctx.vfs.writeFileSync(full, f.content);
10893
12661
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10965,6 +12733,32 @@ if (typeof module !== 'undefined' && module.exports) {
10965
12733
  pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10966
12734
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10967
12735
 
12736
+ // Also maintain package-lock.json in the same directory for deterministic lockfile verification
12737
+ try {
12738
+ const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
12739
+ let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
12740
+ if (ctx.vfs.existsSync(lockPath)) {
12741
+ const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
12742
+ const parsedLock = JSON.parse(rawLock);
12743
+ if (parsedLock && typeof parsedLock === 'object') {
12744
+ lockData = parsedLock;
12745
+ if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
12746
+ }
12747
+ }
12748
+ for (const inst of installed) {
12749
+ if (inst && inst.name) {
12750
+ lockData.packages[`node_modules/${inst.name}`] = {
12751
+ version: inst.version || '1.0.0',
12752
+ resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
12753
+ };
12754
+ }
12755
+ }
12756
+ ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
12757
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
12758
+ } catch (err) {
12759
+ _shellLogger.debug('Could not write package-lock.json during installPackage.', err);
12760
+ }
12761
+
10968
12762
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10969
12763
  }
10970
12764
 
@@ -11162,7 +12956,9 @@ if (typeof module !== 'undefined' && module.exports) {
11162
12956
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
11163
12957
  if (parsed && parsed.version) return parsed.version;
11164
12958
  }
11165
- } catch (_) {}
12959
+ } catch (err) {
12960
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
12961
+ }
11166
12962
  try {
11167
12963
  for (const dir of [rootDir, '/workspace']) {
11168
12964
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -11171,7 +12967,9 @@ if (typeof module !== 'undefined' && module.exports) {
11171
12967
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
11172
12968
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
11173
12969
  }
11174
- } catch (_) {}
12970
+ } catch (err) {
12971
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
12972
+ }
11175
12973
  return 'latest';
11176
12974
  }
11177
12975
 
@@ -11209,7 +13007,7 @@ if (typeof module !== 'undefined' && module.exports) {
11209
13007
  if (dirFlag) {
11210
13008
  walk(full, depth + 1);
11211
13009
  } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
11212
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
13010
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
11213
13011
  }
11214
13012
  }
11215
13013
  };
@@ -11256,7 +13054,7 @@ if (typeof module !== 'undefined' && module.exports) {
11256
13054
 
11257
13055
  const handler = async (request) => {
11258
13056
  let pathname = '/';
11259
- try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
13057
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
11260
13058
  const rel = pathname.replace(/^\/+/, '');
11261
13059
  let target = PosixPath.join(rootDir, rel);
11262
13060
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -11295,7 +13093,9 @@ if (typeof module !== 'undefined' && module.exports) {
11295
13093
  if (rm && typeof rm.transpileForBrowser === 'function') {
11296
13094
  body = rm.transpileForBrowser(body, target);
11297
13095
  }
11298
- } catch (_) {}
13096
+ } catch (err) {
13097
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
13098
+ }
11299
13099
  }
11300
13100
 
11301
13101
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -11303,7 +13103,7 @@ if (typeof module !== 'undefined' && module.exports) {
11303
13103
 
11304
13104
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
11305
13105
  return portTable.registerServer(port, {
11306
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
13106
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
11307
13107
  fetch: handler,
11308
13108
  name: 'code-lab-serve',
11309
13109
  pid,
@@ -11416,7 +13216,9 @@ if (typeof module !== 'undefined' && module.exports) {
11416
13216
  let isDir = false;
11417
13217
  try {
11418
13218
  isDir = ctx.vfs.statSync(resolved).isDirectory();
11419
- } catch (_) {}
13219
+ } catch (err) {
13220
+ _shellLogger.debug('cd statSync failed.', resolved, err);
13221
+ }
11420
13222
 
11421
13223
  if (!isDir) {
11422
13224
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -11516,7 +13318,9 @@ if (typeof module !== 'undefined' && module.exports) {
11516
13318
  isDirectory = st.isDirectory();
11517
13319
  size = st.size;
11518
13320
  mtimeMs = st.mtimeMs || Date.now();
11519
- } catch (_) {}
13321
+ } catch (err) {
13322
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
13323
+ }
11520
13324
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
11521
13325
  });
11522
13326
 
@@ -11936,7 +13740,9 @@ if (typeof module !== 'undefined' && module.exports) {
11936
13740
  if (st.isDirectory()) walk(full);
11937
13741
  else targets.push(full);
11938
13742
  }
11939
- } catch (_) {}
13743
+ } catch (err) {
13744
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
13745
+ }
11940
13746
  }
11941
13747
  if (ctx.vfs.existsSync(absRoot)) {
11942
13748
  const st = ctx.vfs.statSync(absRoot);
@@ -12060,7 +13866,9 @@ if (typeof module !== 'undefined' && module.exports) {
12060
13866
  let isDir = false;
12061
13867
  try {
12062
13868
  isDir = ctx.vfs.statSync(full).isDirectory();
12063
- } catch (_) {}
13869
+ } catch (err) {
13870
+ _shellLogger.debug('find statSync skipped.', full, err);
13871
+ }
12064
13872
 
12065
13873
  const relPath = root === '.'
12066
13874
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -12079,7 +13887,7 @@ if (typeof module !== 'undefined' && module.exports) {
12079
13887
  // Root itself check
12080
13888
  if (ctx.vfs.existsSync(absRoot)) {
12081
13889
  let isDir = false;
12082
- try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (_) {}
13890
+ try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
12083
13891
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
12084
13892
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
12085
13893
  results.push(root);
@@ -12991,7 +14799,7 @@ if (typeof module !== 'undefined' && module.exports) {
12991
14799
  const isLast = i === entries.length - 1;
12992
14800
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
12993
14801
  let isDir = false;
12994
- try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (_) {}
14802
+ try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
12995
14803
 
12996
14804
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
12997
14805
 
@@ -13219,10 +15027,10 @@ if (typeof module !== 'undefined' && module.exports) {
13219
15027
  for (const s of ctx.shell.portTable.listServers()) {
13220
15028
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
13221
15029
  if (s.server && typeof s.server.close === 'function') {
13222
- try { s.server.close(); } catch (_) {}
15030
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
13223
15031
  }
13224
15032
  if (typeof s.stop === 'function') {
13225
- try { s.stop(); } catch (_) {}
15033
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
13226
15034
  }
13227
15035
  ctx.shell.portTable.unregisterServer(s.port);
13228
15036
  killedPort = true;
@@ -15513,12 +17321,14 @@ if (typeof module !== 'undefined' && module.exports) {
15513
17321
  };
15514
17322
  });
15515
17323
 
17324
+
15516
17325
  })();
15517
17326
 
15518
17327
  const CodeLabShell = root.CodeLabShell;
15519
17328
 
15520
17329
  // --- Module 3: PTY Terminal Engine ---
15521
17330
  (function () {
17331
+ // @ts-nocheck
15522
17332
  /**
15523
17333
  * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
15524
17334
  *
@@ -15553,6 +17363,16 @@ if (typeof module !== 'undefined' && module.exports) {
15553
17363
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
15554
17364
  'use strict';
15555
17365
 
17366
+ const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
17367
+ const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
17368
+ ? _termRoot.CodeLabLogger.createLogger()
17369
+ : {
17370
+ debug() {},
17371
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
17372
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
17373
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
17374
+ };
17375
+
15556
17376
  const ANSI_CODE_MAP = {
15557
17377
  1: 'cl-ansi-bold',
15558
17378
  2: 'cl-ansi-dim',
@@ -16093,7 +17913,7 @@ if (typeof module !== 'undefined' && module.exports) {
16093
17913
  if (!this.container || typeof this.container.querySelector !== 'function') return;
16094
17914
  const input = this.container.querySelector('#cl-repl-input');
16095
17915
  if (input && typeof input.focus === 'function') {
16096
- try { input.focus(); } catch (_) {}
17916
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
16097
17917
  }
16098
17918
  }
16099
17919
 
@@ -16117,9 +17937,9 @@ if (typeof module !== 'undefined' && module.exports) {
16117
17937
  }
16118
17938
  for (const entry of this._listeners) {
16119
17939
  if (typeof entry === 'function') {
16120
- try { entry(); } catch (_) {}
17940
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
16121
17941
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
16122
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
17942
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
16123
17943
  }
16124
17944
  }
16125
17945
  this._listeners = [];
@@ -16188,7 +18008,9 @@ if (typeof module !== 'undefined' && module.exports) {
16188
18008
  try {
16189
18009
  const res = this.onKey(e);
16190
18010
  if (res === false) return;
16191
- } catch (_) {}
18011
+ } catch (err) {
18012
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
18013
+ }
16192
18014
  }
16193
18015
 
16194
18016
  const key = e.key;
@@ -16341,7 +18163,7 @@ if (typeof module !== 'undefined' && module.exports) {
16341
18163
  this.replMode = false;
16342
18164
  }
16343
18165
  if (this.onInterrupt) {
16344
- try { this.onInterrupt(); } catch (_) {}
18166
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
16345
18167
  }
16346
18168
  this.render();
16347
18169
  return;
@@ -16542,7 +18364,9 @@ if (typeof module !== 'undefined' && module.exports) {
16542
18364
  if (typeof nextInput.setSelectionRange === 'function') {
16543
18365
  nextInput.setSelectionRange(this.cursor, this.cursor);
16544
18366
  }
16545
- } catch (_) {}
18367
+ } catch (err) {
18368
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
18369
+ }
16546
18370
  }
16547
18371
  }
16548
18372
  }
@@ -16566,12 +18390,14 @@ if (typeof module !== 'undefined' && module.exports) {
16566
18390
  };
16567
18391
  });
16568
18392
 
18393
+
16569
18394
  })();
16570
18395
 
16571
18396
  const CodeLabTerminal = root.CodeLabTerminal;
16572
18397
 
16573
18398
  // --- Module 4: IDE Workbench & Web Component ---
16574
18399
  (function () {
18400
+ // @ts-nocheck
16575
18401
  /* ═══════════════════════════════════════════════════════════════════════════
16576
18402
  @innovatorved/code-lab — Interactive Monaco IDE Workbench & Guided Lab UI
16577
18403
  Supports <code-lab> Custom Element + window.CodeLab.mount() API
@@ -16580,13 +18406,26 @@ if (typeof module !== 'undefined' && module.exports) {
16580
18406
  (function (root) {
16581
18407
  'use strict';
16582
18408
 
16583
- let terminalModule = null;
16584
- let shellModule = null;
16585
- let runtimeModule = null;
18409
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
18410
+ (root && root.CodeLabLogger) ||
18411
+ null;
18412
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
18413
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
18414
+ : () => {};
18415
+
18416
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18417
+ let shellModule = (root && root.CodeLabShell) || null;
18418
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
16586
18419
  if (typeof require === 'function') {
16587
- try { terminalModule = require('./terminal.js'); } catch (_) {}
16588
- try { shellModule = require('./shell.js'); } catch (_) {}
16589
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
18420
+ if (!terminalModule) {
18421
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
18422
+ }
18423
+ if (!shellModule) {
18424
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
18425
+ }
18426
+ if (!runtimeModule) {
18427
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
18428
+ }
16590
18429
  }
16591
18430
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
16592
18431
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -16615,6 +18454,10 @@ if (typeof module !== 'undefined' && module.exports) {
16615
18454
  const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
16616
18455
  const STORAGE_PREFIX = 'sd-codelab-v1:';
16617
18456
 
18457
+ // The bundler rewrites this literal from package.json at build time. Keeping
18458
+ // the fallback in sync lets tests require src/workbench.js directly.
18459
+ const CODELAB_VERSION = '0.1.8';
18460
+
16618
18461
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16619
18462
  const NODE_AMBIENT_DTS = `
16620
18463
  declare var require: (id: string) => any;
@@ -16941,7 +18784,14 @@ declare module 'bun:sqlite' {
16941
18784
  }
16942
18785
  `;
16943
18786
 
18787
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
18788
+ (root && root.CodeLabHtml) ||
18789
+ null;
18790
+
16944
18791
  function escapeHtml(str) {
18792
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
18793
+ return _sharedHtmlMod.escapeHtml(str);
18794
+ }
16945
18795
  if (str == null) return '';
16946
18796
  return String(str)
16947
18797
  .replace(/&/g, '&amp;')
@@ -16951,6 +18801,45 @@ declare module 'bun:sqlite' {
16951
18801
  .replace(/'/g, '&#39;');
16952
18802
  }
16953
18803
 
18804
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
18805
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
18806
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
18807
+ let out = strings[0] || '';
18808
+ for (let i = 0; i < values.length; i++) {
18809
+ const val = values[i];
18810
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
18811
+ out += strings[i + 1] || '';
18812
+ }
18813
+ return raw(out);
18814
+ });
18815
+
18816
+ // Schemes that may appear in a rendered href. Everything else
18817
+ // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
18818
+ const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
18819
+
18820
+ function sanitizeUrl(raw) {
18821
+ if (raw === null || raw === undefined) return '#';
18822
+ const trimmed = String(raw).trim();
18823
+ if (!trimmed) return '#';
18824
+
18825
+ // Browsers ignore C0 controls and zero-width characters while resolving a
18826
+ // scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
18827
+ // them before deciding what the scheme is, but return the original value
18828
+ // when it is safe.
18829
+ const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
18830
+ const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
18831
+
18832
+ if (!schemeMatch) {
18833
+ // No scheme: a fragment, an absolute path, or a relative path.
18834
+ // Backslashes are treated as slashes by the URL parser and can turn a
18835
+ // "relative" URL into a protocol-relative one, so reject those.
18836
+ if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
18837
+ return trimmed;
18838
+ }
18839
+
18840
+ return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
18841
+ }
18842
+
16954
18843
  function formatErrorText(err) {
16955
18844
  if (!err) return '';
16956
18845
  if (typeof err === 'string') return err;
@@ -17142,16 +19031,11 @@ declare module 'bun:sqlite' {
17142
19031
  if (!str) return '';
17143
19032
  let text = String(str);
17144
19033
 
17145
- // Markdown Links: [label](url "title") or [label](url)
17146
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17147
- const cleanUrl = url.trim();
17148
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17149
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`;
17150
- });
17151
-
17152
- // Autolinks: <https://...>
17153
- text = text.replace(/<(https?:\/\/[^>]+)>/g, (_, url) => {
17154
- return `<a href="${escapeHtml(url)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`;
19034
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
19035
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
19036
+ const cleanUrl = sanitizeUrl(url);
19037
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
19038
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
17155
19039
  });
17156
19040
 
17157
19041
  // Strikethrough: ~~del~~
@@ -17346,8 +19230,9 @@ declare module 'bun:sqlite' {
17346
19230
  // Normalize CRLF to LF
17347
19231
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
17348
19232
 
17349
- // Prevent raw custom elements from executing within markdown previews
17350
- text = text.replace(/<\/?code-lab(\s[^>]*)?>/gi, (m) => escapeHtml(m));
19233
+ // NUL delimits internal placeholders. Strip author-supplied NULs so
19234
+ // markdown cannot forge a code-block or autolink placeholder.
19235
+ text = text.replace(/\u0000/g, '');
17351
19236
 
17352
19237
  // Phase 1: Fenced Code Block Extraction
17353
19238
  const codeBlocks = [];
@@ -17370,6 +19255,25 @@ declare module 'bun:sqlite' {
17370
19255
  return `\x00INLINECODE_${idx}\x00`;
17371
19256
  });
17372
19257
 
19258
+ // Phase 2b: Autolinks are the only inline construct that uses angle
19259
+ // brackets. Extract them before raw HTML is neutralized, then restore the
19260
+ // anchors in Phase 7.
19261
+ const autolinks = [];
19262
+ text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
19263
+ const idx = autolinks.length;
19264
+ const safe = sanitizeUrl(url);
19265
+ autolinks.push(
19266
+ `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
19267
+ );
19268
+ return `\x00AUTOLINK_${idx}\x00`;
19269
+ });
19270
+
19271
+ // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
19272
+ // escaping that one character turns any author-supplied markup into text
19273
+ // without disturbing `>` blockquote syntax. From here on, every real tag
19274
+ // in the output is generated by this renderer.
19275
+ text = text.replace(/</g, '&lt;');
19276
+
17373
19277
  // Phase 3: GitHub Callout Alerts & Blockquotes
17374
19278
  const calloutBlocks = [];
17375
19279
  text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
@@ -17447,7 +19351,8 @@ declare module 'bun:sqlite' {
17447
19351
  .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
17448
19352
  .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
17449
19353
  .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
17450
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '');
19354
+ .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
19355
+ .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
17451
19356
 
17452
19357
  return finalHtml;
17453
19358
  }
@@ -17654,27 +19559,124 @@ declare module 'bun:sqlite' {
17654
19559
  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>'
17655
19560
  };
17656
19561
 
17657
- let _workbenchInstanceCounter = 0;
17658
- const _fallbackStorage = new Map();
19562
+ let _workbenchInstanceCounter = 0;
19563
+ const _fallbackStorage = new Map();
19564
+
19565
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
19566
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
19567
+ // there is exactly one policy implementation shared by both sides.
19568
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
19569
+ (root && root.CodeLabCsp) ||
19570
+ null;
19571
+
19572
+ function normalizePreviewCspOption(raw) {
19573
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
19574
+ return PreviewCsp.normalizePreviewCspConfig(raw);
19575
+ }
19576
+ return { mode: 'balanced', allow: {} };
19577
+ }
19578
+
19579
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
19580
+ // that ships, using it would silently *pretend* to isolate previews while the
19581
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
19582
+ const PREVIEW_RELAY_AVAILABLE = false;
19583
+
19584
+ function normalizePreviewOrigin(raw) {
19585
+ if (raw === null || raw === undefined || raw === '') return null;
19586
+ try {
19587
+ const parsed = new URL(String(raw));
19588
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
19589
+ return parsed.origin;
19590
+ } catch (_) {
19591
+ return null;
19592
+ }
19593
+ }
19594
+
19595
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
19596
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
19597
+ constructor(code, message, options = {}) {
19598
+ super(message);
19599
+ this.name = 'CodeLabError';
19600
+ this.code = code || 'E_CODELAB';
19601
+ this.module = options.module || 'workbench';
19602
+ this.context = options.context || {};
19603
+ if (options.cause !== undefined) this.cause = options.cause;
19604
+ }
19605
+ };
19606
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
19607
+
19608
+ // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
19609
+ // into their own telemetry; `options.debug` enables verbose output. Errors
19610
+ // are never silently discarded.
19611
+ function createLogger(options = {}) {
19612
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
19613
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
19614
+ }
19615
+ const sink = options.logger;
19616
+ const debugEnabled = options.debug === true;
19617
+
19618
+ const write = (level, args) => {
19619
+ if (level === 'debug' && !debugEnabled) return;
19620
+ if (sink && typeof sink[level] === 'function') {
19621
+ try {
19622
+ sink[level](...args);
19623
+ return;
19624
+ } catch (sinkErr) {
19625
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
19626
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
19627
+ }
19628
+ }
19629
+ const fn = typeof console !== 'undefined' ? console[level] : null;
19630
+ if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
19631
+ };
19632
+
19633
+ return {
19634
+ debug: (...args) => write('debug', args),
19635
+ info: (...args) => write('info', args),
19636
+ warn: (...args) => write('warn', args),
19637
+ error: (...args) => write('error', args)
19638
+ };
19639
+ }
19640
+
19641
+ const DEFAULT_LOGGER = createLogger();
17659
19642
 
17660
- function safeStorageGet(key) {
19643
+ function safeStorageGet(key, logger = DEFAULT_LOGGER) {
17661
19644
  try {
17662
19645
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17663
- return localStorage.getItem(key);
19646
+ const value = localStorage.getItem(key);
19647
+ if (value !== null && value !== undefined) return value;
17664
19648
  }
17665
- } catch (_) {}
19649
+ } catch (err) {
19650
+ logger.warn(
19651
+ `localStorage.getItem("${key}") failed; using in-memory state.`,
19652
+ err && err.message ? err.message : err
19653
+ );
19654
+ }
17666
19655
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17667
19656
  }
17668
19657
 
17669
- function safeStorageSet(key, value) {
19658
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
17670
19659
  const str = String(value);
17671
19660
  try {
17672
19661
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17673
19662
  localStorage.setItem(key, str);
17674
- return;
19663
+ return true;
19664
+ }
19665
+ } catch (err) {
19666
+ if (typeof onError === 'function') {
19667
+ onError(err);
19668
+ }
19669
+ if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
19670
+ if (!safeStorageSet._warnedKeys.has(key)) {
19671
+ safeStorageSet._warnedKeys.add(key);
19672
+ logger.warn(
19673
+ `localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
19674
+ err && err.message ? err.message : err
19675
+ );
17675
19676
  }
17676
- } catch (_) {}
19677
+ }
17677
19678
  _fallbackStorage.set(key, str);
19679
+ return false;
17678
19680
  }
17679
19681
 
17680
19682
  // ── CodeLabWorkbench Instance Class ──────────────────────────────────────
@@ -17685,12 +19687,25 @@ declare module 'bun:sqlite' {
17685
19687
  throw new Error('CodeLabWorkbench requires a valid DOM container element.');
17686
19688
  }
17687
19689
  this.options = options || {};
19690
+ this.logger = createLogger({ logger: options.logger, debug: options.debug });
19691
+ this._persistenceFailureReported = false;
19692
+ this.saveStatusState = 'saved';
19693
+ this.saveStatusError = null;
17688
19694
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17689
19695
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17690
19696
  this.title = options.title || this.labId;
17691
19697
  this.summary = options.summary || '';
17692
19698
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17693
19699
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
19700
+ this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
19701
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
19702
+ this._previewIsolationWarned = false;
19703
+ if (options.previewOrigin && !this.previewOrigin) {
19704
+ this.logger.warn(
19705
+ 'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
19706
+ 'such as "https://preview.example.com".'
19707
+ );
19708
+ }
17694
19709
  this.explicitEntry = options.entry || null;
17695
19710
  this.explicitTestEntry = options.testEntry || options.testFile || null;
17696
19711
  this.backLabel = options.backLabel || 'Back to Build Guide';
@@ -17762,12 +19777,15 @@ declare module 'bun:sqlite' {
17762
19777
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
17763
19778
  loading: false,
17764
19779
  error: null,
17765
- srcdoc: ''
19780
+ srcdoc: '',
19781
+ violations: []
17766
19782
  };
17767
19783
  this.previewHistory = [];
17768
19784
  this.previewHistoryIdx = -1;
17769
19785
  this._previewSwReady = false;
17770
19786
  this._previewSwRegistration = null;
19787
+ this._previewViolationHandler = null;
19788
+ this._swMessageHandler = null;
17771
19789
  this._portToasts = new Map();
17772
19790
  this.isFullscreen = false;
17773
19791
  this.isRunning = false;
@@ -17867,7 +19885,9 @@ declare module 'bun:sqlite' {
17867
19885
  onCommand: (cmd) => this._handleReplCommand(cmd),
17868
19886
  onInterrupt: () => this._handleInterrupt()
17869
19887
  });
17870
- } catch (_) {}
19888
+ } catch (err) {
19889
+ this.logger.debug('PTY engine initialization skipped.', err);
19890
+ }
17871
19891
  }
17872
19892
 
17873
19893
  this.shell = null;
@@ -17893,7 +19913,7 @@ declare module 'bun:sqlite' {
17893
19913
  intoRoot: options.cloneIntoRoot !== false,
17894
19914
  branch: options.branch || undefined,
17895
19915
  fetchImpl: options.fetchImpl || undefined
17896
- }).catch(() => {});
19916
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
17897
19917
  }
17898
19918
  }
17899
19919
 
@@ -17918,7 +19938,9 @@ declare module 'bun:sqlite' {
17918
19938
  }
17919
19939
  });
17920
19940
  this._syncFilesToShellVfs();
17921
- } catch (_) {}
19941
+ } catch (err) {
19942
+ this.logger.debug('POSIX shell initialization skipped.', err);
19943
+ }
17922
19944
  }
17923
19945
  }
17924
19946
 
@@ -17944,7 +19966,9 @@ declare module 'bun:sqlite' {
17944
19966
  const u = new URL(fullUrl);
17945
19967
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
17946
19968
  reqPath = u.pathname + (u.search || '');
17947
- } catch (_) {}
19969
+ } catch (err) {
19970
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
19971
+ }
17948
19972
  const method = String((init && init.method) || 'GET').toUpperCase();
17949
19973
  try {
17950
19974
  const res = await origDispatch(url, init);
@@ -17956,7 +19980,9 @@ declare module 'bun:sqlite' {
17956
19980
  } else if (res && res.body !== undefined) {
17957
19981
  bodyText = String(res.body);
17958
19982
  }
17959
- } catch (_) {}
19983
+ } catch (err) {
19984
+ this.logger.debug('Could not read response body for HTTP trace.', err);
19985
+ }
17960
19986
  const responseHeaders = {};
17961
19987
  if (res && res.headers) {
17962
19988
  if (typeof res.headers.forEach === 'function') {
@@ -17968,7 +19994,9 @@ declare module 'bun:sqlite' {
17968
19994
  let formattedBody = bodyText;
17969
19995
  try {
17970
19996
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
17971
- } catch (_) {}
19997
+ } catch (err) {
19998
+ void err;
19999
+ }
17972
20000
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
17973
20001
  this.lastHttpTrace.push({
17974
20002
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -18017,7 +20045,9 @@ declare module 'bun:sqlite' {
18017
20045
  vfs.writeFileSync(absPath, String(content ?? ''));
18018
20046
  }
18019
20047
  }
18020
- } catch (_) {}
20048
+ } catch (err) {
20049
+ this.logger.debug('Could not sync files to shell VFS.', err);
20050
+ }
18021
20051
  }
18022
20052
 
18023
20053
  _emitEvent(name, detail) {
@@ -18028,7 +20058,7 @@ declare module 'bun:sqlite' {
18028
20058
  const handlers = this._eventListeners.get(key);
18029
20059
  if (handlers) {
18030
20060
  for (const fn of Array.from(handlers)) {
18031
- try { fn(detail); } catch (_) {}
20061
+ try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
18032
20062
  }
18033
20063
  }
18034
20064
  }
@@ -18039,7 +20069,9 @@ declare module 'bun:sqlite' {
18039
20069
  if (shortName !== fullName) {
18040
20070
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
18041
20071
  }
18042
- } catch (_) {}
20072
+ } catch (err) {
20073
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
20074
+ }
18043
20075
  }
18044
20076
 
18045
20077
  _resolvedTheme() {
@@ -18062,13 +20094,39 @@ declare module 'bun:sqlite' {
18062
20094
  return {};
18063
20095
  }
18064
20096
  try {
18065
- const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
20097
+ const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
18066
20098
  return raw ? JSON.parse(raw) : {};
18067
- } catch {
20099
+ } catch (err) {
20100
+ this.logger.warn(
20101
+ `Ignoring unreadable saved state for "${this.labId}".`,
20102
+ err && err.message ? err.message : err
20103
+ );
18068
20104
  return {};
18069
20105
  }
18070
20106
  }
18071
20107
 
20108
+ _reportPersistenceFailure(cause) {
20109
+ const error = isCodeLabError(cause)
20110
+ ? cause
20111
+ : new CodeLabError(
20112
+ 'E_SAVE',
20113
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
20114
+ { cause, recoverable: true, details: { labId: this.labId } }
20115
+ );
20116
+ this.saveStatusState = 'failed';
20117
+ this.saveStatusError = error;
20118
+ this._updateStatusBar();
20119
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
20120
+ if (this._persistenceFailureReported) return error;
20121
+ this._persistenceFailureReported = true;
20122
+ this.logger.warn(
20123
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
20124
+ );
20125
+ this._emitEvent('persistence-error', { labId: this.labId, error });
20126
+ this._emitEvent('error', error);
20127
+ return error;
20128
+ }
20129
+
18072
20130
  _saveState() {
18073
20131
  try {
18074
20132
  const key = `${this.mode}:${this.lang}`;
@@ -18090,14 +20148,36 @@ declare module 'bun:sqlite' {
18090
20148
  };
18091
20149
  this.savedState = state;
18092
20150
  if (this.options && this.options.persistState === false) {
20151
+ this.saveStatusState = 'saved';
20152
+ this.saveStatusError = null;
20153
+ this._updateStatusBar();
18093
20154
  return;
18094
20155
  }
20156
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
18095
20157
  const serialized = JSON.stringify(state);
18096
- safeStorageSet(this._storageKey(), serialized);
18097
- // Sync with host app sidebar & build overview progress trackers
18098
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr));
18099
- safeStorageSet('sd_codelab_' + this.labId, serialized);
18100
- } catch {}
20158
+ safeStorageSet._lastError = null;
20159
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
20160
+ const persisted = [
20161
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
20162
+ // Sync with host app sidebar & build overview progress trackers
20163
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20164
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
20165
+ ];
20166
+ if (persisted.includes(false)) {
20167
+ this._reportPersistenceFailure(safeStorageSet._lastError);
20168
+ } else {
20169
+ this.saveStatusState = 'saved';
20170
+ this.saveStatusError = null;
20171
+ this._updateStatusBar();
20172
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
20173
+ }
20174
+ } catch (err) {
20175
+ this.logger.error(
20176
+ 'Failed to save workbench state.',
20177
+ err && err.message ? err.message : err
20178
+ );
20179
+ this._reportPersistenceFailure(err);
20180
+ }
18101
20181
  }
18102
20182
 
18103
20183
  _detectPackages() {
@@ -18119,7 +20199,9 @@ declare module 'bun:sqlite' {
18119
20199
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
18120
20200
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
18121
20201
  }
18122
- } catch (_) {}
20202
+ } catch (err) {
20203
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
20204
+ }
18123
20205
  }
18124
20206
 
18125
20207
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -18166,6 +20248,7 @@ declare module 'bun:sqlite' {
18166
20248
  const dotEl = this.container.querySelector('#cl-status-dot');
18167
20249
  const textEl = this.container.querySelector('#cl-status-text');
18168
20250
  const fileEl = this.container.querySelector('#cl-status-file');
20251
+ const saveEl = this.container.querySelector('#cl-status-save');
18169
20252
  const durEl = this.container.querySelector('#cl-status-duration');
18170
20253
  const curEl = this.container.querySelector('#cl-status-cursor');
18171
20254
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -18177,6 +20260,24 @@ declare module 'bun:sqlite' {
18177
20260
  }
18178
20261
  if (textEl) textEl.textContent = this.runtimeStatusText;
18179
20262
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
20263
+ if (saveEl) {
20264
+ if (this.saveStatusState === 'failed') {
20265
+ saveEl.style.display = 'inline-flex';
20266
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
20267
+ saveEl.textContent = '⚠ Save failed (session-only)';
20268
+ const reason = this.saveStatusError && this.saveStatusError.message
20269
+ ? this.saveStatusError.message
20270
+ : 'localStorage is unavailable or quota exceeded';
20271
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
20272
+ saveEl.setAttribute('data-save-state', 'failed');
20273
+ } else {
20274
+ saveEl.style.display = 'none';
20275
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
20276
+ saveEl.textContent = '';
20277
+ saveEl.removeAttribute('title');
20278
+ saveEl.setAttribute('data-save-state', 'saved');
20279
+ }
20280
+ }
18180
20281
  if (durEl) {
18181
20282
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
18182
20283
  durEl.style.display = 'inline-flex';
@@ -18484,6 +20585,7 @@ declare module 'bun:sqlite' {
18484
20585
  </span>
18485
20586
  <span class="codelab-statusbar__sep">·</span>
18486
20587
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
20588
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
18487
20589
  </div>
18488
20590
  <div class="codelab-statusbar__right">
18489
20591
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -19738,7 +21840,9 @@ declare module 'bun:sqlite' {
19738
21840
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
19739
21841
  try {
19740
21842
  this.ptyEngine.writeStreamChunk(rawText, type);
19741
- } catch (_) {}
21843
+ } catch (err) {
21844
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
21845
+ }
19742
21846
  }
19743
21847
 
19744
21848
  this._activeStreamType = type;
@@ -19870,14 +21974,18 @@ declare module 'bun:sqlite' {
19870
21974
  if (this._activeCommandAbortController) {
19871
21975
  try {
19872
21976
  this._activeCommandAbortController.abort('SIGINT');
19873
- } catch (_) {}
21977
+ } catch (err) {
21978
+ this.logger.debug('AbortController.abort failed.', err);
21979
+ }
19874
21980
  this._activeCommandAbortController = null;
19875
21981
  }
19876
21982
 
19877
21983
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
19878
21984
  try {
19879
21985
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
19880
- } catch (_) {}
21986
+ } catch (err) {
21987
+ this.logger.debug('cancelWorkerExecution failed.', err);
21988
+ }
19881
21989
  }
19882
21990
 
19883
21991
  this.isRunning = false;
@@ -20446,7 +22554,9 @@ declare module 'bun:sqlite' {
20446
22554
  try {
20447
22555
  const parsed = JSON.parse(responseBody);
20448
22556
  formattedBody = JSON.stringify(parsed, null, 2);
20449
- } catch (_) {}
22557
+ } catch (_) {
22558
+ formattedBody = responseBody;
22559
+ }
20450
22560
 
20451
22561
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
20452
22562
  const traceItem = {
@@ -20519,7 +22629,9 @@ declare module 'bun:sqlite' {
20519
22629
  if (this.drawerTab === 'ports') this._renderDrawerBody();
20520
22630
  this._dismissPortToast(port);
20521
22631
  }));
20522
- } catch (_) {}
22632
+ } catch (err) {
22633
+ this.logger.warn('Failed to attach portTable event listeners.', err);
22634
+ }
20523
22635
  }
20524
22636
 
20525
22637
  _updatePortsPill() {
@@ -20593,16 +22705,55 @@ declare module 'bun:sqlite' {
20593
22705
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
20594
22706
  try {
20595
22707
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
22708
+ this._swMessageHandler = onMessage;
20596
22709
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
20597
22710
  navigator.serviceWorker.addEventListener('message', onMessage);
20598
22711
  } else {
20599
22712
  navigator.serviceWorker.onmessage = onMessage;
20600
22713
  }
20601
22714
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
20602
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
20603
- .catch(() => { this._previewSwReady = false; });
20604
- } catch (_) {
22715
+ .then((reg) => {
22716
+ this._previewSwRegistration = reg;
22717
+ this._previewSwReady = true;
22718
+ this._pushPreviewCsp(reg);
22719
+ })
22720
+ .catch((err) => {
22721
+ this._previewSwReady = false;
22722
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
22723
+ });
22724
+ } catch (err) {
20605
22725
  this._previewSwReady = false;
22726
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
22727
+ }
22728
+ }
22729
+
22730
+ /**
22731
+ * The service worker cannot read workbench options, so the resolved policy
22732
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
22733
+ * the srcdoc fallback and silently not the served previews.
22734
+ */
22735
+ _pushPreviewCsp(registration) {
22736
+ const policy = this._previewPolicy();
22737
+ const send = (worker) => {
22738
+ if (!worker || typeof worker.postMessage !== 'function') return;
22739
+ try {
22740
+ worker.postMessage({ type: 'codelab:config', csp: policy });
22741
+ } catch (err) {
22742
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
22743
+ }
22744
+ };
22745
+
22746
+ if (registration) {
22747
+ send(registration.active);
22748
+ send(registration.installing);
22749
+ send(registration.waiting);
22750
+ }
22751
+
22752
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
22753
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
22754
+ sw.ready
22755
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
22756
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
20606
22757
  }
20607
22758
  }
20608
22759
 
@@ -20635,11 +22786,15 @@ declare module 'bun:sqlite' {
20635
22786
  } else if (res && res.headers) {
20636
22787
  Object.assign(outHeaders, res.headers);
20637
22788
  }
20638
- } catch (_) {}
22789
+ } catch (err) {
22790
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
22791
+ }
20639
22792
  let bodyText = '';
20640
22793
  try {
20641
22794
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
20642
- } catch (_) {}
22795
+ } catch (err) {
22796
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
22797
+ }
20643
22798
  return {
20644
22799
  status: (res && res.status) || 200,
20645
22800
  statusText: (res && res.statusText) || 'OK',
@@ -20662,12 +22817,174 @@ declare module 'bun:sqlite' {
20662
22817
  return `http://127.0.0.1:${port}${path}`;
20663
22818
  }
20664
22819
 
22820
+ _previewFrameUrl(port, pathAndQuery = '/') {
22821
+ const p = Number(port) || 3000;
22822
+ const rawPath = pathAndQuery || '/';
22823
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
22824
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
22825
+ // relay exists on that origin; pretending otherwise yields a 503.
22826
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
22827
+ return `${base}/__preview/${p}${path}`;
22828
+ }
22829
+
22830
+ /** Resolved CSP for preview documents served by this workbench. */
22831
+ _previewPolicy() {
22832
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
22833
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
22834
+ return "default-src 'self'; object-src 'none'";
22835
+ }
22836
+ return PreviewCsp.buildPreviewPolicy(
22837
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
22838
+ );
22839
+ }
22840
+
22841
+ /** Remote origins the current policy allows, for the preview toolbar. */
22842
+ _previewNetworkHosts() {
22843
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
22844
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
22845
+ }
22846
+
22847
+ _warnPreviewIsolation() {
22848
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
22849
+ this._previewIsolationWarned = true;
22850
+ if (PREVIEW_RELAY_AVAILABLE) return;
22851
+ this.logger.warn(
22852
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
22853
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
22854
+ 'the host origin: no host DOM, no host storage.'
22855
+ );
22856
+ }
22857
+
22858
+ _injectPreviewCsp(html, port) {
22859
+ if (typeof html !== 'string' || !html) return html;
22860
+
22861
+ const tags = [];
22862
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
22863
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
22864
+ }
22865
+ if (!/<base\b/i.test(html)) {
22866
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
22867
+ }
22868
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
22869
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
22870
+ tags.push(PreviewCsp.buildPreviewShims());
22871
+ }
22872
+ if (tags.length === 0) return html;
22873
+
22874
+ const injection = tags.join('');
22875
+ if (/<head\b[^>]*>/i.test(html)) {
22876
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
22877
+ }
22878
+ if (/<html\b[^>]*>/i.test(html)) {
22879
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
22880
+ }
22881
+ return `<head>${injection}</head>${html}`;
22882
+ }
22883
+
22884
+ /**
22885
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
22886
+ * string `"null"` and cannot be used to authenticate the sender. Match the
22887
+ * message source against the preview frame instead.
22888
+ */
22889
+ _installPreviewViolationListener() {
22890
+ if (this._previewViolationHandler) return;
22891
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
22892
+
22893
+ this._previewViolationHandler = (event) => {
22894
+ const data = event && event.data;
22895
+ if (!data || typeof data.type !== 'string') return;
22896
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
22897
+ if (!iframe) return;
22898
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
22899
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
22900
+
22901
+ if (data.type === 'codelab:preview-violation') {
22902
+ this._reportPreviewViolation(data);
22903
+ } else if (data.type === 'codelab:preview-console') {
22904
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
22905
+ const args = Array.isArray(data.args) ? data.args : [data.args];
22906
+ const text = args.map((a) => String(a ?? '')).join(' ');
22907
+ this.terminalLogs.push({
22908
+ type: level === 'error' ? 'stderr' : 'stdout',
22909
+ text: `[Preview ${level.toUpperCase()}] ${text}`
22910
+ });
22911
+ this._emitEvent('preview-console', { level, text, args });
22912
+ } else if (data.type === 'codelab:preview-error') {
22913
+ const msg = String(data.message || 'Uncaught runtime error');
22914
+ this.previewState.runtimeError = {
22915
+ message: msg,
22916
+ file: data.file ? String(data.file) : null,
22917
+ line: typeof data.line === 'number' ? data.line : null,
22918
+ col: typeof data.col === 'number' ? data.col : null,
22919
+ stack: data.stack ? String(data.stack) : null
22920
+ };
22921
+ this.terminalLogs.push({
22922
+ type: 'stderr',
22923
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
22924
+ });
22925
+ this._emitEvent('preview-error', this.previewState.runtimeError);
22926
+ } else if (data.type === 'codelab:preview-error-clear') {
22927
+ this.previewState.runtimeError = null;
22928
+ }
22929
+ };
22930
+ window.addEventListener('message', this._previewViolationHandler);
22931
+ }
22932
+
22933
+ _reportPreviewViolation(violation) {
22934
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
22935
+ const directive = String((violation && violation.directive) || '');
22936
+ const key = `${directive}|${blockedURI}`;
22937
+ const state = this.previewState;
22938
+ state.violations = state.violations || [];
22939
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
22940
+ state.violations.push({ key, directive, blockedURI });
22941
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
22942
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
22943
+ }
22944
+ this._updatePreviewCspStatus();
22945
+ }
22946
+
22947
+ _shortPreviewUrl(raw) {
22948
+ const value = String(raw || '');
22949
+ try {
22950
+ const parsed = new URL(value);
22951
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
22952
+ return `${parsed.host}${path === '/' ? '' : path}`;
22953
+ } catch (_) {
22954
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
22955
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
22956
+ }
22957
+ }
22958
+
22959
+ /** Update (or create) the CSP status chip in the preview toolbar. */
22960
+ _updatePreviewCspStatus() {
22961
+ if (!this.container) return;
22962
+ const chip = this.container.querySelector('#cl-preview-csp-status');
22963
+ if (!chip) return;
22964
+ const violations = (this.previewState && this.previewState.violations) || [];
22965
+ if (!violations.length) {
22966
+ chip.hidden = true;
22967
+ chip.textContent = '';
22968
+ chip.removeAttribute('title');
22969
+ return;
22970
+ }
22971
+ const last = violations[violations.length - 1];
22972
+ chip.hidden = false;
22973
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
22974
+ chip.title = violations
22975
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
22976
+ .join('\n');
22977
+ }
22978
+
20665
22979
  _openWebPreview(port, path = '/') {
20666
22980
  const p = Number(port) || this._firstListeningPort() || 3000;
22981
+ this._warnPreviewIsolation();
22982
+ this._installPreviewViolationListener();
20667
22983
  this.previewState.port = p;
20668
22984
  this.previewState.path = path || '/';
20669
22985
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
20670
22986
  this.previewState.error = null;
22987
+ this.previewState.violations = [];
20671
22988
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20672
22989
  this.previewHistory.push(this.previewState.url);
20673
22990
  this.previewHistoryIdx = this.previewHistory.length - 1;
@@ -20758,7 +23075,7 @@ declare module 'bun:sqlite' {
20758
23075
  try {
20759
23076
  const win = window.open(url, '_blank');
20760
23077
  if (win) {
20761
- try { win.opener = null; } catch (_) {}
23078
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
20762
23079
  opened = true;
20763
23080
  }
20764
23081
  } catch (_) { opened = false; }
@@ -20780,7 +23097,9 @@ declare module 'bun:sqlite' {
20780
23097
  const u = new URL(url);
20781
23098
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
20782
23099
  path = u.pathname + (u.search || '') + (u.hash || '');
20783
- } catch (_) {}
23100
+ } catch (err) {
23101
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
23102
+ }
20784
23103
  this.previewState.port = port;
20785
23104
  this.previewState.path = path;
20786
23105
  this.previewState.url = url;
@@ -20812,7 +23131,9 @@ declare module 'bun:sqlite' {
20812
23131
  const u = new URL(url);
20813
23132
  this.previewState.port = Number(u.port || 80);
20814
23133
  this.previewState.path = u.pathname + (u.search || '');
20815
- } catch (_) {}
23134
+ } catch (err) {
23135
+ this.logger.debug('Failed to parse preview history URL.', err);
23136
+ }
20816
23137
  const input = this.container.querySelector('#cl-preview-url-input');
20817
23138
  if (input) input.value = url;
20818
23139
  this._renderWebPreviewControls();
@@ -20842,19 +23163,22 @@ declare module 'bun:sqlite' {
20842
23163
 
20843
23164
  _popoutPreview() {
20844
23165
  const url = this._previewUrl();
20845
- let popout = '/__preview/';
23166
+ let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
20846
23167
  try {
20847
23168
  const u = new URL(url);
20848
- popout = `/__preview/${u.port}${u.pathname}${u.search || ''}`;
20849
- } catch (_) {}
23169
+ popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
23170
+ } catch (err) {
23171
+ this.logger.debug('Failed to parse popout preview URL.', err);
23172
+ }
20850
23173
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
20851
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
23174
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
20852
23175
  }
20853
23176
  return popout;
20854
23177
  }
20855
23178
 
20856
23179
  _renderWebPreview(bodyEl) {
20857
23180
  if (!bodyEl) return;
23181
+ this._warnPreviewIsolation();
20858
23182
  const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
20859
23183
  if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
20860
23184
  this._renderWebPreviewControls();
@@ -20874,6 +23198,19 @@ declare module 'bun:sqlite' {
20874
23198
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
20875
23199
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
20876
23200
 
23201
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
23202
+ const cspHosts = this._previewNetworkHosts();
23203
+ const cspBadge = cspMode === 'strict'
23204
+ ? 'CSP: strict'
23205
+ : !cspHosts.length
23206
+ ? 'CSP: custom'
23207
+ : cspHosts.length === 1
23208
+ ? `CSP: ${cspHosts[0]}`
23209
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
23210
+ const cspBadgeTitle = cspMode === 'strict'
23211
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23212
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23213
+
20877
23214
  bodyEl.innerHTML = `
20878
23215
  <div class="codelab-preview">
20879
23216
  <div class="codelab-preview-chrome">
@@ -20889,10 +23226,12 @@ declare module 'bun:sqlite' {
20889
23226
  <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>
20890
23227
  <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>
20891
23228
  </div>
23229
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23230
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
20892
23231
  <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>
20893
23232
  </div>
20894
23233
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
20895
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
23234
+ <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>
20896
23235
  </div>
20897
23236
  ${servers.length
20898
23237
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -20905,6 +23244,7 @@ declare module 'bun:sqlite' {
20905
23244
  </div>`}
20906
23245
  </div>
20907
23246
  `;
23247
+ this._updatePreviewCspStatus();
20908
23248
  this._loadPreviewFrame();
20909
23249
  }
20910
23250
 
@@ -20929,10 +23269,12 @@ declare module 'bun:sqlite' {
20929
23269
  try {
20930
23270
  const u = new URL(fullUrl);
20931
23271
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
20932
- iframe.setAttribute('src', `/__preview/${u.port}${u.pathname}${u.search || ''}`);
23272
+ iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
20933
23273
  this.previewState.loading = false;
20934
23274
  return Promise.resolve();
20935
- } catch (_) {}
23275
+ } catch (err) {
23276
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
23277
+ }
20936
23278
  }
20937
23279
 
20938
23280
  // Fallback (no Service Worker): dispatch via the virtual port table and
@@ -20941,8 +23283,8 @@ declare module 'bun:sqlite' {
20941
23283
  .then((res) => {
20942
23284
  let body = res.body || '';
20943
23285
  const contentType = res.headers['content-type'] || res.headers['Content-Type'] || '';
20944
- if (/text\/html/i.test(contentType) && /<head\b/i.test(body) && !/<base\b/i.test(body)) {
20945
- body = body.replace(/<head\b[^>]*>/i, (m) => `${m}<base href="/__preview/${port}/">`);
23286
+ if (/text\/html/i.test(contentType)) {
23287
+ body = this._injectPreviewCsp(body, port);
20946
23288
  }
20947
23289
  this.previewState.srcdoc = body;
20948
23290
  this.previewState.loading = false;
@@ -20954,7 +23296,7 @@ declare module 'bun:sqlite' {
20954
23296
  this.previewState.loading = false;
20955
23297
  this.previewState.error = String((err && err.message) || err);
20956
23298
  const msg = `<body style="font-family:system-ui;padding:24px;color:#888"><h2>Preview unavailable</h2><p>${escapeHtml(this.previewState.error)}</p></body>`;
20957
- iframe.setAttribute('srcdoc', msg);
23299
+ iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
20958
23300
  });
20959
23301
  }
20960
23302
 
@@ -20998,7 +23340,7 @@ declare module 'bun:sqlite' {
20998
23340
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
20999
23341
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
21000
23342
  let isDir = false;
21001
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
23343
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
21002
23344
  if (isDir) {
21003
23345
  shellWorkspaceFolders.add(rel);
21004
23346
  walk(full, rel);
@@ -21006,7 +23348,9 @@ declare module 'bun:sqlite' {
21006
23348
  try {
21007
23349
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
21008
23350
  shellWorkspaceFiles.set(rel, content);
21009
- } catch (_) {}
23351
+ } catch (err) {
23352
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
23353
+ }
21010
23354
  }
21011
23355
  }
21012
23356
  };
@@ -21308,8 +23652,29 @@ declare module 'bun:sqlite' {
21308
23652
  }
21309
23653
 
21310
23654
  _notifyCodeChange(filename, code) {
23655
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
23656
+ try {
23657
+ const clean = String(filename).replace(/^\/+/, '');
23658
+ const parts = clean.split('/');
23659
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
23660
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
23661
+ }
23662
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
23663
+ } catch (err) {
23664
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
23665
+ }
23666
+ }
23667
+ if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
23668
+ if (this._previewReloadTimer) {
23669
+ clearTimeout(this._previewReloadTimer);
23670
+ }
23671
+ this._previewReloadTimer = setTimeout(() => {
23672
+ this._previewReloadTimer = null;
23673
+ this._previewReload();
23674
+ }, 300);
23675
+ }
21311
23676
  if (this.onCodeChange) {
21312
- try { this.onCodeChange(filename, code); } catch (_) {}
23677
+ try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21313
23678
  }
21314
23679
  const detail = { labId: this.labId, filename, path: filename, code, content: code };
21315
23680
  this._emitEvent('codelab:change', detail);
@@ -21365,7 +23730,7 @@ declare module 'bun:sqlite' {
21365
23730
  if (fallbackWrap) fallbackWrap.style.display = 'none';
21366
23731
  if (mdPreview) mdPreview.style.display = 'none';
21367
23732
  if (this.editor) {
21368
- try { this.editor.setModel(null); } catch (_) {}
23733
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
21369
23734
  }
21370
23735
  if (emptyEl) {
21371
23736
  emptyEl.style.display = 'flex';
@@ -21677,7 +24042,9 @@ declare module 'bun:sqlite' {
21677
24042
  textarea.select();
21678
24043
  document.execCommand('copy');
21679
24044
  document.body.removeChild(textarea);
21680
- } catch (_) {}
24045
+ } catch (err) {
24046
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
24047
+ }
21681
24048
  };
21682
24049
 
21683
24050
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -22035,6 +24402,7 @@ declare module 'bun:sqlite' {
22035
24402
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
22036
24403
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
22037
24404
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
24405
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
22038
24406
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
22039
24407
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
22040
24408
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -22045,6 +24413,9 @@ declare module 'bun:sqlite' {
22045
24413
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
22046
24414
  } },
22047
24415
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
24416
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
24417
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
24418
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
22048
24419
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
22049
24420
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
22050
24421
  ];
@@ -22077,7 +24448,9 @@ declare module 'bun:sqlite' {
22077
24448
  input.focus();
22078
24449
  try {
22079
24450
  input.setSelectionRange(initialVal.length, initialVal.length);
22080
- } catch (_) {}
24451
+ } catch (err) {
24452
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
24453
+ }
22081
24454
 
22082
24455
  input.addEventListener('input', () => {
22083
24456
  this.paletteSelectedIndex = 0;
@@ -22350,7 +24723,7 @@ declare module 'bun:sqlite' {
22350
24723
  const onUp = ev => {
22351
24724
  vSplitter.classList.remove('is-dragging');
22352
24725
  shell.classList.remove('is-resizing');
22353
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24726
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22354
24727
  vSplitter.removeEventListener('pointermove', onMove);
22355
24728
  vSplitter.removeEventListener('pointerup', onUp);
22356
24729
  };
@@ -22391,7 +24764,7 @@ declare module 'bun:sqlite' {
22391
24764
  const onUp = ev => {
22392
24765
  hSplitter.classList.remove('is-dragging');
22393
24766
  shell.classList.remove('is-resizing-row');
22394
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24767
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22395
24768
  hSplitter.removeEventListener('pointermove', onMove);
22396
24769
  hSplitter.removeEventListener('pointerup', onUp);
22397
24770
  };
@@ -22418,7 +24791,7 @@ declare module 'bun:sqlite' {
22418
24791
  e.preventDefault();
22419
24792
  fSplitter.classList.add('is-dragging');
22420
24793
  shell.classList.add('is-resizing');
22421
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
24794
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
22422
24795
 
22423
24796
  const onMove = ev => {
22424
24797
  const ws = this.container.querySelector('.codelab-workspace');
@@ -22432,7 +24805,7 @@ declare module 'bun:sqlite' {
22432
24805
  const onUp = ev => {
22433
24806
  fSplitter.classList.remove('is-dragging');
22434
24807
  shell.classList.remove('is-resizing');
22435
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24808
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22436
24809
  fSplitter.removeEventListener('pointermove', onMove);
22437
24810
  fSplitter.removeEventListener('pointerup', onUp);
22438
24811
  this._saveState();
@@ -22775,7 +25148,9 @@ declare module 'bun:sqlite' {
22775
25148
  if (this.files['package.json']) {
22776
25149
  try {
22777
25150
  pkgJson = JSON.parse(this.files['package.json']);
22778
- } catch (_) {}
25151
+ } catch (err) {
25152
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
25153
+ }
22779
25154
  }
22780
25155
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
22781
25156
  pkgJson.dependencies = {};
@@ -22948,7 +25323,7 @@ declare module 'bun:sqlite' {
22948
25323
  }
22949
25324
 
22950
25325
  if (this.onRun) {
22951
- try { this.onRun(res); } catch (_) {}
25326
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
22952
25327
  }
22953
25328
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
22954
25329
  } catch (err) {
@@ -23023,10 +25398,10 @@ declare module 'bun:sqlite' {
23023
25398
  }
23024
25399
 
23025
25400
  if (this.onTestResult) {
23026
- try { this.onTestResult(res); } catch (_) {}
25401
+ try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
23027
25402
  }
23028
25403
  if (this.onRun) {
23029
- try { this.onRun(res); } catch (_) {}
25404
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
23030
25405
  }
23031
25406
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
23032
25407
 
@@ -23040,7 +25415,7 @@ declare module 'bun:sqlite' {
23040
25415
  this.completedSteps.add(step.id);
23041
25416
  newlyCompleted = true;
23042
25417
  if (this.onStepComplete) {
23043
- try { this.onStepComplete(step, sIdx); } catch (_) {}
25418
+ try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
23044
25419
  }
23045
25420
  const stepDetail = {
23046
25421
  labId: this.labId,
@@ -23059,7 +25434,7 @@ declare module 'bun:sqlite' {
23059
25434
  this._saveState();
23060
25435
  if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
23061
25436
  if (this.onLabComplete) {
23062
- try { this.onLabComplete(this.labId); } catch (_) {}
25437
+ try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
23063
25438
  }
23064
25439
  this._emitEvent('codelab:lab-complete', {
23065
25440
  labId: this.labId,
@@ -23364,7 +25739,12 @@ declare module 'bun:sqlite' {
23364
25739
  a.click();
23365
25740
  setTimeout(() => URL.revokeObjectURL(url), 500);
23366
25741
  }
23367
- } catch (_) {}
25742
+ } catch (err) {
25743
+ this.logger.error(
25744
+ `Failed to start download for "${filename}".`,
25745
+ err && err.message ? err.message : err
25746
+ );
25747
+ }
23368
25748
  return content;
23369
25749
  }
23370
25750
 
@@ -23392,7 +25772,12 @@ declare module 'bun:sqlite' {
23392
25772
  a.click();
23393
25773
  setTimeout(() => URL.revokeObjectURL(url), 500);
23394
25774
  }
23395
- } catch (_) {}
25775
+ } catch (err) {
25776
+ this.logger.error(
25777
+ 'Failed to download workspace export.',
25778
+ err && err.message ? err.message : err
25779
+ );
25780
+ }
23396
25781
  }
23397
25782
  return snapshot;
23398
25783
  }
@@ -23426,6 +25811,219 @@ declare module 'bun:sqlite' {
23426
25811
  return true;
23427
25812
  }
23428
25813
 
25814
+ exportProjectZip(options = {}) {
25815
+ const zipMod = root.CodeLabZip;
25816
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
25817
+ throw new Error('CodeLabZip engine is not loaded');
25818
+ }
25819
+ const bytes = zipMod.createZip(this.files || {});
25820
+ if (options && options.download) {
25821
+ try {
25822
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
25823
+ const blob = new Blob([bytes], { type: 'application/zip' });
25824
+ const url = URL.createObjectURL(blob);
25825
+ const a = document.createElement('a');
25826
+ a.href = url;
25827
+ a.download = `${this.labId || 'workspace'}.zip`;
25828
+ a.click();
25829
+ setTimeout(() => URL.revokeObjectURL(url), 500);
25830
+ }
25831
+ } catch (err) {
25832
+ this.logger.error('Failed to download project ZIP export.', err);
25833
+ }
25834
+ }
25835
+ return bytes;
25836
+ }
25837
+
25838
+ importProjectZip(zipBytes) {
25839
+ const zipMod = root.CodeLabZip;
25840
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
25841
+ throw new Error('CodeLabZip engine is not loaded');
25842
+ }
25843
+ const extracted = zipMod.extractZip(zipBytes);
25844
+ if (!extracted || typeof extracted !== 'object') return false;
25845
+ this.setFiles(extracted);
25846
+ this._syncFilesToShellVfs();
25847
+ return true;
25848
+ }
25849
+
25850
+ searchWorkspace(options) {
25851
+ const searchMod = root.CodeLabSearch;
25852
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
25853
+ throw new Error('CodeLabSearch engine is not loaded');
25854
+ }
25855
+ return searchMod.searchInFiles(this.files || {}, options);
25856
+ }
25857
+
25858
+ replaceInWorkspace(options) {
25859
+ const searchMod = root.CodeLabSearch;
25860
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
25861
+ throw new Error('CodeLabSearch engine is not loaded');
25862
+ }
25863
+ const res = searchMod.replaceInFiles(this.files || {}, options);
25864
+ if (res && res.files && res.filesModified > 0) {
25865
+ this.setFiles(res.files);
25866
+ this._syncFilesToShellVfs();
25867
+ }
25868
+ return res;
25869
+ }
25870
+
25871
+ getGitStatus() {
25872
+ const scmMod = root.CodeLabScm;
25873
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
25874
+ return [];
25875
+ }
25876
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
25877
+ return scmMod.computeGitStatus(gs, this.files || {});
25878
+ }
25879
+
25880
+ getDiagnostics() {
25881
+ const diagMod = root.CodeLabDiagnostics;
25882
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
25883
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
25884
+ }
25885
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
25886
+ return this._diagnosticsStore.getAll();
25887
+ }
25888
+ return [];
25889
+ }
25890
+
25891
+ showSearchModal(initialQuery = '') {
25892
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25893
+ if (!slot) return;
25894
+ const q = String(initialQuery || '');
25895
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
25896
+ const rowsHtml = (results.matches || []).map((m) => `
25897
+ <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;">
25898
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
25899
+ </div>
25900
+ `).join('');
25901
+ slot.innerHTML = `
25902
+ <div class="codelab-modal-backdrop">
25903
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
25904
+ <div class="codelab-modal__header">
25905
+ <span>Search &amp; Replace Across Workspace</span>
25906
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25907
+ </div>
25908
+ <div class="codelab-modal__body">
25909
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
25910
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
25911
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
25912
+ </div>
25913
+ <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>
25914
+ </div>
25915
+ </div>
25916
+ </div>
25917
+ `;
25918
+ }
25919
+
25920
+ showScmModal() {
25921
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25922
+ if (!slot) return;
25923
+ const statusList = this.getGitStatus();
25924
+ const rowsHtml = statusList.map((entry) => `
25925
+ <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;">
25926
+ <span>${escapeHtml(entry.path)}</span>
25927
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
25928
+ </div>
25929
+ `).join('');
25930
+ slot.innerHTML = `
25931
+ <div class="codelab-modal-backdrop">
25932
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
25933
+ <div class="codelab-modal__header">
25934
+ <span>Source Control (Git Status)</span>
25935
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25936
+ </div>
25937
+ <div class="codelab-modal__body">
25938
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
25939
+ </div>
25940
+ </div>
25941
+ </div>
25942
+ `;
25943
+ }
25944
+
25945
+ showProblemsModal() {
25946
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25947
+ if (!slot) return;
25948
+ const items = this.getDiagnostics();
25949
+ const rowsHtml = items.map((d) => `
25950
+ <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;">
25951
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
25952
+ </div>
25953
+ `).join('');
25954
+ slot.innerHTML = `
25955
+ <div class="codelab-modal-backdrop">
25956
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
25957
+ <div class="codelab-modal__header">
25958
+ <span>Problems (${items.length})</span>
25959
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25960
+ </div>
25961
+ <div class="codelab-modal__body">
25962
+ <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>
25963
+ </div>
25964
+ </div>
25965
+ </div>
25966
+ `;
25967
+ }
25968
+
25969
+ _ensureTerminalSessions() {
25970
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
25971
+ this._terminalSessions = [
25972
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
25973
+ ];
25974
+ this._activeTerminalSessionId = 'session-1';
25975
+ }
25976
+ return this._terminalSessions;
25977
+ }
25978
+
25979
+ listTerminalSessions() {
25980
+ const sessions = this._ensureTerminalSessions();
25981
+ return sessions.map((s) => ({
25982
+ id: s.id,
25983
+ name: s.name,
25984
+ active: s.id === this._activeTerminalSessionId,
25985
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
25986
+ }));
25987
+ }
25988
+
25989
+ createTerminalSession(name) {
25990
+ const sessions = this._ensureTerminalSessions();
25991
+ const nextNum = sessions.length + 1;
25992
+ const id = `session-${Date.now()}-${nextNum}`;
25993
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
25994
+ const newLogs = [];
25995
+ sessions.push({ id, name: label, logs: newLogs });
25996
+ this._activeTerminalSessionId = id;
25997
+ this.terminalLogs = newLogs;
25998
+ this._renderDrawerBody();
25999
+ return id;
26000
+ }
26001
+
26002
+ switchTerminalSession(id) {
26003
+ const sessions = this._ensureTerminalSessions();
26004
+ const target = sessions.find((s) => s.id === id || s.name === id);
26005
+ if (!target) return false;
26006
+ this._activeTerminalSessionId = target.id;
26007
+ this.terminalLogs = target.logs;
26008
+ this._renderDrawerBody();
26009
+ return true;
26010
+ }
26011
+
26012
+ closeTerminalSession(id) {
26013
+ const sessions = this._ensureTerminalSessions();
26014
+ if (sessions.length <= 1) return false;
26015
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
26016
+ if (idx === -1) return false;
26017
+ const removed = sessions.splice(idx, 1)[0];
26018
+ if (this._activeTerminalSessionId === removed.id) {
26019
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
26020
+ this._activeTerminalSessionId = next.id;
26021
+ this.terminalLogs = next.logs;
26022
+ }
26023
+ this._renderDrawerBody();
26024
+ return true;
26025
+ }
26026
+
23429
26027
  getFiles() {
23430
26028
  return { ...this.files };
23431
26029
  }
@@ -23433,7 +26031,7 @@ declare module 'bun:sqlite' {
23433
26031
  setFiles(filesMap) {
23434
26032
  if (!filesMap || typeof filesMap !== 'object') return;
23435
26033
  for (const model of this.models.values()) {
23436
- try { model.dispose(); } catch (_) {}
26034
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
23437
26035
  }
23438
26036
  this.models.clear();
23439
26037
  this.files = {};
@@ -23523,7 +26121,9 @@ declare module 'bun:sqlite' {
23523
26121
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
23524
26122
  try {
23525
26123
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
23526
- } catch (_) {}
26124
+ } catch (err) {
26125
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
26126
+ }
23527
26127
  }
23528
26128
  this._notifyCodeChange(clean, updated);
23529
26129
  }
@@ -23743,9 +26343,22 @@ declare module 'bun:sqlite' {
23743
26343
 
23744
26344
  destroy() {
23745
26345
  this.stopExecution();
26346
+ if (this._previewReloadTimer) {
26347
+ clearTimeout(this._previewReloadTimer);
26348
+ this._previewReloadTimer = null;
26349
+ }
23746
26350
  if (this._escHandler && typeof document !== 'undefined') {
23747
26351
  document.removeEventListener('keydown', this._escHandler);
23748
26352
  }
26353
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26354
+ window.removeEventListener('message', this._previewViolationHandler);
26355
+ }
26356
+ this._previewViolationHandler = null;
26357
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
26358
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
26359
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
26360
+ }
26361
+ this._swMessageHandler = null;
23749
26362
  if (this._themeObserver) {
23750
26363
  this._themeObserver.disconnect();
23751
26364
  }
@@ -23806,7 +26419,9 @@ declare module 'bun:sqlite' {
23806
26419
  if (jsonScript && jsonScript.textContent) {
23807
26420
  try {
23808
26421
  inlineConfig = JSON.parse(jsonScript.textContent);
23809
- } catch (_) {}
26422
+ } catch (err) {
26423
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
26424
+ }
23810
26425
  }
23811
26426
 
23812
26427
  // Parse optional files JSON attribute
@@ -23815,7 +26430,9 @@ declare module 'bun:sqlite' {
23815
26430
  if (filesAttr) {
23816
26431
  try {
23817
26432
  attrFiles = JSON.parse(filesAttr);
23818
- } catch (_) {}
26433
+ } catch (err) {
26434
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
26435
+ }
23819
26436
  }
23820
26437
 
23821
26438
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -23858,6 +26475,19 @@ declare module 'bun:sqlite' {
23858
26475
  reset() { if (this._instance) this._instance.reset(); }
23859
26476
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
23860
26477
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
26478
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
26479
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
26480
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
26481
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
26482
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
26483
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
26484
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
26485
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
26486
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
26487
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
26488
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
26489
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
26490
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
23861
26491
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
23862
26492
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
23863
26493
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -23888,13 +26518,46 @@ declare module 'bun:sqlite' {
23888
26518
  }
23889
26519
 
23890
26520
  const CodeLabSDK = {
23891
- version: '2.0.0',
26521
+ version: CODELAB_VERSION,
23892
26522
  Workbench: CodeLabWorkbench,
23893
26523
  CodeLabWorkbench,
23894
26524
  CodeLabElement: CodeLabElementClass,
26525
+ CodeLabError,
26526
+ isCodeLabError,
26527
+ createLogger,
26528
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
26529
+ html,
26530
+ raw,
26531
+ isSafeHtml,
26532
+ escapeHtml,
26533
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
23895
26534
  Runtime: root.CodeLabRuntime,
23896
26535
  Shell: root.CodeLabShell,
23897
26536
  Terminal: root.CodeLabTerminal,
26537
+ zip: root.CodeLabZip || null,
26538
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
26539
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
26540
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
26541
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
26542
+ storage: root.CodeLabStorage || null,
26543
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
26544
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
26545
+ search: root.CodeLabSearch || null,
26546
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
26547
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
26548
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
26549
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
26550
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
26551
+ diagnostics: root.CodeLabDiagnostics || null,
26552
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
26553
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
26554
+ scm: root.CodeLabScm || null,
26555
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
26556
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
26557
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
26558
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
26559
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
26560
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
23898
26561
  renderMarkdown: renderSimpleMarkdown,
23899
26562
  renderSimpleMarkdown: renderSimpleMarkdown,
23900
26563
  extensions: {
@@ -23957,6 +26620,48 @@ declare module 'bun:sqlite' {
23957
26620
  createVirtualHttp: CodeLabRuntime.createVirtualHttp,
23958
26621
  createVirtualNet: CodeLabRuntime.createVirtualNet,
23959
26622
  createVirtualPortTable: CodeLabRuntime.createVirtualPortTable,
26623
+ createWorkerRuntimeSource: CodeLabRuntime.createWorkerRuntimeSource,
26624
+ CodeLabCsp: CodeLabCsp,
26625
+ CodeLabLogger: CodeLabLogger,
26626
+ CodeLabHtml: CodeLabHtml,
26627
+ html: CodeLabHtml.html,
26628
+ raw: CodeLabHtml.raw,
26629
+ isSafeHtml: CodeLabHtml.isSafeHtml,
26630
+ escapeHtml: CodeLabHtml.escapeHtml,
26631
+ CodeLabError: CodeLabLogger.CodeLabError,
26632
+ isCodeLabError: CodeLabLogger.isCodeLabError,
26633
+ createLogger: CodeLabLogger.createLogger,
26634
+ DEFAULT_LOGGER: CodeLabLogger.DEFAULT_LOGGER,
26635
+ LOG_PREFIX: CodeLabLogger.LOG_PREFIX,
26636
+ CodeLabZip: CodeLabZip,
26637
+ zip: CodeLabZip,
26638
+ createZip: CodeLabZip.createZip,
26639
+ extractZip: CodeLabZip.extractZip,
26640
+ computeCrc32: CodeLabZip.computeCrc32,
26641
+ sanitizeZipPath: CodeLabZip.sanitizeZipPath,
26642
+ CodeLabStorage: CodeLabStorage,
26643
+ storage: CodeLabStorage,
26644
+ WorkspaceStorage: CodeLabStorage.WorkspaceStorage,
26645
+ createWorkspaceStorage: CodeLabStorage.createWorkspaceStorage,
26646
+ CodeLabSearch: CodeLabSearch,
26647
+ search: CodeLabSearch,
26648
+ searchInFiles: CodeLabSearch.searchInFiles,
26649
+ replaceInFiles: CodeLabSearch.replaceInFiles,
26650
+ matchesGlob: CodeLabSearch.matchesGlob,
26651
+ escapeRegex: CodeLabSearch.escapeRegex,
26652
+ normalizeSearchPath: CodeLabSearch.normalizeSearchPath,
26653
+ CodeLabDiagnostics: CodeLabDiagnostics,
26654
+ diagnostics: CodeLabDiagnostics,
26655
+ DiagnosticsStore: CodeLabDiagnostics.DiagnosticsStore,
26656
+ createDiagnosticsStore: CodeLabDiagnostics.createDiagnosticsStore,
26657
+ CodeLabScm: CodeLabScm,
26658
+ scm: CodeLabScm,
26659
+ createGitState: CodeLabScm.createGitState,
26660
+ computeGitStatus: CodeLabScm.computeGitStatus,
26661
+ stageFile: CodeLabScm.stageFile,
26662
+ unstageFile: CodeLabScm.unstageFile,
26663
+ commitChanges: CodeLabScm.commitChanges,
26664
+ computeShortCommitHash: CodeLabScm.computeShortCommitHash,
23960
26665
  default: CodeLab
23961
26666
  });
23962
26667
  }