@innovatorved/code-lab 0.1.7 → 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.
package/dist/code-lab.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.1.7 — 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,6 +17,1678 @@
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 () {
22
1694
  // @ts-nocheck
@@ -41,6 +1713,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
41
1713
  */
42
1714
 
43
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
+ };
44
1724
  // =========================================================================
45
1725
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
46
1726
  // =========================================================================
@@ -1600,7 +3280,7 @@ function __initVirtualRuntime(rootScope) {
1600
3280
  },
1601
3281
  final(cb) {
1602
3282
  if (fd !== null) {
1603
- try { fsShim.closeSync(fd); } catch (_) {}
3283
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1604
3284
  fd = null;
1605
3285
  }
1606
3286
  cb(null);
@@ -2120,7 +3800,9 @@ function __initVirtualRuntime(rootScope) {
2120
3800
  return pathname + search + hash;
2121
3801
  }
2122
3802
  return resolvedUrl.href;
2123
- } catch (_) {}
3803
+ } catch (err) {
3804
+ _runtimeLogger.debug('url.resolve fallback used', err);
3805
+ }
2124
3806
  }
2125
3807
  if (toStr.startsWith('/')) {
2126
3808
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2559,10 +4241,10 @@ function __initVirtualRuntime(rootScope) {
2559
4241
  for (const [port, entry] of Array.from(table.entries())) {
2560
4242
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2561
4243
  if (entry.server && typeof entry.server.close === 'function') {
2562
- try { entry.server.close(); } catch (_) {}
4244
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2563
4245
  }
2564
4246
  if (typeof entry.stop === 'function') {
2565
- try { entry.stop(); } catch (_) {}
4247
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2566
4248
  }
2567
4249
  // Avoid a double 'close' emission when entry.server.close() already
2568
4250
  // unregistered the port through unregisterServer().
@@ -3199,7 +4881,7 @@ function __initVirtualRuntime(rootScope) {
3199
4881
  },
3200
4882
  closeAllServers() {
3201
4883
  for (const s of Array.from(activeServers.values())) {
3202
- try { s.close(); } catch (_) {}
4884
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3203
4885
  }
3204
4886
  activeServers.clear();
3205
4887
  }
@@ -4025,7 +5707,7 @@ function __initVirtualRuntime(rootScope) {
4025
5707
 
4026
5708
  function closeAllServers() {
4027
5709
  for (const srv of servers.values()) {
4028
- try { srv.close(); } catch (_) {}
5710
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4029
5711
  }
4030
5712
  servers.clear();
4031
5713
  }
@@ -5105,7 +6787,9 @@ function __initVirtualRuntime(rootScope) {
5105
6787
  try {
5106
6788
  const pkgJson = JSON.parse(content);
5107
6789
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5108
- } catch (_) {}
6790
+ } catch (err) {
6791
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
6792
+ }
5109
6793
  continue;
5110
6794
  }
5111
6795
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5134,7 +6818,9 @@ function __initVirtualRuntime(rootScope) {
5134
6818
  const meta = await res.json();
5135
6819
  deps = Object.keys((meta && meta.dependencies) || {});
5136
6820
  }
5137
- } catch (_) {}
6821
+ } catch (err) {
6822
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
6823
+ }
5138
6824
  _npmMetadataCache.set(pkg, deps);
5139
6825
  }));
5140
6826
  for (const pkg of pending) {
@@ -5152,7 +6838,7 @@ function __initVirtualRuntime(rootScope) {
5152
6838
  continue;
5153
6839
  }
5154
6840
  if (typeof onProgress === 'function') {
5155
- try { onProgress(pkg); } catch (_) {}
6841
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5156
6842
  }
5157
6843
  if (typeof fetch === 'function') {
5158
6844
  try {
@@ -5162,7 +6848,9 @@ function __initVirtualRuntime(rootScope) {
5162
6848
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5163
6849
  loaded[pkg] = text;
5164
6850
  }
5165
- } catch (_) {}
6851
+ } catch (err) {
6852
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
6853
+ }
5166
6854
  }
5167
6855
  }
5168
6856
  return loaded;
@@ -5354,7 +7042,9 @@ function __initVirtualRuntime(rootScope) {
5354
7042
  const dir = VirtualPath.dirname(abs);
5355
7043
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5356
7044
  vfs.writeFileSync(abs, content);
5357
- } catch (_) {}
7045
+ } catch (err) {
7046
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
7047
+ }
5358
7048
  }
5359
7049
  }
5360
7050
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5799,7 +7489,7 @@ function __initVirtualRuntime(rootScope) {
5799
7489
  exitCode = Number(code) || 0;
5800
7490
  if (!hasExited) {
5801
7491
  hasExited = true;
5802
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7492
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5803
7493
  }
5804
7494
  if (syncExecDepth > 0) {
5805
7495
  throw new ProcessExitSignal(exitCode);
@@ -5832,8 +7522,8 @@ function __initVirtualRuntime(rootScope) {
5832
7522
  resourceTracker.inFlightHttp.clear();
5833
7523
 
5834
7524
  if (!isBackground) {
5835
- try { vhttp.closeAllServers(); } catch (_) {}
5836
- 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); }
5837
7527
  }
5838
7528
  };
5839
7529
 
@@ -5943,10 +7633,10 @@ function __initVirtualRuntime(rootScope) {
5943
7633
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5944
7634
  } finally {
5945
7635
  for (const ae of hooksSnapshot.afterEachList) {
5946
- try { await ae(); } catch (_) {}
7636
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5947
7637
  }
5948
7638
  for (const af of hooksSnapshot.afterToRun) {
5949
- try { await af(); } catch (_) {}
7639
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5950
7640
  }
5951
7641
  hooksSnapshot.afterToRun.length = 0;
5952
7642
  }
@@ -5994,7 +7684,7 @@ function __initVirtualRuntime(rootScope) {
5994
7684
  const afters = [...suiteCtx.afterCallbacks];
5995
7685
  const cleanupTask = nodeTestChain.then(async () => {
5996
7686
  for (const af of afters) {
5997
- try { await af(); } catch (_) {}
7687
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5998
7688
  }
5999
7689
  });
6000
7690
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6040,7 +7730,7 @@ function __initVirtualRuntime(rootScope) {
6040
7730
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6041
7731
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6042
7732
  };
6043
- try { obs._cb(list, obs); } catch (_) {}
7733
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6044
7734
  }
6045
7735
  }
6046
7736
  }
@@ -6145,7 +7835,7 @@ function __initVirtualRuntime(rootScope) {
6145
7835
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6146
7836
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6147
7837
  };
6148
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
7838
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6149
7839
  }
6150
7840
  }
6151
7841
  }
@@ -7416,7 +9106,9 @@ function __initVirtualRuntime(rootScope) {
7416
9106
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7417
9107
  if (resolvedEntry) return resolvedEntry;
7418
9108
  }
7419
- } catch (_) {}
9109
+ } catch (err) {
9110
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
9111
+ }
7420
9112
  }
7421
9113
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7422
9114
  for (const idx of indexCandidates) {
@@ -7486,7 +9178,9 @@ function __initVirtualRuntime(rootScope) {
7486
9178
  if (found) return found;
7487
9179
  }
7488
9180
  }
7489
- } catch (_) {}
9181
+ } catch (err) {
9182
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
9183
+ }
7490
9184
  }
7491
9185
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7492
9186
  if (foundSub) return foundSub;
@@ -7528,7 +9222,9 @@ function __initVirtualRuntime(rootScope) {
7528
9222
  if (isLocal && activePortTable) {
7529
9223
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7530
9224
  }
7531
- } catch (_) {}
9225
+ } catch (err) {
9226
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
9227
+ }
7532
9228
 
7533
9229
  if (typeof globalThis.fetch === 'function') {
7534
9230
  return await globalThis.fetch(urlOrReq, init);
@@ -7695,7 +9391,9 @@ function __initVirtualRuntime(rootScope) {
7695
9391
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7696
9392
  try {
7697
9393
  return new AsyncFunction(...argNames, body);
7698
- } catch (_) {}
9394
+ } catch (asyncErr) {
9395
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
9396
+ }
7699
9397
  }
7700
9398
  if (
7701
9399
  err &&
@@ -7749,7 +9447,9 @@ function __initVirtualRuntime(rootScope) {
7749
9447
  if (signal && onAbort) {
7750
9448
  try {
7751
9449
  signal.removeEventListener('abort', onAbort);
7752
- } catch (_) {}
9450
+ } catch (err) {
9451
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
9452
+ }
7753
9453
  }
7754
9454
  };
7755
9455
 
@@ -7908,11 +9608,11 @@ function __initVirtualRuntime(rootScope) {
7908
9608
  }
7909
9609
  } finally {
7910
9610
  if (signal && signalListener) {
7911
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
9611
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7912
9612
  }
7913
9613
  if (!hasExited) {
7914
9614
  hasExited = true;
7915
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
9615
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7916
9616
  }
7917
9617
  for (const rawId of resourceTracker.allTimers) {
7918
9618
  clearTimeout(rawId);
@@ -8020,7 +9720,16 @@ function createWorkerRuntimeSource() {
8020
9720
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8021
9721
  }
8022
9722
 
8023
- 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);
8024
9733
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8025
9734
 
8026
9735
  let _cachedWorkerUrl = null;
@@ -8044,7 +9753,7 @@ function _ensureWarmWorker() {
8044
9753
 
8045
9754
  function _destroyWarmWorker() {
8046
9755
  if (_warmWorker) {
8047
- try { _warmWorker.terminate(); } catch (_) {}
9756
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8048
9757
  _warmWorker = null;
8049
9758
  }
8050
9759
  _warmWorkerBusy = false;
@@ -8099,7 +9808,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8099
9808
 
8100
9809
  function releaseWorker(terminateWorker) {
8101
9810
  if (options.signal && abortListener) {
8102
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
9811
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8103
9812
  abortListener = null;
8104
9813
  }
8105
9814
  _activeWorkerJobs.delete(requestId);
@@ -8114,7 +9823,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8114
9823
  }
8115
9824
  }
8116
9825
  } else {
8117
- try { worker.terminate(); } catch (_) {}
9826
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8118
9827
  }
8119
9828
  }
8120
9829
 
@@ -8304,12 +10013,23 @@ if (typeof module !== 'undefined' && module.exports) {
8304
10013
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
8305
10014
  'use strict';
8306
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
+
8307
10025
  function getRuntimeModule() {
8308
10026
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
8309
10027
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
8310
10028
  try {
8311
10029
  if (typeof require !== 'undefined') return require('./runtime.js');
8312
- } catch (_) {}
10030
+ } catch (err) {
10031
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
10032
+ }
8313
10033
  return null;
8314
10034
  }
8315
10035
 
@@ -8901,7 +10621,9 @@ if (typeof module !== 'undefined' && module.exports) {
8901
10621
  if (typeof vfs.statSync === 'function') {
8902
10622
  isDir = vfs.statSync(full).isDirectory();
8903
10623
  }
8904
- } catch (_) {}
10624
+ } catch (err) {
10625
+ _shellLogger.debug('Glob statSync failed.', full, err);
10626
+ }
8905
10627
 
8906
10628
  if (isDir) {
8907
10629
  traverse(full, rel);
@@ -10223,7 +11945,9 @@ if (typeof module !== 'undefined' && module.exports) {
10223
11945
  : name;
10224
11946
  try {
10225
11947
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
10226
- } catch (_) {}
11948
+ } catch (err) {
11949
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
11950
+ }
10227
11951
  }
10228
11952
  }
10229
11953
  }
@@ -10327,8 +12051,9 @@ if (typeof module !== 'undefined' && module.exports) {
10327
12051
  }
10328
12052
  }
10329
12053
  }
10330
- } catch (_) {
12054
+ } catch (err) {
10331
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);
10332
12057
  }
10333
12058
 
10334
12059
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -10355,7 +12080,9 @@ if (typeof module !== 'undefined' && module.exports) {
10355
12080
  }
10356
12081
  }
10357
12082
  }
10358
- } catch (_) {}
12083
+ } catch (err) {
12084
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
12085
+ }
10359
12086
  }
10360
12087
 
10361
12088
  if (repoNotFound || !rawTreeEntries) {
@@ -10503,7 +12230,9 @@ if (typeof module !== 'undefined' && module.exports) {
10503
12230
  }));
10504
12231
  }
10505
12232
  }
10506
- } catch (_) {}
12233
+ } catch (err) {
12234
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
12235
+ }
10507
12236
 
10508
12237
  if (commits.length === 0) {
10509
12238
  commits = [
@@ -10569,7 +12298,9 @@ if (typeof module !== 'undefined' && module.exports) {
10569
12298
  try {
10570
12299
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
10571
12300
  return { path: p, data: parsed };
10572
- } catch (_) {}
12301
+ } catch (err) {
12302
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
12303
+ }
10573
12304
  }
10574
12305
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
10575
12306
  }
@@ -10610,13 +12341,20 @@ if (typeof module !== 'undefined' && module.exports) {
10610
12341
  vfs.rmdirSync(dirPath);
10611
12342
  }
10612
12343
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
10613
- } catch (_) {}
12344
+ } catch (err) {
12345
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
12346
+ }
10614
12347
  }
10615
12348
 
10616
12349
  // ---------------------------------------------------------------------------
10617
12350
  // Real npm package installation via the jsDelivr CDN
10618
12351
  // ---------------------------------------------------------------------------
10619
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
+ ];
10620
12358
 
10621
12359
  // Minimal offline registry, used only when the CDN is unreachable so common
10622
12360
  // demos still resolve without network access.
@@ -10762,16 +12500,23 @@ if (typeof module !== 'undefined' && module.exports) {
10762
12500
  }
10763
12501
 
10764
12502
  async function resolvePackageMetadata(fetchImpl, name, range) {
10765
- const urls = range
10766
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10767
- : [`${CDN_NPM_BASE}/${name}/package.json`];
10768
- for (const url of urls) {
10769
- const text = await fetchTextFromCdn(fetchImpl, url);
10770
- if (!text) continue;
10771
- try {
10772
- const parsed = JSON.parse(text);
10773
- if (parsed && parsed.version) return parsed;
10774
- } 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
+ }
10775
12520
  }
10776
12521
  return null;
10777
12522
  }
@@ -10789,6 +12534,7 @@ if (typeof module !== 'undefined' && module.exports) {
10789
12534
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10790
12535
  }
10791
12536
 
12537
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
10792
12538
  const version = meta.version;
10793
12539
  const key = `${name}@${version}`;
10794
12540
  if (seen.has(key)) {
@@ -10836,7 +12582,7 @@ if (typeof module !== 'undefined' && module.exports) {
10836
12582
  frontier = [];
10837
12583
  if (batch.length === 0) break;
10838
12584
  const texts = await Promise.all(
10839
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
12585
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
10840
12586
  );
10841
12587
  for (let idx = 0; idx < batch.length; idx++) {
10842
12588
  const rel = batch[idx];
@@ -10860,7 +12606,7 @@ if (typeof module !== 'undefined' && module.exports) {
10860
12606
  }
10861
12607
  // The declared entry may be missing on the CDN; fall back to index.js.
10862
12608
  if (!files.some(f => f.rel === entry)) {
10863
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
12609
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
10864
12610
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10865
12611
  }
10866
12612
 
@@ -10907,7 +12653,9 @@ if (typeof module !== 'undefined' && module.exports) {
10907
12653
  // directory target would otherwise raise EISDIR).
10908
12654
  try {
10909
12655
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10910
- } catch (_) {}
12656
+ } catch (err) {
12657
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
12658
+ }
10911
12659
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10912
12660
  ctx.vfs.writeFileSync(full, f.content);
10913
12661
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10982,9 +12730,35 @@ if (typeof module !== 'undefined' && module.exports) {
10982
12730
  }
10983
12731
  }
10984
12732
 
10985
- pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10986
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10987
-
12733
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
12734
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
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
+
10988
12762
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10989
12763
  }
10990
12764
 
@@ -11182,7 +12956,9 @@ if (typeof module !== 'undefined' && module.exports) {
11182
12956
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
11183
12957
  if (parsed && parsed.version) return parsed.version;
11184
12958
  }
11185
- } catch (_) {}
12959
+ } catch (err) {
12960
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
12961
+ }
11186
12962
  try {
11187
12963
  for (const dir of [rootDir, '/workspace']) {
11188
12964
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -11191,7 +12967,9 @@ if (typeof module !== 'undefined' && module.exports) {
11191
12967
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
11192
12968
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
11193
12969
  }
11194
- } catch (_) {}
12970
+ } catch (err) {
12971
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
12972
+ }
11195
12973
  return 'latest';
11196
12974
  }
11197
12975
 
@@ -11229,7 +13007,7 @@ if (typeof module !== 'undefined' && module.exports) {
11229
13007
  if (dirFlag) {
11230
13008
  walk(full, depth + 1);
11231
13009
  } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
11232
- 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); }
11233
13011
  }
11234
13012
  }
11235
13013
  };
@@ -11276,7 +13054,7 @@ if (typeof module !== 'undefined' && module.exports) {
11276
13054
 
11277
13055
  const handler = async (request) => {
11278
13056
  let pathname = '/';
11279
- 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); }
11280
13058
  const rel = pathname.replace(/^\/+/, '');
11281
13059
  let target = PosixPath.join(rootDir, rel);
11282
13060
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -11315,7 +13093,9 @@ if (typeof module !== 'undefined' && module.exports) {
11315
13093
  if (rm && typeof rm.transpileForBrowser === 'function') {
11316
13094
  body = rm.transpileForBrowser(body, target);
11317
13095
  }
11318
- } catch (_) {}
13096
+ } catch (err) {
13097
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
13098
+ }
11319
13099
  }
11320
13100
 
11321
13101
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -11323,7 +13103,7 @@ if (typeof module !== 'undefined' && module.exports) {
11323
13103
 
11324
13104
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
11325
13105
  return portTable.registerServer(port, {
11326
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
13106
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
11327
13107
  fetch: handler,
11328
13108
  name: 'code-lab-serve',
11329
13109
  pid,
@@ -11436,7 +13216,9 @@ if (typeof module !== 'undefined' && module.exports) {
11436
13216
  let isDir = false;
11437
13217
  try {
11438
13218
  isDir = ctx.vfs.statSync(resolved).isDirectory();
11439
- } catch (_) {}
13219
+ } catch (err) {
13220
+ _shellLogger.debug('cd statSync failed.', resolved, err);
13221
+ }
11440
13222
 
11441
13223
  if (!isDir) {
11442
13224
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -11536,7 +13318,9 @@ if (typeof module !== 'undefined' && module.exports) {
11536
13318
  isDirectory = st.isDirectory();
11537
13319
  size = st.size;
11538
13320
  mtimeMs = st.mtimeMs || Date.now();
11539
- } catch (_) {}
13321
+ } catch (err) {
13322
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
13323
+ }
11540
13324
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
11541
13325
  });
11542
13326
 
@@ -11956,7 +13740,9 @@ if (typeof module !== 'undefined' && module.exports) {
11956
13740
  if (st.isDirectory()) walk(full);
11957
13741
  else targets.push(full);
11958
13742
  }
11959
- } catch (_) {}
13743
+ } catch (err) {
13744
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
13745
+ }
11960
13746
  }
11961
13747
  if (ctx.vfs.existsSync(absRoot)) {
11962
13748
  const st = ctx.vfs.statSync(absRoot);
@@ -12080,7 +13866,9 @@ if (typeof module !== 'undefined' && module.exports) {
12080
13866
  let isDir = false;
12081
13867
  try {
12082
13868
  isDir = ctx.vfs.statSync(full).isDirectory();
12083
- } catch (_) {}
13869
+ } catch (err) {
13870
+ _shellLogger.debug('find statSync skipped.', full, err);
13871
+ }
12084
13872
 
12085
13873
  const relPath = root === '.'
12086
13874
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -12099,7 +13887,7 @@ if (typeof module !== 'undefined' && module.exports) {
12099
13887
  // Root itself check
12100
13888
  if (ctx.vfs.existsSync(absRoot)) {
12101
13889
  let isDir = false;
12102
- 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); }
12103
13891
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
12104
13892
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
12105
13893
  results.push(root);
@@ -13011,7 +14799,7 @@ if (typeof module !== 'undefined' && module.exports) {
13011
14799
  const isLast = i === entries.length - 1;
13012
14800
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
13013
14801
  let isDir = false;
13014
- 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); }
13015
14803
 
13016
14804
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
13017
14805
 
@@ -13239,10 +15027,10 @@ if (typeof module !== 'undefined' && module.exports) {
13239
15027
  for (const s of ctx.shell.portTable.listServers()) {
13240
15028
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
13241
15029
  if (s.server && typeof s.server.close === 'function') {
13242
- try { s.server.close(); } catch (_) {}
15030
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
13243
15031
  }
13244
15032
  if (typeof s.stop === 'function') {
13245
- try { s.stop(); } catch (_) {}
15033
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
13246
15034
  }
13247
15035
  ctx.shell.portTable.unregisterServer(s.port);
13248
15036
  killedPort = true;
@@ -15575,6 +17363,16 @@ if (typeof module !== 'undefined' && module.exports) {
15575
17363
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
15576
17364
  'use strict';
15577
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
+
15578
17376
  const ANSI_CODE_MAP = {
15579
17377
  1: 'cl-ansi-bold',
15580
17378
  2: 'cl-ansi-dim',
@@ -16115,7 +17913,7 @@ if (typeof module !== 'undefined' && module.exports) {
16115
17913
  if (!this.container || typeof this.container.querySelector !== 'function') return;
16116
17914
  const input = this.container.querySelector('#cl-repl-input');
16117
17915
  if (input && typeof input.focus === 'function') {
16118
- try { input.focus(); } catch (_) {}
17916
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
16119
17917
  }
16120
17918
  }
16121
17919
 
@@ -16139,9 +17937,9 @@ if (typeof module !== 'undefined' && module.exports) {
16139
17937
  }
16140
17938
  for (const entry of this._listeners) {
16141
17939
  if (typeof entry === 'function') {
16142
- try { entry(); } catch (_) {}
17940
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
16143
17941
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
16144
- 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); }
16145
17943
  }
16146
17944
  }
16147
17945
  this._listeners = [];
@@ -16210,7 +18008,9 @@ if (typeof module !== 'undefined' && module.exports) {
16210
18008
  try {
16211
18009
  const res = this.onKey(e);
16212
18010
  if (res === false) return;
16213
- } catch (_) {}
18011
+ } catch (err) {
18012
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
18013
+ }
16214
18014
  }
16215
18015
 
16216
18016
  const key = e.key;
@@ -16363,7 +18163,7 @@ if (typeof module !== 'undefined' && module.exports) {
16363
18163
  this.replMode = false;
16364
18164
  }
16365
18165
  if (this.onInterrupt) {
16366
- try { this.onInterrupt(); } catch (_) {}
18166
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
16367
18167
  }
16368
18168
  this.render();
16369
18169
  return;
@@ -16564,7 +18364,9 @@ if (typeof module !== 'undefined' && module.exports) {
16564
18364
  if (typeof nextInput.setSelectionRange === 'function') {
16565
18365
  nextInput.setSelectionRange(this.cursor, this.cursor);
16566
18366
  }
16567
- } catch (_) {}
18367
+ } catch (err) {
18368
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
18369
+ }
16568
18370
  }
16569
18371
  }
16570
18372
  }
@@ -16604,13 +18406,26 @@ if (typeof module !== 'undefined' && module.exports) {
16604
18406
  (function (root) {
16605
18407
  'use strict';
16606
18408
 
16607
- let terminalModule = null;
16608
- let shellModule = null;
16609
- 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;
16610
18419
  if (typeof require === 'function') {
16611
- try { terminalModule = require('./terminal.js'); } catch (_) {}
16612
- try { shellModule = require('./shell.js'); } catch (_) {}
16613
- 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
+ }
16614
18429
  }
16615
18430
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
16616
18431
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -16641,7 +18456,7 @@ if (typeof module !== 'undefined' && module.exports) {
16641
18456
 
16642
18457
  // The bundler rewrites this literal from package.json at build time. Keeping
16643
18458
  // the fallback in sync lets tests require src/workbench.js directly.
16644
- const CODELAB_VERSION = '0.1.7';
18459
+ const CODELAB_VERSION = '0.1.8';
16645
18460
 
16646
18461
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16647
18462
  const NODE_AMBIENT_DTS = `
@@ -16969,7 +18784,14 @@ declare module 'bun:sqlite' {
16969
18784
  }
16970
18785
  `;
16971
18786
 
18787
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
18788
+ (root && root.CodeLabHtml) ||
18789
+ null;
18790
+
16972
18791
  function escapeHtml(str) {
18792
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
18793
+ return _sharedHtmlMod.escapeHtml(str);
18794
+ }
16973
18795
  if (str == null) return '';
16974
18796
  return String(str)
16975
18797
  .replace(/&/g, '&amp;')
@@ -16979,6 +18801,18 @@ declare module 'bun:sqlite' {
16979
18801
  .replace(/'/g, '&#39;');
16980
18802
  }
16981
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
+
16982
18816
  // Schemes that may appear in a rendered href. Everything else
16983
18817
  // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16984
18818
  const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
@@ -17197,11 +19031,11 @@ declare module 'bun:sqlite' {
17197
19031
  if (!str) return '';
17198
19032
  let text = String(str);
17199
19033
 
17200
- // Markdown Links: [label](url "title") or [label](url)
17201
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
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) => {
17202
19036
  const cleanUrl = sanitizeUrl(url);
17203
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17204
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
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>`);
17205
19039
  });
17206
19040
 
17207
19041
  // Strikethrough: ~~del~~
@@ -17728,23 +19562,24 @@ declare module 'bun:sqlite' {
17728
19562
  let _workbenchInstanceCounter = 0;
17729
19563
  const _fallbackStorage = new Map();
17730
19564
 
17731
- // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17732
- // in src/preview-sw.js — keep both copies in sync.
17733
- const PREVIEW_CSP = [
17734
- "default-src 'self' data: blob:",
17735
- "base-uri 'self'",
17736
- "object-src 'none'",
17737
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17738
- "style-src 'self' 'unsafe-inline'",
17739
- "img-src 'self' data: blob:",
17740
- "font-src 'self' data:",
17741
- "connect-src 'self' data: blob:",
17742
- "media-src 'self' data: blob:",
17743
- "worker-src 'self' blob:",
17744
- "frame-src 'self' data: blob:",
17745
- "form-action 'self'",
17746
- "frame-ancestors 'self'"
17747
- ].join('; ');
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;
17748
19583
 
17749
19584
  function normalizePreviewOrigin(raw) {
17750
19585
  if (raw === null || raw === undefined || raw === '') return null;
@@ -17757,12 +19592,26 @@ declare module 'bun:sqlite' {
17757
19592
  }
17758
19593
  }
17759
19594
 
17760
- const LOG_PREFIX = '[code-lab]';
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'));
17761
19607
 
17762
19608
  // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17763
19609
  // into their own telemetry; `options.debug` enables verbose output. Errors
17764
19610
  // are never silently discarded.
17765
19611
  function createLogger(options = {}) {
19612
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
19613
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
19614
+ }
17766
19615
  const sink = options.logger;
17767
19616
  const debugEnabled = options.debug === true;
17768
19617
 
@@ -17772,8 +19621,9 @@ declare module 'bun:sqlite' {
17772
19621
  try {
17773
19622
  sink[level](...args);
17774
19623
  return;
17775
- } catch (_) {
17776
- // A broken host logger must not break the IDE; fall through.
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);
17777
19627
  }
17778
19628
  }
17779
19629
  const fn = typeof console !== 'undefined' ? console[level] : null;
@@ -17805,7 +19655,7 @@ declare module 'bun:sqlite' {
17805
19655
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17806
19656
  }
17807
19657
 
17808
- function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
19658
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
17809
19659
  const str = String(value);
17810
19660
  try {
17811
19661
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
@@ -17813,6 +19663,9 @@ declare module 'bun:sqlite' {
17813
19663
  return true;
17814
19664
  }
17815
19665
  } catch (err) {
19666
+ if (typeof onError === 'function') {
19667
+ onError(err);
19668
+ }
17816
19669
  if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17817
19670
  if (!safeStorageSet._warnedKeys.has(key)) {
17818
19671
  safeStorageSet._warnedKeys.add(key);
@@ -17836,6 +19689,8 @@ declare module 'bun:sqlite' {
17836
19689
  this.options = options || {};
17837
19690
  this.logger = createLogger({ logger: options.logger, debug: options.debug });
17838
19691
  this._persistenceFailureReported = false;
19692
+ this.saveStatusState = 'saved';
19693
+ this.saveStatusError = null;
17839
19694
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17840
19695
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17841
19696
  this.title = options.title || this.labId;
@@ -17843,6 +19698,7 @@ declare module 'bun:sqlite' {
17843
19698
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17844
19699
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17845
19700
  this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
19701
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
17846
19702
  this._previewIsolationWarned = false;
17847
19703
  if (options.previewOrigin && !this.previewOrigin) {
17848
19704
  this.logger.warn(
@@ -17921,12 +19777,15 @@ declare module 'bun:sqlite' {
17921
19777
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
17922
19778
  loading: false,
17923
19779
  error: null,
17924
- srcdoc: ''
19780
+ srcdoc: '',
19781
+ violations: []
17925
19782
  };
17926
19783
  this.previewHistory = [];
17927
19784
  this.previewHistoryIdx = -1;
17928
19785
  this._previewSwReady = false;
17929
19786
  this._previewSwRegistration = null;
19787
+ this._previewViolationHandler = null;
19788
+ this._swMessageHandler = null;
17930
19789
  this._portToasts = new Map();
17931
19790
  this.isFullscreen = false;
17932
19791
  this.isRunning = false;
@@ -18026,7 +19885,9 @@ declare module 'bun:sqlite' {
18026
19885
  onCommand: (cmd) => this._handleReplCommand(cmd),
18027
19886
  onInterrupt: () => this._handleInterrupt()
18028
19887
  });
18029
- } catch (_) {}
19888
+ } catch (err) {
19889
+ this.logger.debug('PTY engine initialization skipped.', err);
19890
+ }
18030
19891
  }
18031
19892
 
18032
19893
  this.shell = null;
@@ -18052,7 +19913,7 @@ declare module 'bun:sqlite' {
18052
19913
  intoRoot: options.cloneIntoRoot !== false,
18053
19914
  branch: options.branch || undefined,
18054
19915
  fetchImpl: options.fetchImpl || undefined
18055
- }).catch(() => {});
19916
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
18056
19917
  }
18057
19918
  }
18058
19919
 
@@ -18077,7 +19938,9 @@ declare module 'bun:sqlite' {
18077
19938
  }
18078
19939
  });
18079
19940
  this._syncFilesToShellVfs();
18080
- } catch (_) {}
19941
+ } catch (err) {
19942
+ this.logger.debug('POSIX shell initialization skipped.', err);
19943
+ }
18081
19944
  }
18082
19945
  }
18083
19946
 
@@ -18103,7 +19966,9 @@ declare module 'bun:sqlite' {
18103
19966
  const u = new URL(fullUrl);
18104
19967
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
18105
19968
  reqPath = u.pathname + (u.search || '');
18106
- } catch (_) {}
19969
+ } catch (err) {
19970
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
19971
+ }
18107
19972
  const method = String((init && init.method) || 'GET').toUpperCase();
18108
19973
  try {
18109
19974
  const res = await origDispatch(url, init);
@@ -18115,7 +19980,9 @@ declare module 'bun:sqlite' {
18115
19980
  } else if (res && res.body !== undefined) {
18116
19981
  bodyText = String(res.body);
18117
19982
  }
18118
- } catch (_) {}
19983
+ } catch (err) {
19984
+ this.logger.debug('Could not read response body for HTTP trace.', err);
19985
+ }
18119
19986
  const responseHeaders = {};
18120
19987
  if (res && res.headers) {
18121
19988
  if (typeof res.headers.forEach === 'function') {
@@ -18127,7 +19994,9 @@ declare module 'bun:sqlite' {
18127
19994
  let formattedBody = bodyText;
18128
19995
  try {
18129
19996
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
18130
- } catch (_) {}
19997
+ } catch (err) {
19998
+ void err;
19999
+ }
18131
20000
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
18132
20001
  this.lastHttpTrace.push({
18133
20002
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -18176,7 +20045,9 @@ declare module 'bun:sqlite' {
18176
20045
  vfs.writeFileSync(absPath, String(content ?? ''));
18177
20046
  }
18178
20047
  }
18179
- } catch (_) {}
20048
+ } catch (err) {
20049
+ this.logger.debug('Could not sync files to shell VFS.', err);
20050
+ }
18180
20051
  }
18181
20052
 
18182
20053
  _emitEvent(name, detail) {
@@ -18198,7 +20069,9 @@ declare module 'bun:sqlite' {
18198
20069
  if (shortName !== fullName) {
18199
20070
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
18200
20071
  }
18201
- } catch (_) {}
20072
+ } catch (err) {
20073
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
20074
+ }
18202
20075
  }
18203
20076
 
18204
20077
  _resolvedTheme() {
@@ -18232,13 +20105,26 @@ declare module 'bun:sqlite' {
18232
20105
  }
18233
20106
  }
18234
20107
 
18235
- _reportPersistenceFailure() {
18236
- if (this._persistenceFailureReported) return;
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;
18237
20121
  this._persistenceFailureReported = true;
18238
20122
  this.logger.warn(
18239
20123
  'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18240
20124
  );
18241
- this._emitEvent('persistence-error', { labId: this.labId });
20125
+ this._emitEvent('persistence-error', { labId: this.labId, error });
20126
+ this._emitEvent('error', error);
20127
+ return error;
18242
20128
  }
18243
20129
 
18244
20130
  _saveState() {
@@ -18262,22 +20148,35 @@ declare module 'bun:sqlite' {
18262
20148
  };
18263
20149
  this.savedState = state;
18264
20150
  if (this.options && this.options.persistState === false) {
20151
+ this.saveStatusState = 'saved';
20152
+ this.saveStatusError = null;
20153
+ this._updateStatusBar();
18265
20154
  return;
18266
20155
  }
20156
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
18267
20157
  const serialized = JSON.stringify(state);
20158
+ safeStorageSet._lastError = null;
20159
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
18268
20160
  const persisted = [
18269
- safeStorageSet(this._storageKey(), serialized, this.logger),
20161
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
18270
20162
  // Sync with host app sidebar & build overview progress trackers
18271
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18272
- safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
20163
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20164
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
18273
20165
  ];
18274
- if (persisted.includes(false)) this._reportPersistenceFailure();
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
+ }
18275
20174
  } catch (err) {
18276
20175
  this.logger.error(
18277
20176
  'Failed to save workbench state.',
18278
20177
  err && err.message ? err.message : err
18279
20178
  );
18280
- this._reportPersistenceFailure();
20179
+ this._reportPersistenceFailure(err);
18281
20180
  }
18282
20181
  }
18283
20182
 
@@ -18300,7 +20199,9 @@ declare module 'bun:sqlite' {
18300
20199
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
18301
20200
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
18302
20201
  }
18303
- } catch (_) {}
20202
+ } catch (err) {
20203
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
20204
+ }
18304
20205
  }
18305
20206
 
18306
20207
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -18347,6 +20248,7 @@ declare module 'bun:sqlite' {
18347
20248
  const dotEl = this.container.querySelector('#cl-status-dot');
18348
20249
  const textEl = this.container.querySelector('#cl-status-text');
18349
20250
  const fileEl = this.container.querySelector('#cl-status-file');
20251
+ const saveEl = this.container.querySelector('#cl-status-save');
18350
20252
  const durEl = this.container.querySelector('#cl-status-duration');
18351
20253
  const curEl = this.container.querySelector('#cl-status-cursor');
18352
20254
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -18358,6 +20260,24 @@ declare module 'bun:sqlite' {
18358
20260
  }
18359
20261
  if (textEl) textEl.textContent = this.runtimeStatusText;
18360
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
+ }
18361
20281
  if (durEl) {
18362
20282
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
18363
20283
  durEl.style.display = 'inline-flex';
@@ -18665,6 +20585,7 @@ declare module 'bun:sqlite' {
18665
20585
  </span>
18666
20586
  <span class="codelab-statusbar__sep">·</span>
18667
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>
18668
20589
  </div>
18669
20590
  <div class="codelab-statusbar__right">
18670
20591
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -19919,7 +21840,9 @@ declare module 'bun:sqlite' {
19919
21840
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
19920
21841
  try {
19921
21842
  this.ptyEngine.writeStreamChunk(rawText, type);
19922
- } catch (_) {}
21843
+ } catch (err) {
21844
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
21845
+ }
19923
21846
  }
19924
21847
 
19925
21848
  this._activeStreamType = type;
@@ -20051,14 +21974,18 @@ declare module 'bun:sqlite' {
20051
21974
  if (this._activeCommandAbortController) {
20052
21975
  try {
20053
21976
  this._activeCommandAbortController.abort('SIGINT');
20054
- } catch (_) {}
21977
+ } catch (err) {
21978
+ this.logger.debug('AbortController.abort failed.', err);
21979
+ }
20055
21980
  this._activeCommandAbortController = null;
20056
21981
  }
20057
21982
 
20058
21983
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
20059
21984
  try {
20060
21985
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
20061
- } catch (_) {}
21986
+ } catch (err) {
21987
+ this.logger.debug('cancelWorkerExecution failed.', err);
21988
+ }
20062
21989
  }
20063
21990
 
20064
21991
  this.isRunning = false;
@@ -20627,7 +22554,9 @@ declare module 'bun:sqlite' {
20627
22554
  try {
20628
22555
  const parsed = JSON.parse(responseBody);
20629
22556
  formattedBody = JSON.stringify(parsed, null, 2);
20630
- } catch (_) {}
22557
+ } catch (_) {
22558
+ formattedBody = responseBody;
22559
+ }
20631
22560
 
20632
22561
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
20633
22562
  const traceItem = {
@@ -20700,7 +22629,9 @@ declare module 'bun:sqlite' {
20700
22629
  if (this.drawerTab === 'ports') this._renderDrawerBody();
20701
22630
  this._dismissPortToast(port);
20702
22631
  }));
20703
- } catch (_) {}
22632
+ } catch (err) {
22633
+ this.logger.warn('Failed to attach portTable event listeners.', err);
22634
+ }
20704
22635
  }
20705
22636
 
20706
22637
  _updatePortsPill() {
@@ -20774,16 +22705,55 @@ declare module 'bun:sqlite' {
20774
22705
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
20775
22706
  try {
20776
22707
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
22708
+ this._swMessageHandler = onMessage;
20777
22709
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
20778
22710
  navigator.serviceWorker.addEventListener('message', onMessage);
20779
22711
  } else {
20780
22712
  navigator.serviceWorker.onmessage = onMessage;
20781
22713
  }
20782
22714
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
20783
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
20784
- .catch(() => { this._previewSwReady = false; });
20785
- } 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) {
20786
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));
20787
22757
  }
20788
22758
  }
20789
22759
 
@@ -20816,11 +22786,15 @@ declare module 'bun:sqlite' {
20816
22786
  } else if (res && res.headers) {
20817
22787
  Object.assign(outHeaders, res.headers);
20818
22788
  }
20819
- } catch (_) {}
22789
+ } catch (err) {
22790
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
22791
+ }
20820
22792
  let bodyText = '';
20821
22793
  try {
20822
22794
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
20823
- } catch (_) {}
22795
+ } catch (err) {
22796
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
22797
+ }
20824
22798
  return {
20825
22799
  status: (res && res.status) || 200,
20826
22800
  statusText: (res && res.statusText) || 'OK',
@@ -20847,44 +22821,170 @@ declare module 'bun:sqlite' {
20847
22821
  const p = Number(port) || 3000;
20848
22822
  const rawPath = pathAndQuery || '/';
20849
22823
  const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20850
- const base = this.previewOrigin || '';
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 : '';
20851
22827
  return `${base}/__preview/${p}${path}`;
20852
22828
  }
20853
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
+
20854
22847
  _warnPreviewIsolation() {
20855
- if (this.previewOrigin || this._previewIsolationWarned) return;
22848
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
20856
22849
  this._previewIsolationWarned = true;
20857
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20858
- console.warn(
20859
- '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20860
- 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20861
- );
20862
- }
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
+ );
20863
22856
  }
20864
22857
 
20865
22858
  _injectPreviewCsp(html, port) {
20866
22859
  if (typeof html !== 'string' || !html) return html;
20867
- if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20868
22860
 
20869
- const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20870
- (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
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;
20871
22873
 
22874
+ const injection = tags.join('');
20872
22875
  if (/<head\b[^>]*>/i.test(html)) {
20873
- return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
22876
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
20874
22877
  }
20875
22878
  if (/<html\b[^>]*>/i.test(html)) {
20876
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
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;
20877
22970
  }
20878
- return `<head>${tags}</head>${html}`;
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');
20879
22977
  }
20880
22978
 
20881
22979
  _openWebPreview(port, path = '/') {
20882
22980
  const p = Number(port) || this._firstListeningPort() || 3000;
20883
22981
  this._warnPreviewIsolation();
22982
+ this._installPreviewViolationListener();
20884
22983
  this.previewState.port = p;
20885
22984
  this.previewState.path = path || '/';
20886
22985
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
20887
22986
  this.previewState.error = null;
22987
+ this.previewState.violations = [];
20888
22988
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20889
22989
  this.previewHistory.push(this.previewState.url);
20890
22990
  this.previewHistoryIdx = this.previewHistory.length - 1;
@@ -20975,7 +23075,7 @@ declare module 'bun:sqlite' {
20975
23075
  try {
20976
23076
  const win = window.open(url, '_blank');
20977
23077
  if (win) {
20978
- try { win.opener = null; } catch (_) {}
23078
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
20979
23079
  opened = true;
20980
23080
  }
20981
23081
  } catch (_) { opened = false; }
@@ -20997,7 +23097,9 @@ declare module 'bun:sqlite' {
20997
23097
  const u = new URL(url);
20998
23098
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
20999
23099
  path = u.pathname + (u.search || '') + (u.hash || '');
21000
- } catch (_) {}
23100
+ } catch (err) {
23101
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
23102
+ }
21001
23103
  this.previewState.port = port;
21002
23104
  this.previewState.path = path;
21003
23105
  this.previewState.url = url;
@@ -21029,7 +23131,9 @@ declare module 'bun:sqlite' {
21029
23131
  const u = new URL(url);
21030
23132
  this.previewState.port = Number(u.port || 80);
21031
23133
  this.previewState.path = u.pathname + (u.search || '');
21032
- } catch (_) {}
23134
+ } catch (err) {
23135
+ this.logger.debug('Failed to parse preview history URL.', err);
23136
+ }
21033
23137
  const input = this.container.querySelector('#cl-preview-url-input');
21034
23138
  if (input) input.value = url;
21035
23139
  this._renderWebPreviewControls();
@@ -21063,9 +23167,11 @@ declare module 'bun:sqlite' {
21063
23167
  try {
21064
23168
  const u = new URL(url);
21065
23169
  popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
21066
- } catch (_) {}
23170
+ } catch (err) {
23171
+ this.logger.debug('Failed to parse popout preview URL.', err);
23172
+ }
21067
23173
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
21068
- 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); }
21069
23175
  }
21070
23176
  return popout;
21071
23177
  }
@@ -21092,6 +23198,19 @@ declare module 'bun:sqlite' {
21092
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('')
21093
23199
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
21094
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
+
21095
23214
  bodyEl.innerHTML = `
21096
23215
  <div class="codelab-preview">
21097
23216
  <div class="codelab-preview-chrome">
@@ -21107,10 +23226,12 @@ declare module 'bun:sqlite' {
21107
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>
21108
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>
21109
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>
21110
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>
21111
23232
  </div>
21112
23233
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
21113
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="same-origin" title="Web Preview"></iframe>
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>
21114
23235
  </div>
21115
23236
  ${servers.length
21116
23237
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -21123,6 +23244,7 @@ declare module 'bun:sqlite' {
21123
23244
  </div>`}
21124
23245
  </div>
21125
23246
  `;
23247
+ this._updatePreviewCspStatus();
21126
23248
  this._loadPreviewFrame();
21127
23249
  }
21128
23250
 
@@ -21150,7 +23272,9 @@ declare module 'bun:sqlite' {
21150
23272
  iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
21151
23273
  this.previewState.loading = false;
21152
23274
  return Promise.resolve();
21153
- } catch (_) {}
23275
+ } catch (err) {
23276
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
23277
+ }
21154
23278
  }
21155
23279
 
21156
23280
  // Fallback (no Service Worker): dispatch via the virtual port table and
@@ -21216,7 +23340,7 @@ declare module 'bun:sqlite' {
21216
23340
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
21217
23341
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
21218
23342
  let isDir = false;
21219
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
23343
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
21220
23344
  if (isDir) {
21221
23345
  shellWorkspaceFolders.add(rel);
21222
23346
  walk(full, rel);
@@ -21224,7 +23348,9 @@ declare module 'bun:sqlite' {
21224
23348
  try {
21225
23349
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
21226
23350
  shellWorkspaceFiles.set(rel, content);
21227
- } catch (_) {}
23351
+ } catch (err) {
23352
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
23353
+ }
21228
23354
  }
21229
23355
  }
21230
23356
  };
@@ -21526,6 +23652,27 @@ declare module 'bun:sqlite' {
21526
23652
  }
21527
23653
 
21528
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
+ }
21529
23676
  if (this.onCodeChange) {
21530
23677
  try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21531
23678
  }
@@ -21583,7 +23730,7 @@ declare module 'bun:sqlite' {
21583
23730
  if (fallbackWrap) fallbackWrap.style.display = 'none';
21584
23731
  if (mdPreview) mdPreview.style.display = 'none';
21585
23732
  if (this.editor) {
21586
- try { this.editor.setModel(null); } catch (_) {}
23733
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
21587
23734
  }
21588
23735
  if (emptyEl) {
21589
23736
  emptyEl.style.display = 'flex';
@@ -21895,7 +24042,9 @@ declare module 'bun:sqlite' {
21895
24042
  textarea.select();
21896
24043
  document.execCommand('copy');
21897
24044
  document.body.removeChild(textarea);
21898
- } catch (_) {}
24045
+ } catch (err) {
24046
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
24047
+ }
21899
24048
  };
21900
24049
 
21901
24050
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -22253,6 +24402,7 @@ declare module 'bun:sqlite' {
22253
24402
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
22254
24403
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
22255
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 }) },
22256
24406
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
22257
24407
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
22258
24408
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -22263,6 +24413,9 @@ declare module 'bun:sqlite' {
22263
24413
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
22264
24414
  } },
22265
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() },
22266
24419
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
22267
24420
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
22268
24421
  ];
@@ -22295,7 +24448,9 @@ declare module 'bun:sqlite' {
22295
24448
  input.focus();
22296
24449
  try {
22297
24450
  input.setSelectionRange(initialVal.length, initialVal.length);
22298
- } catch (_) {}
24451
+ } catch (err) {
24452
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
24453
+ }
22299
24454
 
22300
24455
  input.addEventListener('input', () => {
22301
24456
  this.paletteSelectedIndex = 0;
@@ -22568,7 +24723,7 @@ declare module 'bun:sqlite' {
22568
24723
  const onUp = ev => {
22569
24724
  vSplitter.classList.remove('is-dragging');
22570
24725
  shell.classList.remove('is-resizing');
22571
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24726
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22572
24727
  vSplitter.removeEventListener('pointermove', onMove);
22573
24728
  vSplitter.removeEventListener('pointerup', onUp);
22574
24729
  };
@@ -22609,7 +24764,7 @@ declare module 'bun:sqlite' {
22609
24764
  const onUp = ev => {
22610
24765
  hSplitter.classList.remove('is-dragging');
22611
24766
  shell.classList.remove('is-resizing-row');
22612
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24767
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22613
24768
  hSplitter.removeEventListener('pointermove', onMove);
22614
24769
  hSplitter.removeEventListener('pointerup', onUp);
22615
24770
  };
@@ -22636,7 +24791,7 @@ declare module 'bun:sqlite' {
22636
24791
  e.preventDefault();
22637
24792
  fSplitter.classList.add('is-dragging');
22638
24793
  shell.classList.add('is-resizing');
22639
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
24794
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
22640
24795
 
22641
24796
  const onMove = ev => {
22642
24797
  const ws = this.container.querySelector('.codelab-workspace');
@@ -22650,7 +24805,7 @@ declare module 'bun:sqlite' {
22650
24805
  const onUp = ev => {
22651
24806
  fSplitter.classList.remove('is-dragging');
22652
24807
  shell.classList.remove('is-resizing');
22653
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24808
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22654
24809
  fSplitter.removeEventListener('pointermove', onMove);
22655
24810
  fSplitter.removeEventListener('pointerup', onUp);
22656
24811
  this._saveState();
@@ -22993,7 +25148,9 @@ declare module 'bun:sqlite' {
22993
25148
  if (this.files['package.json']) {
22994
25149
  try {
22995
25150
  pkgJson = JSON.parse(this.files['package.json']);
22996
- } catch (_) {}
25151
+ } catch (err) {
25152
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
25153
+ }
22997
25154
  }
22998
25155
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
22999
25156
  pkgJson.dependencies = {};
@@ -23654,6 +25811,219 @@ declare module 'bun:sqlite' {
23654
25811
  return true;
23655
25812
  }
23656
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
+
23657
26027
  getFiles() {
23658
26028
  return { ...this.files };
23659
26029
  }
@@ -23661,7 +26031,7 @@ declare module 'bun:sqlite' {
23661
26031
  setFiles(filesMap) {
23662
26032
  if (!filesMap || typeof filesMap !== 'object') return;
23663
26033
  for (const model of this.models.values()) {
23664
- try { model.dispose(); } catch (_) {}
26034
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
23665
26035
  }
23666
26036
  this.models.clear();
23667
26037
  this.files = {};
@@ -23751,7 +26121,9 @@ declare module 'bun:sqlite' {
23751
26121
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
23752
26122
  try {
23753
26123
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
23754
- } catch (_) {}
26124
+ } catch (err) {
26125
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
26126
+ }
23755
26127
  }
23756
26128
  this._notifyCodeChange(clean, updated);
23757
26129
  }
@@ -23971,9 +26343,22 @@ declare module 'bun:sqlite' {
23971
26343
 
23972
26344
  destroy() {
23973
26345
  this.stopExecution();
26346
+ if (this._previewReloadTimer) {
26347
+ clearTimeout(this._previewReloadTimer);
26348
+ this._previewReloadTimer = null;
26349
+ }
23974
26350
  if (this._escHandler && typeof document !== 'undefined') {
23975
26351
  document.removeEventListener('keydown', this._escHandler);
23976
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;
23977
26362
  if (this._themeObserver) {
23978
26363
  this._themeObserver.disconnect();
23979
26364
  }
@@ -24034,7 +26419,9 @@ declare module 'bun:sqlite' {
24034
26419
  if (jsonScript && jsonScript.textContent) {
24035
26420
  try {
24036
26421
  inlineConfig = JSON.parse(jsonScript.textContent);
24037
- } catch (_) {}
26422
+ } catch (err) {
26423
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
26424
+ }
24038
26425
  }
24039
26426
 
24040
26427
  // Parse optional files JSON attribute
@@ -24043,7 +26430,9 @@ declare module 'bun:sqlite' {
24043
26430
  if (filesAttr) {
24044
26431
  try {
24045
26432
  attrFiles = JSON.parse(filesAttr);
24046
- } catch (_) {}
26433
+ } catch (err) {
26434
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
26435
+ }
24047
26436
  }
24048
26437
 
24049
26438
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -24086,6 +26475,19 @@ declare module 'bun:sqlite' {
24086
26475
  reset() { if (this._instance) this._instance.reset(); }
24087
26476
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
24088
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; }
24089
26491
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
24090
26492
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
24091
26493
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -24120,9 +26522,42 @@ declare module 'bun:sqlite' {
24120
26522
  Workbench: CodeLabWorkbench,
24121
26523
  CodeLabWorkbench,
24122
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 },
24123
26534
  Runtime: root.CodeLabRuntime,
24124
26535
  Shell: root.CodeLabShell,
24125
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,
24126
26561
  renderMarkdown: renderSimpleMarkdown,
24127
26562
  renderSimpleMarkdown: renderSimpleMarkdown,
24128
26563
  extensions: {
@@ -24185,6 +26620,48 @@ declare module 'bun:sqlite' {
24185
26620
  createVirtualHttp: CodeLabRuntime.createVirtualHttp,
24186
26621
  createVirtualNet: CodeLabRuntime.createVirtualNet,
24187
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,
24188
26665
  default: CodeLab
24189
26666
  });
24190
26667
  }