@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.
@@ -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
@@ -16,6 +16,1678 @@
16
16
  */
17
17
  const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : {};
18
18
 
19
+ // --- Module 0: Preview CSP, Structured Logger, Safe HTML & Leaf Engines ---
20
+ var CodeLabCsp = (() => {
21
+ var __defProp = Object.defineProperty;
22
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
23
+ var __getOwnPropNames = Object.getOwnPropertyNames;
24
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+
39
+ // src/csp.ts
40
+ var csp_exports = {};
41
+ __export(csp_exports, {
42
+ PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
43
+ buildPreviewPolicy: () => buildPreviewPolicy,
44
+ buildPreviewShims: () => buildPreviewShims,
45
+ default: () => csp_default,
46
+ describePreviewNetwork: () => describePreviewNetwork,
47
+ normalizeOrigin: () => normalizeOrigin,
48
+ normalizePreviewCspConfig: () => normalizePreviewCspConfig
49
+ });
50
+ var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
51
+ var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
52
+ var PRESETS = {
53
+ strict: {},
54
+ balanced: {
55
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
56
+ styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
57
+ fontSrc: FONT_CDNS.slice(),
58
+ connectSrc: IMPORT_MAP_CDNS.slice(),
59
+ imgSrc: ["https://cdn.jsdelivr.net"]
60
+ }
61
+ };
62
+ var SOURCE_KEYS = [
63
+ "scriptSrc",
64
+ "styleSrc",
65
+ "imgSrc",
66
+ "fontSrc",
67
+ "connectSrc",
68
+ "mediaSrc",
69
+ "workerSrc",
70
+ "frameSrc"
71
+ ];
72
+ var MAX_SOURCES = 64;
73
+ var MAX_SOURCE_LENGTH = 512;
74
+ var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
75
+ function normalizeOrigin(raw) {
76
+ if (raw === null || raw === void 0 || raw === "") return null;
77
+ try {
78
+ const parsed = new URL(String(raw));
79
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
80
+ return parsed.origin;
81
+ } catch (_) {
82
+ return null;
83
+ }
84
+ }
85
+ function normalizeMode(raw) {
86
+ if (raw === "strict" || raw === "custom") return raw;
87
+ return "balanced";
88
+ }
89
+ var ALLOWED_KEYWORDS = [
90
+ "'self'",
91
+ "'none'",
92
+ "'unsafe-inline'",
93
+ "'unsafe-eval'",
94
+ "'wasm-unsafe-eval'",
95
+ "'strict-dynamic'",
96
+ "'unsafe-hashes'"
97
+ ];
98
+ var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
99
+ function isSafeSource(source) {
100
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
101
+ }
102
+ function cleanSources(raw) {
103
+ if (!Array.isArray(raw)) return [];
104
+ const out = [];
105
+ for (const value of raw.slice(0, MAX_SOURCES)) {
106
+ if (typeof value !== "string") continue;
107
+ const source = value.trim();
108
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
109
+ if (!isSafeSource(source)) continue;
110
+ if (out.indexOf(source) === -1) out.push(source);
111
+ }
112
+ return out;
113
+ }
114
+ function unique(...lists) {
115
+ const out = [];
116
+ for (const list of lists) {
117
+ if (!list) continue;
118
+ for (const value of list) {
119
+ if (value && out.indexOf(value) === -1) out.push(value);
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+ function normalizePreviewCspConfig(raw) {
125
+ if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
126
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
127
+ return { mode: "balanced", allow: {} };
128
+ }
129
+ const input = raw;
130
+ const nested = input.allow;
131
+ const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
132
+ const allow = {};
133
+ for (const key of SOURCE_KEYS) {
134
+ const list = cleanSources(sources[key]);
135
+ if (list.length) allow[key] = list;
136
+ }
137
+ return { mode: normalizeMode(input.mode), allow };
138
+ }
139
+ function sourcesFor(mode, allow, key) {
140
+ const preset = mode === "custom" ? {} : PRESETS[mode];
141
+ return unique(preset[key], cleanSources(allow[key]));
142
+ }
143
+ function buildPreviewPolicy(options = {}) {
144
+ const mode = normalizeMode(options.mode);
145
+ const allow = options;
146
+ const host = normalizeOrigin(options.hostOrigin);
147
+ const self = host || "'self'";
148
+ const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
149
+ const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
150
+ const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
151
+ const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
152
+ return [
153
+ directive("default-src", [self, "data:", "blob:"]),
154
+ directive("base-uri", [self]),
155
+ "object-src 'none'",
156
+ directive("script-src", script()),
157
+ directive("style-src", style()),
158
+ directive("img-src", withData("imgSrc")),
159
+ directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
160
+ directive("connect-src", withData("connectSrc")),
161
+ directive("media-src", withData("mediaSrc")),
162
+ directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
163
+ directive("frame-src", withData("frameSrc")),
164
+ directive("form-action", [self]),
165
+ directive("frame-ancestors", [options.frameAncestors || "'self'"])
166
+ ].join("; ");
167
+ }
168
+ function describePreviewNetwork(config) {
169
+ const normalized = normalizePreviewCspConfig(config);
170
+ if (normalized.mode === "strict") return [];
171
+ const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
172
+ const hosts = [];
173
+ for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
174
+ for (const source of unique(preset[key], normalized.allow[key])) {
175
+ if (!/^https?:\/\//i.test(source)) continue;
176
+ let host;
177
+ try {
178
+ host = new URL(source).host;
179
+ } catch (_) {
180
+ continue;
181
+ }
182
+ if (hosts.indexOf(host) === -1) hosts.push(host);
183
+ }
184
+ }
185
+ return hosts;
186
+ }
187
+ function buildPreviewShims() {
188
+ return `<script ${PREVIEW_SHIM_MARKER}>
189
+ (function () {
190
+ 'use strict';
191
+ function memoryStorage() {
192
+ var data = new Map();
193
+ return {
194
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
195
+ setItem: function (k, v) { data.set(String(k), String(v)); },
196
+ removeItem: function (k) { data.delete(String(k)); },
197
+ clear: function () { data.clear(); },
198
+ key: function (i) { return Array.from(data.keys())[i] || null; },
199
+ get length() { return data.size; }
200
+ };
201
+ }
202
+ function shim(name) {
203
+ var blocked = false;
204
+ try {
205
+ var existing = window[name];
206
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
207
+ } catch (err) {
208
+ // Expected on an opaque origin: the accessor itself throws.
209
+ blocked = Boolean(err);
210
+ }
211
+ void blocked;
212
+ try {
213
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
214
+ } catch (err) {
215
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
216
+ }
217
+ }
218
+ shim('localStorage');
219
+ shim('sessionStorage');
220
+ document.addEventListener('securitypolicyviolation', function (event) {
221
+ try {
222
+ parent.postMessage({
223
+ type: 'codelab:preview-violation',
224
+ directive: event.effectiveDirective || event.violatedDirective || '',
225
+ blockedURI: event.blockedURI || '',
226
+ sourceFile: event.sourceFile || '',
227
+ line: event.lineNumber || 0
228
+ }, '*');
229
+ } catch (err) {
230
+ console.warn('[code-lab] preview: could not report CSP violation', err);
231
+ }
232
+ });
233
+ function serializeArg(arg) {
234
+ if (typeof arg !== 'object' || arg === null) return String(arg);
235
+ try {
236
+ return JSON.stringify(arg);
237
+ } catch (err) {
238
+ void err;
239
+ return '[Circular/Unserializable]';
240
+ }
241
+ }
242
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
243
+ var orig = console[level];
244
+ if (typeof orig !== 'function') return;
245
+ console[level] = function () {
246
+ var args = Array.prototype.slice.call(arguments);
247
+ try {
248
+ parent.postMessage({
249
+ type: 'codelab:preview-console',
250
+ level: level,
251
+ args: args.map(serializeArg)
252
+ }, '*');
253
+ } catch (err) {
254
+ void err;
255
+ }
256
+ return orig.apply(console, args);
257
+ };
258
+ });
259
+ function showPreviewErrorOverlay(msg, stack) {
260
+ try {
261
+ if (!document || !document.body) return;
262
+ var existing = document.getElementById('codelab-preview-error-overlay');
263
+ if (!existing) {
264
+ existing = document.createElement('div');
265
+ existing.id = 'codelab-preview-error-overlay';
266
+ existing.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,0.94);color:#f8fafc;font-family:ui-monospace,monospace;padding:24px;overflow:auto;';
267
+ document.body.appendChild(existing);
268
+ }
269
+ existing.textContent = '';
270
+ var header = document.createElement('div');
271
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
272
+ header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
273
+ var pre = document.createElement('pre');
274
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
275
+ pre.textContent = String(stack || msg || '');
276
+ existing.appendChild(header);
277
+ existing.appendChild(pre);
278
+ } catch (err) {
279
+ void err;
280
+ }
281
+ }
282
+ window.addEventListener('error', function (event) {
283
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
284
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
285
+ showPreviewErrorOverlay(msg, stack);
286
+ try {
287
+ parent.postMessage({
288
+ type: 'codelab:preview-error',
289
+ message: msg,
290
+ file: (event && event.filename) || null,
291
+ line: (event && event.lineno) || null,
292
+ col: (event && event.colno) || null,
293
+ stack: stack || null
294
+ }, '*');
295
+ } catch (err) {
296
+ void err;
297
+ }
298
+ });
299
+ window.addEventListener('unhandledrejection', function (event) {
300
+ var reason = event ? event.reason : null;
301
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
302
+ var stack = reason && reason.stack ? String(reason.stack) : '';
303
+ showPreviewErrorOverlay(msg, stack);
304
+ try {
305
+ parent.postMessage({
306
+ type: 'codelab:preview-error',
307
+ message: msg,
308
+ file: null,
309
+ line: null,
310
+ col: null,
311
+ stack: stack || null
312
+ }, '*');
313
+ } catch (err) {
314
+ void err;
315
+ }
316
+ });
317
+ })();
318
+ <\/script>`;
319
+ }
320
+ var csp_default = {
321
+ buildPreviewPolicy,
322
+ buildPreviewShims,
323
+ describePreviewNetwork,
324
+ normalizePreviewCspConfig,
325
+ normalizeOrigin,
326
+ PREVIEW_SHIM_MARKER
327
+ };
328
+ return __toCommonJS(csp_exports);
329
+ })();
330
+
331
+ var CodeLabLogger = (() => {
332
+ var __defProp = Object.defineProperty;
333
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
334
+ var __getOwnPropNames = Object.getOwnPropertyNames;
335
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
336
+ var __export = (target, all) => {
337
+ for (var name in all)
338
+ __defProp(target, name, { get: all[name], enumerable: true });
339
+ };
340
+ var __copyProps = (to, from, except, desc) => {
341
+ if (from && typeof from === "object" || typeof from === "function") {
342
+ for (let key of __getOwnPropNames(from))
343
+ if (!__hasOwnProp.call(to, key) && key !== except)
344
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
345
+ }
346
+ return to;
347
+ };
348
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
349
+
350
+ // src/logger.ts
351
+ var logger_exports = {};
352
+ __export(logger_exports, {
353
+ CodeLabError: () => CodeLabError,
354
+ DEFAULT_LOGGER: () => DEFAULT_LOGGER,
355
+ LOG_PREFIX: () => LOG_PREFIX,
356
+ createLogger: () => createLogger,
357
+ default: () => logger_default,
358
+ isCodeLabError: () => isCodeLabError
359
+ });
360
+ var LOG_PREFIX = "[code-lab]";
361
+ var CodeLabError = class extends Error {
362
+ code;
363
+ options;
364
+ cause;
365
+ recoverable;
366
+ details;
367
+ context;
368
+ constructor(code, message, options = {}) {
369
+ super(message);
370
+ this.name = "CodeLabError";
371
+ this.code = code;
372
+ this.options = options;
373
+ this.cause = options.cause;
374
+ this.recoverable = options.recoverable !== false;
375
+ const meta = options.details ?? options.context;
376
+ if (meta !== void 0) {
377
+ this.details = meta;
378
+ this.context = meta;
379
+ }
380
+ Object.setPrototypeOf(this, new.target.prototype);
381
+ }
382
+ };
383
+ function isCodeLabError(value) {
384
+ return Boolean(
385
+ value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
386
+ );
387
+ }
388
+ function createLogger(options = {}) {
389
+ const sink = options.logger ?? null;
390
+ const debugEnabled = options.debug === true;
391
+ const prefix = options.prefix || LOG_PREFIX;
392
+ const write = (level, args) => {
393
+ if (level === "debug" && !debugEnabled) return;
394
+ if (sink && typeof sink[level] === "function") {
395
+ let sinkError = null;
396
+ try {
397
+ sink[level](...args);
398
+ return;
399
+ } catch (err) {
400
+ sinkError = err;
401
+ }
402
+ }
403
+ const consoleObj = typeof console !== "undefined" ? console : null;
404
+ const fn = consoleObj ? consoleObj[level] : null;
405
+ if (typeof fn === "function") {
406
+ fn.call(consoleObj, prefix, ...args);
407
+ }
408
+ };
409
+ return {
410
+ debug: (...args) => write("debug", args),
411
+ info: (...args) => write("info", args),
412
+ warn: (...args) => write("warn", args),
413
+ error: (...args) => write("error", args)
414
+ };
415
+ }
416
+ var DEFAULT_LOGGER = createLogger();
417
+ var _loggerNamespace = {
418
+ LOG_PREFIX,
419
+ CodeLabError,
420
+ isCodeLabError,
421
+ createLogger,
422
+ DEFAULT_LOGGER
423
+ };
424
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
425
+ if (_globalRoot && !_globalRoot.CodeLabLogger) {
426
+ _globalRoot.CodeLabLogger = _loggerNamespace;
427
+ }
428
+ var logger_default = _loggerNamespace;
429
+ return __toCommonJS(logger_exports);
430
+ })();
431
+
432
+ var CodeLabHtml = (() => {
433
+ var __defProp = Object.defineProperty;
434
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
435
+ var __getOwnPropNames = Object.getOwnPropertyNames;
436
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
437
+ var __export = (target, all) => {
438
+ for (var name in all)
439
+ __defProp(target, name, { get: all[name], enumerable: true });
440
+ };
441
+ var __copyProps = (to, from, except, desc) => {
442
+ if (from && typeof from === "object" || typeof from === "function") {
443
+ for (let key of __getOwnPropNames(from))
444
+ if (!__hasOwnProp.call(to, key) && key !== except)
445
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
446
+ }
447
+ return to;
448
+ };
449
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
450
+
451
+ // src/html.ts
452
+ var html_exports = {};
453
+ __export(html_exports, {
454
+ default: () => html_default,
455
+ escapeHtml: () => escapeHtml,
456
+ html: () => html,
457
+ isSafeHtml: () => isSafeHtml,
458
+ raw: () => raw
459
+ });
460
+ var SAFE_HTML_BRAND = Symbol.for("codelab.SafeHtml");
461
+ var SafeHtmlImpl = class {
462
+ [SAFE_HTML_BRAND] = true;
463
+ __html;
464
+ constructor(trusted) {
465
+ this.__html = String(trusted);
466
+ }
467
+ toString() {
468
+ return this.__html;
469
+ }
470
+ };
471
+ function isSafeHtml(value) {
472
+ return Boolean(
473
+ value && typeof value === "object" && value[SAFE_HTML_BRAND] === true && typeof value.__html === "string"
474
+ );
475
+ }
476
+ function escapeHtml(value) {
477
+ if (value === null || value === void 0) return "";
478
+ if (isSafeHtml(value)) return value.__html;
479
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
480
+ }
481
+ function raw(trustedHtml) {
482
+ return new SafeHtmlImpl(trustedHtml);
483
+ }
484
+ function renderInterpolation(value) {
485
+ if (value === null || value === void 0 || value === false) return "";
486
+ if (isSafeHtml(value)) return value.__html;
487
+ if (Array.isArray(value)) {
488
+ let out = "";
489
+ for (let i = 0; i < value.length; i++) {
490
+ out += renderInterpolation(value[i]);
491
+ }
492
+ return out;
493
+ }
494
+ return escapeHtml(value);
495
+ }
496
+ function html(strings, ...values) {
497
+ let out = strings[0] ?? "";
498
+ for (let i = 0; i < values.length; i++) {
499
+ out += renderInterpolation(values[i]);
500
+ out += strings[i + 1] ?? "";
501
+ }
502
+ return new SafeHtmlImpl(out);
503
+ }
504
+ var _htmlNamespace = {
505
+ escapeHtml,
506
+ raw,
507
+ isSafeHtml,
508
+ html
509
+ };
510
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
511
+ if (_globalRoot && !_globalRoot.CodeLabHtml) {
512
+ _globalRoot.CodeLabHtml = _htmlNamespace;
513
+ }
514
+ var html_default = _htmlNamespace;
515
+ return __toCommonJS(html_exports);
516
+ })();
517
+
518
+ var CodeLabZip = (() => {
519
+ var __defProp = Object.defineProperty;
520
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
521
+ var __getOwnPropNames = Object.getOwnPropertyNames;
522
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
523
+ var __export = (target, all) => {
524
+ for (var name in all)
525
+ __defProp(target, name, { get: all[name], enumerable: true });
526
+ };
527
+ var __copyProps = (to, from, except, desc) => {
528
+ if (from && typeof from === "object" || typeof from === "function") {
529
+ for (let key of __getOwnPropNames(from))
530
+ if (!__hasOwnProp.call(to, key) && key !== except)
531
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
532
+ }
533
+ return to;
534
+ };
535
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
536
+
537
+ // src/zip.ts
538
+ var zip_exports = {};
539
+ __export(zip_exports, {
540
+ computeCrc32: () => computeCrc32,
541
+ createZip: () => createZip,
542
+ default: () => zip_default,
543
+ extractZip: () => extractZip,
544
+ sanitizeZipPath: () => sanitizeZipPath,
545
+ toUint8Array: () => toUint8Array
546
+ });
547
+ var LOCAL_FILE_HEADER_SIG = 67324752;
548
+ var CENTRAL_DIR_HEADER_SIG = 33639248;
549
+ var END_OF_CENTRAL_DIR_SIG = 101010256;
550
+ var UTF8_FLAG = 2048;
551
+ var CRC32_TABLE = new Uint32Array(256);
552
+ for (let i = 0; i < 256; i++) {
553
+ let c = i;
554
+ for (let k = 0; k < 8; k++) {
555
+ c = (c & 1) !== 0 ? 3988292384 ^ c >>> 1 : c >>> 1;
556
+ }
557
+ CRC32_TABLE[i] = c >>> 0;
558
+ }
559
+ var textEncoder = new TextEncoder();
560
+ var textDecoder = new TextDecoder("utf-8");
561
+ function toUint8Array(input) {
562
+ if (typeof input === "string") {
563
+ return textEncoder.encode(input);
564
+ }
565
+ if (input instanceof Uint8Array) {
566
+ return input;
567
+ }
568
+ if (input instanceof ArrayBuffer) {
569
+ return new Uint8Array(input);
570
+ }
571
+ return new Uint8Array(0);
572
+ }
573
+ function computeCrc32(data) {
574
+ const bytes = toUint8Array(data);
575
+ let crc = 4294967295;
576
+ for (let i = 0; i < bytes.length; i++) {
577
+ const index = (crc ^ bytes[i]) & 255;
578
+ crc = crc >>> 8 ^ CRC32_TABLE[index];
579
+ }
580
+ return (crc ^ 4294967295) >>> 0;
581
+ }
582
+ function sanitizeZipPath(rawPath) {
583
+ const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
584
+ const parts = normalized.split("/");
585
+ const safeParts = [];
586
+ for (const part of parts) {
587
+ const trimmed = part.trim();
588
+ if (!trimmed || trimmed === ".") continue;
589
+ if (trimmed === "..") {
590
+ if (safeParts.length > 0) {
591
+ safeParts.pop();
592
+ }
593
+ continue;
594
+ }
595
+ safeParts.push(trimmed);
596
+ }
597
+ return safeParts.join("/");
598
+ }
599
+ function writeUInt16LE(buf, offset, value) {
600
+ buf[offset] = value & 255;
601
+ buf[offset + 1] = value >>> 8 & 255;
602
+ }
603
+ function writeUInt32LE(buf, offset, value) {
604
+ buf[offset] = value & 255;
605
+ buf[offset + 1] = value >>> 8 & 255;
606
+ buf[offset + 2] = value >>> 16 & 255;
607
+ buf[offset + 3] = value >>> 24 & 255;
608
+ }
609
+ function readUInt16LE(buf, offset) {
610
+ return (buf[offset] | buf[offset + 1] << 8) >>> 0;
611
+ }
612
+ function readUInt32LE(buf, offset) {
613
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
614
+ }
615
+ async function createZip(files) {
616
+ const entries = [];
617
+ let localSectionSize = 0;
618
+ let centralDirSize = 0;
619
+ const rawKeys = Object.keys(files || {});
620
+ for (const rawKey of rawKeys) {
621
+ const safePath = sanitizeZipPath(rawKey);
622
+ if (!safePath) continue;
623
+ const rawContent = files[rawKey];
624
+ const dataBytes = toUint8Array(rawContent);
625
+ const nameBytes = textEncoder.encode(safePath);
626
+ const crc = computeCrc32(dataBytes);
627
+ entries.push({
628
+ nameBytes,
629
+ dataBytes,
630
+ crc32: crc,
631
+ offset: localSectionSize
632
+ });
633
+ localSectionSize += 30 + nameBytes.length + dataBytes.length;
634
+ centralDirSize += 46 + nameBytes.length;
635
+ }
636
+ const totalSize = localSectionSize + centralDirSize + 22;
637
+ const out = new Uint8Array(totalSize);
638
+ let cursor = 0;
639
+ for (const entry of entries) {
640
+ writeUInt32LE(out, cursor, LOCAL_FILE_HEADER_SIG);
641
+ writeUInt16LE(out, cursor + 4, 20);
642
+ writeUInt16LE(out, cursor + 6, UTF8_FLAG);
643
+ writeUInt16LE(out, cursor + 8, 0);
644
+ writeUInt16LE(out, cursor + 10, 0);
645
+ writeUInt16LE(out, cursor + 12, 8448);
646
+ writeUInt32LE(out, cursor + 14, entry.crc32);
647
+ writeUInt32LE(out, cursor + 18, entry.dataBytes.length);
648
+ writeUInt32LE(out, cursor + 22, entry.dataBytes.length);
649
+ writeUInt16LE(out, cursor + 26, entry.nameBytes.length);
650
+ writeUInt16LE(out, cursor + 28, 0);
651
+ cursor += 30;
652
+ out.set(entry.nameBytes, cursor);
653
+ cursor += entry.nameBytes.length;
654
+ out.set(entry.dataBytes, cursor);
655
+ cursor += entry.dataBytes.length;
656
+ }
657
+ const centralDirOffset = cursor;
658
+ for (const entry of entries) {
659
+ writeUInt32LE(out, cursor, CENTRAL_DIR_HEADER_SIG);
660
+ writeUInt16LE(out, cursor + 4, 20);
661
+ writeUInt16LE(out, cursor + 6, 20);
662
+ writeUInt16LE(out, cursor + 8, UTF8_FLAG);
663
+ writeUInt16LE(out, cursor + 10, 0);
664
+ writeUInt16LE(out, cursor + 12, 0);
665
+ writeUInt16LE(out, cursor + 14, 8448);
666
+ writeUInt32LE(out, cursor + 16, entry.crc32);
667
+ writeUInt32LE(out, cursor + 20, entry.dataBytes.length);
668
+ writeUInt32LE(out, cursor + 24, entry.dataBytes.length);
669
+ writeUInt16LE(out, cursor + 28, entry.nameBytes.length);
670
+ writeUInt16LE(out, cursor + 30, 0);
671
+ writeUInt16LE(out, cursor + 32, 0);
672
+ writeUInt16LE(out, cursor + 34, 0);
673
+ writeUInt16LE(out, cursor + 36, 0);
674
+ writeUInt32LE(out, cursor + 38, 0);
675
+ writeUInt32LE(out, cursor + 42, entry.offset);
676
+ cursor += 46;
677
+ out.set(entry.nameBytes, cursor);
678
+ cursor += entry.nameBytes.length;
679
+ }
680
+ writeUInt32LE(out, cursor, END_OF_CENTRAL_DIR_SIG);
681
+ writeUInt16LE(out, cursor + 4, 0);
682
+ writeUInt16LE(out, cursor + 6, 0);
683
+ writeUInt16LE(out, cursor + 8, entries.length);
684
+ writeUInt16LE(out, cursor + 10, entries.length);
685
+ writeUInt32LE(out, cursor + 12, centralDirSize);
686
+ writeUInt32LE(out, cursor + 16, centralDirOffset);
687
+ writeUInt16LE(out, cursor + 20, 0);
688
+ return out;
689
+ }
690
+ async function extractZip(data) {
691
+ const bytes = toUint8Array(data);
692
+ if (bytes.length < 22) {
693
+ throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
694
+ }
695
+ let eocdOffset = -1;
696
+ const minSearchOffset = Math.max(0, bytes.length - 65557);
697
+ for (let i = bytes.length - 22; i >= minSearchOffset; i--) {
698
+ if (readUInt32LE(bytes, i) === END_OF_CENTRAL_DIR_SIG) {
699
+ eocdOffset = i;
700
+ break;
701
+ }
702
+ }
703
+ if (eocdOffset === -1) {
704
+ throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
705
+ }
706
+ const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
707
+ const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
708
+ const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
709
+ if (centralDirOffset + centralDirSize > bytes.length) {
710
+ throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
711
+ }
712
+ const result = {};
713
+ let cdCursor = centralDirOffset;
714
+ for (let i = 0; i < totalEntries; i++) {
715
+ if (cdCursor + 46 > bytes.length) {
716
+ throw new Error("Corrupted ZIP archive: truncated Central Directory header");
717
+ }
718
+ const sig = readUInt32LE(bytes, cdCursor);
719
+ if (sig !== CENTRAL_DIR_HEADER_SIG) {
720
+ throw new Error(`Corrupted ZIP archive: invalid Central Directory signature 0x${sig.toString(16)}`);
721
+ }
722
+ const compressionMethod = readUInt16LE(bytes, cdCursor + 10);
723
+ const expectedCrc = readUInt32LE(bytes, cdCursor + 16);
724
+ const compressedSize = readUInt32LE(bytes, cdCursor + 20);
725
+ const fileNameLen = readUInt16LE(bytes, cdCursor + 28);
726
+ const extraLen = readUInt16LE(bytes, cdCursor + 30);
727
+ const commentLen = readUInt16LE(bytes, cdCursor + 32);
728
+ const localHeaderOffset = readUInt32LE(bytes, cdCursor + 42);
729
+ const nameStart = cdCursor + 46;
730
+ const nameEnd = nameStart + fileNameLen;
731
+ if (nameEnd > bytes.length) {
732
+ throw new Error("Corrupted ZIP archive: file name exceeds buffer");
733
+ }
734
+ const rawName = textDecoder.decode(bytes.subarray(nameStart, nameEnd));
735
+ cdCursor = nameEnd + extraLen + commentLen;
736
+ if (rawName.endsWith("/")) continue;
737
+ const safeName = sanitizeZipPath(rawName);
738
+ if (!safeName) continue;
739
+ if (localHeaderOffset + 30 > bytes.length) {
740
+ throw new Error(`Corrupted ZIP archive: local header offset out of bounds for ${safeName}`);
741
+ }
742
+ const localSig = readUInt32LE(bytes, localHeaderOffset);
743
+ if (localSig !== LOCAL_FILE_HEADER_SIG) {
744
+ throw new Error(`Corrupted ZIP archive: invalid Local File Header signature for ${safeName}`);
745
+ }
746
+ const localNameLen = readUInt16LE(bytes, localHeaderOffset + 26);
747
+ const localExtraLen = readUInt16LE(bytes, localHeaderOffset + 28);
748
+ const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
749
+ const dataEnd = dataStart + compressedSize;
750
+ if (dataEnd > bytes.length) {
751
+ throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
752
+ }
753
+ const rawFileBytes = bytes.subarray(dataStart, dataEnd);
754
+ if (compressionMethod !== 0) {
755
+ throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
756
+ }
757
+ const actualCrc = computeCrc32(rawFileBytes);
758
+ if (actualCrc !== expectedCrc) {
759
+ throw new Error(
760
+ `CRC32 integrity mismatch for ${safeName}: expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)}`
761
+ );
762
+ }
763
+ result[safeName] = textDecoder.decode(rawFileBytes);
764
+ }
765
+ return result;
766
+ }
767
+ var zip_default = {
768
+ createZip,
769
+ extractZip,
770
+ computeCrc32,
771
+ sanitizeZipPath,
772
+ toUint8Array
773
+ };
774
+ return __toCommonJS(zip_exports);
775
+ })();
776
+
777
+ var CodeLabStorage = (() => {
778
+ var __defProp = Object.defineProperty;
779
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
780
+ var __getOwnPropNames = Object.getOwnPropertyNames;
781
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
782
+ var __export = (target, all) => {
783
+ for (var name in all)
784
+ __defProp(target, name, { get: all[name], enumerable: true });
785
+ };
786
+ var __copyProps = (to, from, except, desc) => {
787
+ if (from && typeof from === "object" || typeof from === "function") {
788
+ for (let key of __getOwnPropNames(from))
789
+ if (!__hasOwnProp.call(to, key) && key !== except)
790
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
791
+ }
792
+ return to;
793
+ };
794
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
795
+
796
+ // src/storage.ts
797
+ var storage_exports = {};
798
+ __export(storage_exports, {
799
+ WorkspaceStorage: () => WorkspaceStorage,
800
+ createWorkspaceStorage: () => createWorkspaceStorage,
801
+ default: () => storage_default
802
+ });
803
+ var DEFAULT_DB_NAME = "codelab_workspace_db";
804
+ var DEFAULT_STORE_NAME = "projects";
805
+ var DEFAULT_LS_PREFIX = "codelab:project:";
806
+ function cloneProject(project) {
807
+ const filesCopy = {};
808
+ if (project.files && typeof project.files === "object") {
809
+ for (const [k, v] of Object.entries(project.files)) {
810
+ filesCopy[k] = String(v);
811
+ }
812
+ }
813
+ return {
814
+ id: String(project.id),
815
+ name: String(project.name || project.id),
816
+ files: filesCopy,
817
+ updatedAt: typeof project.updatedAt === "number" ? project.updatedAt : Date.now(),
818
+ ...project.createdAt !== void 0 ? { createdAt: project.createdAt } : {},
819
+ ...project.entry !== void 0 ? { entry: project.entry } : {},
820
+ ...project.testEntry !== void 0 ? { testEntry: project.testEntry } : {},
821
+ ...project.version !== void 0 ? { version: project.version } : {}
822
+ };
823
+ }
824
+ function isLocalStorageAvailable(prefix) {
825
+ try {
826
+ if (typeof globalThis === "undefined" || !("localStorage" in globalThis)) {
827
+ return false;
828
+ }
829
+ const ls = globalThis.localStorage;
830
+ if (!ls || typeof ls.getItem !== "function" || typeof ls.setItem !== "function") {
831
+ return false;
832
+ }
833
+ const probeKey = `${prefix}__probe__`;
834
+ ls.setItem(probeKey, "1");
835
+ ls.removeItem(probeKey);
836
+ return true;
837
+ } catch (err) {
838
+ const _ignored = err;
839
+ return false;
840
+ }
841
+ }
842
+ function isIndexedDbAvailable() {
843
+ try {
844
+ if (typeof globalThis === "undefined" || !("indexedDB" in globalThis)) {
845
+ return false;
846
+ }
847
+ return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === "function");
848
+ } catch (err) {
849
+ const _ignored = err;
850
+ return false;
851
+ }
852
+ }
853
+ var WorkspaceStorage = class {
854
+ dbName;
855
+ storeName;
856
+ storagePrefix;
857
+ backendType;
858
+ memoryStore = /* @__PURE__ */ new Map();
859
+ dbPromise = null;
860
+ constructor(options = {}) {
861
+ this.dbName = options.dbName || DEFAULT_DB_NAME;
862
+ this.storeName = options.storeName || DEFAULT_STORE_NAME;
863
+ this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
864
+ if (options.preferredBackend) {
865
+ this.backendType = options.preferredBackend;
866
+ } else if (isIndexedDbAvailable()) {
867
+ this.backendType = "indexeddb";
868
+ } else if (isLocalStorageAvailable(this.storagePrefix)) {
869
+ this.backendType = "localstorage";
870
+ } else {
871
+ this.backendType = "memory";
872
+ }
873
+ }
874
+ getBackendType() {
875
+ return this.backendType;
876
+ }
877
+ openIdb() {
878
+ if (this.dbPromise) return this.dbPromise;
879
+ this.dbPromise = new Promise((resolve) => {
880
+ try {
881
+ const req = globalThis.indexedDB.open(this.dbName, 1);
882
+ req.onupgradeneeded = () => {
883
+ const db = req.result;
884
+ if (!db.objectStoreNames.contains(this.storeName)) {
885
+ db.createObjectStore(this.storeName, { keyPath: "id" });
886
+ }
887
+ };
888
+ req.onsuccess = () => {
889
+ resolve(req.result);
890
+ };
891
+ req.onerror = () => {
892
+ resolve(null);
893
+ };
894
+ } catch (err) {
895
+ const _ignored = err;
896
+ resolve(null);
897
+ }
898
+ });
899
+ return this.dbPromise;
900
+ }
901
+ downgradeFromIdb() {
902
+ if (isLocalStorageAvailable(this.storagePrefix)) {
903
+ this.backendType = "localstorage";
904
+ } else {
905
+ this.backendType = "memory";
906
+ }
907
+ }
908
+ async saveProject(project) {
909
+ if (!project || typeof project.id !== "string" || !project.id.trim()) {
910
+ return false;
911
+ }
912
+ const normalized = cloneProject(project);
913
+ this.memoryStore.set(normalized.id, normalized);
914
+ if (this.backendType === "indexeddb") {
915
+ const db = await this.openIdb();
916
+ if (!db) {
917
+ this.downgradeFromIdb();
918
+ } else {
919
+ const ok = await new Promise((resolve) => {
920
+ try {
921
+ const tx = db.transaction(this.storeName, "readwrite");
922
+ const store = tx.objectStore(this.storeName);
923
+ const req = store.put(normalized);
924
+ req.onsuccess = () => resolve(true);
925
+ req.onerror = () => resolve(false);
926
+ } catch (err) {
927
+ const _ignored = err;
928
+ resolve(false);
929
+ }
930
+ });
931
+ if (ok) return true;
932
+ this.downgradeFromIdb();
933
+ }
934
+ }
935
+ if (this.backendType === "localstorage") {
936
+ try {
937
+ const key = `${this.storagePrefix}${normalized.id}`;
938
+ globalThis.localStorage.setItem(key, JSON.stringify(normalized));
939
+ return true;
940
+ } catch (err) {
941
+ const _ignored = err;
942
+ this.backendType = "memory";
943
+ }
944
+ }
945
+ return true;
946
+ }
947
+ async loadProject(id) {
948
+ if (!id || typeof id !== "string") return null;
949
+ if (this.backendType === "indexeddb") {
950
+ const db = await this.openIdb();
951
+ if (!db) {
952
+ this.downgradeFromIdb();
953
+ } else {
954
+ const found = await new Promise((resolve) => {
955
+ try {
956
+ const tx = db.transaction(this.storeName, "readonly");
957
+ const store = tx.objectStore(this.storeName);
958
+ const req = store.get(id);
959
+ req.onsuccess = () => {
960
+ const res = req.result;
961
+ resolve(res ? cloneProject(res) : null);
962
+ };
963
+ req.onerror = () => resolve(null);
964
+ } catch (err) {
965
+ const _ignored = err;
966
+ resolve(null);
967
+ }
968
+ });
969
+ if (found) return found;
970
+ }
971
+ }
972
+ if (this.backendType === "localstorage") {
973
+ try {
974
+ const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
975
+ if (raw) {
976
+ const parsed = JSON.parse(raw);
977
+ if (parsed && typeof parsed.id === "string" && parsed.files && typeof parsed.files === "object") {
978
+ return cloneProject(parsed);
979
+ }
980
+ }
981
+ } catch (err) {
982
+ const _ignored = err;
983
+ }
984
+ }
985
+ const fromMem = this.memoryStore.get(id);
986
+ return fromMem ? cloneProject(fromMem) : null;
987
+ }
988
+ async listProjects() {
989
+ const byId = /* @__PURE__ */ new Map();
990
+ const recordSummary = (proj) => {
991
+ if (!proj || typeof proj.id !== "string") return;
992
+ byId.set(proj.id, {
993
+ id: proj.id,
994
+ name: proj.name || proj.id,
995
+ updatedAt: typeof proj.updatedAt === "number" ? proj.updatedAt : Date.now(),
996
+ fileCount: proj.files && typeof proj.files === "object" ? Object.keys(proj.files).length : 0
997
+ });
998
+ };
999
+ for (const p of this.memoryStore.values()) {
1000
+ recordSummary(p);
1001
+ }
1002
+ if (this.backendType === "indexeddb") {
1003
+ const db = await this.openIdb();
1004
+ if (db) {
1005
+ await new Promise((resolve) => {
1006
+ try {
1007
+ const tx = db.transaction(this.storeName, "readonly");
1008
+ const store = tx.objectStore(this.storeName);
1009
+ const req = store.getAll();
1010
+ req.onsuccess = () => {
1011
+ const items = Array.isArray(req.result) ? req.result : [];
1012
+ for (const item of items) {
1013
+ recordSummary(item);
1014
+ }
1015
+ resolve();
1016
+ };
1017
+ req.onerror = () => resolve();
1018
+ } catch (err) {
1019
+ const _ignored = err;
1020
+ resolve();
1021
+ }
1022
+ });
1023
+ }
1024
+ } else if (this.backendType === "localstorage") {
1025
+ try {
1026
+ const ls = globalThis.localStorage;
1027
+ for (let i = 0; i < ls.length; i++) {
1028
+ const key = ls.key(i);
1029
+ if (key && key.startsWith(this.storagePrefix)) {
1030
+ const raw = ls.getItem(key);
1031
+ if (raw) {
1032
+ try {
1033
+ const parsed = JSON.parse(raw);
1034
+ recordSummary(parsed);
1035
+ } catch (parseErr) {
1036
+ const _ignored = parseErr;
1037
+ }
1038
+ }
1039
+ }
1040
+ }
1041
+ } catch (err) {
1042
+ const _ignored = err;
1043
+ }
1044
+ }
1045
+ return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
1046
+ }
1047
+ async deleteProject(id) {
1048
+ if (!id || typeof id !== "string") return false;
1049
+ let existed = this.memoryStore.delete(id);
1050
+ if (this.backendType === "indexeddb") {
1051
+ const db = await this.openIdb();
1052
+ if (db) {
1053
+ const idbDeleted = await new Promise((resolve) => {
1054
+ try {
1055
+ const tx = db.transaction(this.storeName, "readwrite");
1056
+ const store = tx.objectStore(this.storeName);
1057
+ const checkReq = store.get(id);
1058
+ checkReq.onsuccess = () => {
1059
+ if (!checkReq.result) {
1060
+ resolve(false);
1061
+ return;
1062
+ }
1063
+ const delReq = store.delete(id);
1064
+ delReq.onsuccess = () => resolve(true);
1065
+ delReq.onerror = () => resolve(false);
1066
+ };
1067
+ checkReq.onerror = () => resolve(false);
1068
+ } catch (err) {
1069
+ const _ignored = err;
1070
+ resolve(false);
1071
+ }
1072
+ });
1073
+ existed = existed || idbDeleted;
1074
+ }
1075
+ }
1076
+ if (this.backendType === "localstorage") {
1077
+ try {
1078
+ const key = `${this.storagePrefix}${id}`;
1079
+ if (globalThis.localStorage.getItem(key) !== null) {
1080
+ globalThis.localStorage.removeItem(key);
1081
+ existed = true;
1082
+ }
1083
+ } catch (err) {
1084
+ const _ignored = err;
1085
+ }
1086
+ }
1087
+ return existed;
1088
+ }
1089
+ };
1090
+ function createWorkspaceStorage(options = {}) {
1091
+ return new WorkspaceStorage(options);
1092
+ }
1093
+ var storage_default = {
1094
+ WorkspaceStorage,
1095
+ createWorkspaceStorage
1096
+ };
1097
+ return __toCommonJS(storage_exports);
1098
+ })();
1099
+
1100
+ var CodeLabSearch = (() => {
1101
+ var __defProp = Object.defineProperty;
1102
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1103
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1104
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1105
+ var __export = (target, all) => {
1106
+ for (var name in all)
1107
+ __defProp(target, name, { get: all[name], enumerable: true });
1108
+ };
1109
+ var __copyProps = (to, from, except, desc) => {
1110
+ if (from && typeof from === "object" || typeof from === "function") {
1111
+ for (let key of __getOwnPropNames(from))
1112
+ if (!__hasOwnProp.call(to, key) && key !== except)
1113
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1114
+ }
1115
+ return to;
1116
+ };
1117
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1118
+
1119
+ // src/search.ts
1120
+ var search_exports = {};
1121
+ __export(search_exports, {
1122
+ escapeRegex: () => escapeRegex,
1123
+ matchesGlob: () => matchesGlob,
1124
+ normalizeSearchPath: () => normalizeSearchPath,
1125
+ replaceInFiles: () => replaceInFiles,
1126
+ searchInFiles: () => searchInFiles
1127
+ });
1128
+ function escapeRegex(text) {
1129
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1130
+ }
1131
+ function normalizeSearchPath(filePath) {
1132
+ let p = filePath.replace(/\\/g, "/");
1133
+ while (p.startsWith("./")) {
1134
+ p = p.slice(2);
1135
+ }
1136
+ while (p.startsWith("/")) {
1137
+ p = p.slice(1);
1138
+ }
1139
+ return p;
1140
+ }
1141
+ function matchesGlob(filePath, pattern) {
1142
+ if (!pattern || pattern === "*" || pattern === "**") return true;
1143
+ const normPath = normalizeSearchPath(filePath);
1144
+ const normPattern = normalizeSearchPath(pattern);
1145
+ if (normPattern === normPath) return true;
1146
+ if (!normPattern.includes("*") && !normPattern.includes("?")) {
1147
+ return normPath.includes(normPattern) || normPath.endsWith(normPattern);
1148
+ }
1149
+ let regexStr = "^";
1150
+ let i = 0;
1151
+ while (i < normPattern.length) {
1152
+ const c = normPattern[i];
1153
+ if (c === "*") {
1154
+ if (normPattern[i + 1] === "*") {
1155
+ regexStr += ".*";
1156
+ i += 2;
1157
+ if (normPattern[i] === "/") {
1158
+ i++;
1159
+ }
1160
+ continue;
1161
+ } else {
1162
+ regexStr += "[^/]*";
1163
+ i++;
1164
+ continue;
1165
+ }
1166
+ } else if (c === "?") {
1167
+ regexStr += "[^/]";
1168
+ i++;
1169
+ continue;
1170
+ } else if ("./+^$()|[]{}\\".includes(c)) {
1171
+ regexStr += "\\" + c;
1172
+ i++;
1173
+ continue;
1174
+ } else {
1175
+ regexStr += c;
1176
+ i++;
1177
+ }
1178
+ }
1179
+ regexStr += "$";
1180
+ try {
1181
+ const re = new RegExp(regexStr);
1182
+ return re.test(normPath);
1183
+ } catch (err) {
1184
+ return normPath.includes(normPattern.replace(/[*?]/g, ""));
1185
+ }
1186
+ }
1187
+ function checkFilter(path, filter) {
1188
+ if (!filter) return true;
1189
+ if (Array.isArray(filter)) {
1190
+ return filter.some((f) => matchesGlob(path, f));
1191
+ }
1192
+ return matchesGlob(path, filter);
1193
+ }
1194
+ function createSearchResult(groups, totalMatches, fileCount, query, error) {
1195
+ const arr = [...groups];
1196
+ const result = Object.assign(arr, {
1197
+ matches: groups,
1198
+ totalMatches,
1199
+ fileCount,
1200
+ filesCount: fileCount,
1201
+ query,
1202
+ durationMs: 0,
1203
+ error
1204
+ });
1205
+ return result;
1206
+ }
1207
+ function searchInFiles(files, queryOrOptions, optionsOrUndefined) {
1208
+ let query = "";
1209
+ let opts = {};
1210
+ if (typeof queryOrOptions === "string") {
1211
+ query = queryOrOptions;
1212
+ opts = optionsOrUndefined || {};
1213
+ } else if (queryOrOptions && typeof queryOrOptions === "object") {
1214
+ opts = queryOrOptions;
1215
+ query = opts.query || "";
1216
+ }
1217
+ if (!query) {
1218
+ return createSearchResult([], 0, 0, query);
1219
+ }
1220
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1221
+ const isWholeWord = Boolean(opts.wholeWord);
1222
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1223
+ const maxMatches = opts.maxMatches ?? 1e4;
1224
+ const maxMatchesPerFile = opts.maxMatchesPerFile ?? 1e3;
1225
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1226
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1227
+ let patternStr = isRegex ? query : escapeRegex(query);
1228
+ if (isWholeWord) {
1229
+ patternStr = `\\b${patternStr}\\b`;
1230
+ }
1231
+ let regex = /(?:)/;
1232
+ try {
1233
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1234
+ } catch (err) {
1235
+ const _err = err;
1236
+ const msg = typeof _err === "object" && _err && "message" in _err ? String(_err.message) : "Invalid regular expression";
1237
+ return createSearchResult([], 0, 0, query, msg);
1238
+ }
1239
+ const matchedGroups = [];
1240
+ let totalMatches = 0;
1241
+ for (const [filePath, content] of Object.entries(files)) {
1242
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1243
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1244
+ if (opts.targetFiles && !opts.targetFiles.includes(filePath)) continue;
1245
+ const fileMatches = [];
1246
+ const lines = content.split("\n");
1247
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1248
+ const lineText = lines[lineIndex];
1249
+ regex.lastIndex = 0;
1250
+ let m = null;
1251
+ while ((m = regex.exec(lineText)) !== null) {
1252
+ const matchLen = m[0].length;
1253
+ const col = m.index + 1;
1254
+ fileMatches.push({
1255
+ line: lineIndex + 1,
1256
+ col,
1257
+ column: col,
1258
+ length: matchLen,
1259
+ matchText: m[0],
1260
+ lineText,
1261
+ beforeSnippet: lineText.slice(0, m.index),
1262
+ afterSnippet: lineText.slice(m.index + matchLen),
1263
+ matchIndex: m.index,
1264
+ matchEndIndex: m.index + matchLen
1265
+ });
1266
+ totalMatches++;
1267
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1268
+ break;
1269
+ }
1270
+ if (matchLen === 0) {
1271
+ regex.lastIndex++;
1272
+ if (regex.lastIndex > lineText.length) {
1273
+ break;
1274
+ }
1275
+ }
1276
+ }
1277
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1278
+ break;
1279
+ }
1280
+ }
1281
+ if (fileMatches.length > 0) {
1282
+ matchedGroups.push({
1283
+ file: filePath,
1284
+ matches: fileMatches
1285
+ });
1286
+ }
1287
+ if (totalMatches >= maxMatches) {
1288
+ break;
1289
+ }
1290
+ }
1291
+ return createSearchResult(matchedGroups, totalMatches, matchedGroups.length, query);
1292
+ }
1293
+ function replaceInFiles(files, arg2, arg3, arg4) {
1294
+ let query = "";
1295
+ const replacement = typeof arg3 === "string" ? arg3 : "";
1296
+ let opts = {};
1297
+ let targetFiles = void 0;
1298
+ if (typeof arg2 === "string") {
1299
+ query = arg2;
1300
+ if (Array.isArray(arg4)) {
1301
+ targetFiles = arg4;
1302
+ } else if (arg4 && typeof arg4 === "object") {
1303
+ opts = arg4;
1304
+ targetFiles = opts.targetFiles;
1305
+ }
1306
+ } else if (arg2 && typeof arg2 === "object") {
1307
+ opts = arg2;
1308
+ query = opts.query || "";
1309
+ if (Array.isArray(arg4)) {
1310
+ targetFiles = arg4;
1311
+ } else {
1312
+ targetFiles = opts.targetFiles;
1313
+ }
1314
+ }
1315
+ if (!query) {
1316
+ return {
1317
+ updatedFiles: { ...files },
1318
+ replacedCount: 0,
1319
+ filesAffected: []
1320
+ };
1321
+ }
1322
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1323
+ const isWholeWord = Boolean(opts.wholeWord);
1324
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1325
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1326
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1327
+ let patternStr = isRegex ? query : escapeRegex(query);
1328
+ if (isWholeWord) {
1329
+ patternStr = `\\b${patternStr}\\b`;
1330
+ }
1331
+ let regex = /(?:)/;
1332
+ try {
1333
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1334
+ } catch (err) {
1335
+ return {
1336
+ updatedFiles: { ...files },
1337
+ replacedCount: 0,
1338
+ filesAffected: []
1339
+ };
1340
+ }
1341
+ const updatedFiles = { ...files };
1342
+ const filesAffected = [];
1343
+ let replacedCount = 0;
1344
+ for (const [filePath, content] of Object.entries(files)) {
1345
+ if (targetFiles && !targetFiles.includes(filePath)) continue;
1346
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1347
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1348
+ regex.lastIndex = 0;
1349
+ let countInFile = 0;
1350
+ let m;
1351
+ while ((m = regex.exec(content)) !== null) {
1352
+ countInFile++;
1353
+ if (m[0].length === 0) {
1354
+ regex.lastIndex++;
1355
+ if (regex.lastIndex > content.length) {
1356
+ break;
1357
+ }
1358
+ }
1359
+ }
1360
+ if (countInFile > 0) {
1361
+ regex.lastIndex = 0;
1362
+ let newContent;
1363
+ if (isRegex) {
1364
+ newContent = content.replace(regex, replacement);
1365
+ } else {
1366
+ newContent = content.replace(regex, () => replacement);
1367
+ }
1368
+ updatedFiles[filePath] = newContent;
1369
+ filesAffected.push(filePath);
1370
+ replacedCount += countInFile;
1371
+ }
1372
+ }
1373
+ return {
1374
+ updatedFiles,
1375
+ replacedCount,
1376
+ filesAffected
1377
+ };
1378
+ }
1379
+ return __toCommonJS(search_exports);
1380
+ })();
1381
+
1382
+ var CodeLabDiagnostics = (() => {
1383
+ var __defProp = Object.defineProperty;
1384
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1385
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1386
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1387
+ var __export = (target, all) => {
1388
+ for (var name in all)
1389
+ __defProp(target, name, { get: all[name], enumerable: true });
1390
+ };
1391
+ var __copyProps = (to, from, except, desc) => {
1392
+ if (from && typeof from === "object" || typeof from === "function") {
1393
+ for (let key of __getOwnPropNames(from))
1394
+ if (!__hasOwnProp.call(to, key) && key !== except)
1395
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1396
+ }
1397
+ return to;
1398
+ };
1399
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1400
+
1401
+ // src/diagnostics.ts
1402
+ var diagnostics_exports = {};
1403
+ __export(diagnostics_exports, {
1404
+ DiagnosticsStore: () => DiagnosticsStore,
1405
+ createDiagnosticsStore: () => createDiagnosticsStore,
1406
+ default: () => diagnostics_default
1407
+ });
1408
+ var DiagnosticsStore = class {
1409
+ items = /* @__PURE__ */ new Map();
1410
+ listeners = /* @__PURE__ */ new Set();
1411
+ add(item) {
1412
+ if (!item || typeof item.id !== "string" || !item.id) return;
1413
+ const normalized = {
1414
+ ...item,
1415
+ file: String(item.file || ""),
1416
+ line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
1417
+ col: typeof item.col === "number" && item.col > 0 ? Math.floor(item.col) : typeof item.column === "number" && item.column > 0 ? Math.floor(item.column) : 1,
1418
+ message: String(item.message || ""),
1419
+ severity: item.severity || "error"
1420
+ };
1421
+ this.items.set(normalized.id, normalized);
1422
+ this.notify();
1423
+ }
1424
+ remove(id) {
1425
+ if (this.items.delete(id)) {
1426
+ this.notify();
1427
+ }
1428
+ }
1429
+ clear(source) {
1430
+ if (source !== void 0 && source !== "") {
1431
+ let changed = false;
1432
+ for (const [id, item] of this.items.entries()) {
1433
+ if (item.source === source) {
1434
+ this.items.delete(id);
1435
+ changed = true;
1436
+ }
1437
+ }
1438
+ if (changed) {
1439
+ this.notify();
1440
+ }
1441
+ } else if (this.items.size > 0) {
1442
+ this.items.clear();
1443
+ this.notify();
1444
+ }
1445
+ }
1446
+ getAll() {
1447
+ return Array.from(this.items.values());
1448
+ }
1449
+ getByFile(file) {
1450
+ const out = [];
1451
+ for (const item of this.items.values()) {
1452
+ if (item.file === file) {
1453
+ out.push(item);
1454
+ }
1455
+ }
1456
+ return out;
1457
+ }
1458
+ subscribe(listener) {
1459
+ this.listeners.add(listener);
1460
+ return () => {
1461
+ this.listeners.delete(listener);
1462
+ };
1463
+ }
1464
+ notify() {
1465
+ if (this.listeners.size === 0) return;
1466
+ const snapshot = this.getAll();
1467
+ for (const listener of this.listeners) {
1468
+ try {
1469
+ listener(snapshot);
1470
+ } catch (err) {
1471
+ console.warn("[code-lab] diagnostics subscriber error:", err);
1472
+ }
1473
+ }
1474
+ }
1475
+ };
1476
+ function createDiagnosticsStore() {
1477
+ return new DiagnosticsStore();
1478
+ }
1479
+ var diagnostics_default = {
1480
+ DiagnosticsStore,
1481
+ createDiagnosticsStore
1482
+ };
1483
+ return __toCommonJS(diagnostics_exports);
1484
+ })();
1485
+
1486
+ var CodeLabScm = (() => {
1487
+ var __defProp = Object.defineProperty;
1488
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1489
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1490
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1491
+ var __export = (target, all) => {
1492
+ for (var name in all)
1493
+ __defProp(target, name, { get: all[name], enumerable: true });
1494
+ };
1495
+ var __copyProps = (to, from, except, desc) => {
1496
+ if (from && typeof from === "object" || typeof from === "function") {
1497
+ for (let key of __getOwnPropNames(from))
1498
+ if (!__hasOwnProp.call(to, key) && key !== except)
1499
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1500
+ }
1501
+ return to;
1502
+ };
1503
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1504
+
1505
+ // src/scm.ts
1506
+ var scm_exports = {};
1507
+ __export(scm_exports, {
1508
+ commitChanges: () => commitChanges,
1509
+ computeGitStatus: () => computeGitStatus,
1510
+ computeShortCommitHash: () => computeShortCommitHash,
1511
+ createGitState: () => createGitState,
1512
+ default: () => scm_default,
1513
+ stageFile: () => stageFile,
1514
+ unstageFile: () => unstageFile
1515
+ });
1516
+ function computeShortCommitHash(input) {
1517
+ let h1 = 3735928559 ^ input.length;
1518
+ let h2 = 1103547991 ^ input.length;
1519
+ for (let i = 0; i < input.length; i++) {
1520
+ const ch = input.charCodeAt(i);
1521
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1522
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1523
+ }
1524
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1525
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1526
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
1527
+ return combined.toString(16).padStart(7, "0").slice(0, 7);
1528
+ }
1529
+ function createGitState(initialFiles = {}, branch = "main") {
1530
+ const headFiles = { ...initialFiles };
1531
+ const initialHash = computeShortCommitHash(JSON.stringify(headFiles) + ":init");
1532
+ return {
1533
+ branch,
1534
+ branches: [branch],
1535
+ headCommit: initialHash,
1536
+ headFiles,
1537
+ staged: /* @__PURE__ */ new Map(),
1538
+ commits: [
1539
+ {
1540
+ hash: initialHash,
1541
+ message: "Initial commit",
1542
+ timestamp: Date.now(),
1543
+ files: { ...headFiles }
1544
+ }
1545
+ ]
1546
+ };
1547
+ }
1548
+ function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1549
+ const state = gitState || createGitState({});
1550
+ const headFiles = state.headFiles || {};
1551
+ const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1552
+ const untracked = [];
1553
+ const modified = [];
1554
+ const deleted = [];
1555
+ const staged = [];
1556
+ for (const [filePath, stagedContent] of currentStaged.entries()) {
1557
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1558
+ if (stagedContent === null) {
1559
+ staged.push({
1560
+ path: filePath,
1561
+ status: "deleted",
1562
+ staged: true,
1563
+ oldContent: headFiles[filePath]
1564
+ });
1565
+ } else {
1566
+ staged.push({
1567
+ path: filePath,
1568
+ status: inHead ? "modified" : "added",
1569
+ staged: true,
1570
+ oldContent: inHead ? headFiles[filePath] : void 0,
1571
+ newContent: stagedContent
1572
+ });
1573
+ }
1574
+ }
1575
+ for (const [filePath, content] of Object.entries(vfsFiles || {})) {
1576
+ if (currentStaged.has(filePath)) {
1577
+ const stagedVal = currentStaged.get(filePath);
1578
+ if (stagedVal !== content) {
1579
+ modified.push({
1580
+ path: filePath,
1581
+ status: "modified",
1582
+ staged: false,
1583
+ oldContent: stagedVal ?? void 0,
1584
+ newContent: content
1585
+ });
1586
+ }
1587
+ } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
1588
+ if (headFiles[filePath] !== content) {
1589
+ modified.push({
1590
+ path: filePath,
1591
+ status: "modified",
1592
+ staged: false,
1593
+ oldContent: headFiles[filePath],
1594
+ newContent: content
1595
+ });
1596
+ }
1597
+ } else {
1598
+ untracked.push({
1599
+ path: filePath,
1600
+ status: "untracked",
1601
+ staged: false,
1602
+ newContent: content
1603
+ });
1604
+ }
1605
+ }
1606
+ for (const filePath of Object.keys(headFiles)) {
1607
+ if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath) && !currentStaged.has(filePath)) {
1608
+ deleted.push({
1609
+ path: filePath,
1610
+ status: "deleted",
1611
+ staged: false,
1612
+ oldContent: headFiles[filePath]
1613
+ });
1614
+ }
1615
+ }
1616
+ const unstaged = [...modified, ...deleted];
1617
+ const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1618
+ return {
1619
+ branch: state.branch || "main",
1620
+ headCommit: state.headCommit || "",
1621
+ untracked,
1622
+ modified,
1623
+ deleted,
1624
+ staged,
1625
+ unstaged,
1626
+ hasChanges: !isClean,
1627
+ isClean
1628
+ };
1629
+ }
1630
+ function stageFile(gitState, relativePath, currentContent) {
1631
+ if (!gitState) return;
1632
+ if (!(gitState.staged instanceof Map)) {
1633
+ gitState.staged = /* @__PURE__ */ new Map();
1634
+ }
1635
+ gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1636
+ }
1637
+ function unstageFile(gitState, relativePath) {
1638
+ if (!gitState || !(gitState.staged instanceof Map)) return;
1639
+ gitState.staged.delete(relativePath);
1640
+ }
1641
+ function commitChanges(gitState, message) {
1642
+ const trimmed = typeof message === "string" ? message.trim() : "";
1643
+ if (!trimmed) {
1644
+ throw new Error("Commit message cannot be empty");
1645
+ }
1646
+ if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1647
+ throw new Error("Nothing to commit (staging area is empty)");
1648
+ }
1649
+ const newHeadFiles = { ...gitState.headFiles || {} };
1650
+ for (const [filePath, content] of gitState.staged.entries()) {
1651
+ if (content === null) {
1652
+ delete newHeadFiles[filePath];
1653
+ } else {
1654
+ newHeadFiles[filePath] = content;
1655
+ }
1656
+ }
1657
+ const timestamp = Date.now();
1658
+ const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1659
+ const commit = {
1660
+ hash,
1661
+ message: trimmed,
1662
+ timestamp,
1663
+ files: newHeadFiles
1664
+ };
1665
+ if (!Array.isArray(gitState.commits)) {
1666
+ gitState.commits = [];
1667
+ }
1668
+ gitState.commits.push(commit);
1669
+ gitState.headCommit = hash;
1670
+ gitState.headFiles = newHeadFiles;
1671
+ gitState.staged.clear();
1672
+ return hash;
1673
+ }
1674
+ var scm_default = {
1675
+ createGitState,
1676
+ computeGitStatus,
1677
+ stageFile,
1678
+ unstageFile,
1679
+ commitChanges,
1680
+ computeShortCommitHash
1681
+ };
1682
+ return __toCommonJS(scm_exports);
1683
+ })();
1684
+
1685
+ _root.CodeLabZip = CodeLabZip;
1686
+ _root.CodeLabStorage = CodeLabStorage;
1687
+ _root.CodeLabSearch = CodeLabSearch;
1688
+ _root.CodeLabDiagnostics = CodeLabDiagnostics;
1689
+ _root.CodeLabScm = CodeLabScm;
1690
+
19
1691
  // --- Module 1: Runtime Engine ---
20
1692
  (function () {
21
1693
  // @ts-nocheck
@@ -40,6 +1712,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
40
1712
  */
41
1713
 
42
1714
  function __initVirtualRuntime(rootScope) {
1715
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
1716
+ ? rootScope.CodeLabLogger.createLogger()
1717
+ : {
1718
+ debug() {},
1719
+ info() {},
1720
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
1721
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
1722
+ };
43
1723
  // =========================================================================
44
1724
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
45
1725
  // =========================================================================
@@ -1599,7 +3279,7 @@ function __initVirtualRuntime(rootScope) {
1599
3279
  },
1600
3280
  final(cb) {
1601
3281
  if (fd !== null) {
1602
- try { fsShim.closeSync(fd); } catch (_) {}
3282
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1603
3283
  fd = null;
1604
3284
  }
1605
3285
  cb(null);
@@ -2119,7 +3799,9 @@ function __initVirtualRuntime(rootScope) {
2119
3799
  return pathname + search + hash;
2120
3800
  }
2121
3801
  return resolvedUrl.href;
2122
- } catch (_) {}
3802
+ } catch (err) {
3803
+ _runtimeLogger.debug('url.resolve fallback used', err);
3804
+ }
2123
3805
  }
2124
3806
  if (toStr.startsWith('/')) {
2125
3807
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2558,10 +4240,10 @@ function __initVirtualRuntime(rootScope) {
2558
4240
  for (const [port, entry] of Array.from(table.entries())) {
2559
4241
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2560
4242
  if (entry.server && typeof entry.server.close === 'function') {
2561
- try { entry.server.close(); } catch (_) {}
4243
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2562
4244
  }
2563
4245
  if (typeof entry.stop === 'function') {
2564
- try { entry.stop(); } catch (_) {}
4246
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2565
4247
  }
2566
4248
  // Avoid a double 'close' emission when entry.server.close() already
2567
4249
  // unregistered the port through unregisterServer().
@@ -3198,7 +4880,7 @@ function __initVirtualRuntime(rootScope) {
3198
4880
  },
3199
4881
  closeAllServers() {
3200
4882
  for (const s of Array.from(activeServers.values())) {
3201
- try { s.close(); } catch (_) {}
4883
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3202
4884
  }
3203
4885
  activeServers.clear();
3204
4886
  }
@@ -4024,7 +5706,7 @@ function __initVirtualRuntime(rootScope) {
4024
5706
 
4025
5707
  function closeAllServers() {
4026
5708
  for (const srv of servers.values()) {
4027
- try { srv.close(); } catch (_) {}
5709
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4028
5710
  }
4029
5711
  servers.clear();
4030
5712
  }
@@ -5104,7 +6786,9 @@ function __initVirtualRuntime(rootScope) {
5104
6786
  try {
5105
6787
  const pkgJson = JSON.parse(content);
5106
6788
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5107
- } catch (_) {}
6789
+ } catch (err) {
6790
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
6791
+ }
5108
6792
  continue;
5109
6793
  }
5110
6794
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5133,7 +6817,9 @@ function __initVirtualRuntime(rootScope) {
5133
6817
  const meta = await res.json();
5134
6818
  deps = Object.keys((meta && meta.dependencies) || {});
5135
6819
  }
5136
- } catch (_) {}
6820
+ } catch (err) {
6821
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
6822
+ }
5137
6823
  _npmMetadataCache.set(pkg, deps);
5138
6824
  }));
5139
6825
  for (const pkg of pending) {
@@ -5151,7 +6837,7 @@ function __initVirtualRuntime(rootScope) {
5151
6837
  continue;
5152
6838
  }
5153
6839
  if (typeof onProgress === 'function') {
5154
- try { onProgress(pkg); } catch (_) {}
6840
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5155
6841
  }
5156
6842
  if (typeof fetch === 'function') {
5157
6843
  try {
@@ -5161,7 +6847,9 @@ function __initVirtualRuntime(rootScope) {
5161
6847
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5162
6848
  loaded[pkg] = text;
5163
6849
  }
5164
- } catch (_) {}
6850
+ } catch (err) {
6851
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
6852
+ }
5165
6853
  }
5166
6854
  }
5167
6855
  return loaded;
@@ -5353,7 +7041,9 @@ function __initVirtualRuntime(rootScope) {
5353
7041
  const dir = VirtualPath.dirname(abs);
5354
7042
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5355
7043
  vfs.writeFileSync(abs, content);
5356
- } catch (_) {}
7044
+ } catch (err) {
7045
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
7046
+ }
5357
7047
  }
5358
7048
  }
5359
7049
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5798,7 +7488,7 @@ function __initVirtualRuntime(rootScope) {
5798
7488
  exitCode = Number(code) || 0;
5799
7489
  if (!hasExited) {
5800
7490
  hasExited = true;
5801
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7491
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5802
7492
  }
5803
7493
  if (syncExecDepth > 0) {
5804
7494
  throw new ProcessExitSignal(exitCode);
@@ -5831,8 +7521,8 @@ function __initVirtualRuntime(rootScope) {
5831
7521
  resourceTracker.inFlightHttp.clear();
5832
7522
 
5833
7523
  if (!isBackground) {
5834
- try { vhttp.closeAllServers(); } catch (_) {}
5835
- try { vnet.closeAllServers(); } catch (_) {}
7524
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
7525
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5836
7526
  }
5837
7527
  };
5838
7528
 
@@ -5942,10 +7632,10 @@ function __initVirtualRuntime(rootScope) {
5942
7632
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5943
7633
  } finally {
5944
7634
  for (const ae of hooksSnapshot.afterEachList) {
5945
- try { await ae(); } catch (_) {}
7635
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5946
7636
  }
5947
7637
  for (const af of hooksSnapshot.afterToRun) {
5948
- try { await af(); } catch (_) {}
7638
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5949
7639
  }
5950
7640
  hooksSnapshot.afterToRun.length = 0;
5951
7641
  }
@@ -5993,7 +7683,7 @@ function __initVirtualRuntime(rootScope) {
5993
7683
  const afters = [...suiteCtx.afterCallbacks];
5994
7684
  const cleanupTask = nodeTestChain.then(async () => {
5995
7685
  for (const af of afters) {
5996
- try { await af(); } catch (_) {}
7686
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5997
7687
  }
5998
7688
  });
5999
7689
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6039,7 +7729,7 @@ function __initVirtualRuntime(rootScope) {
6039
7729
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6040
7730
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6041
7731
  };
6042
- try { obs._cb(list, obs); } catch (_) {}
7732
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6043
7733
  }
6044
7734
  }
6045
7735
  }
@@ -6144,7 +7834,7 @@ function __initVirtualRuntime(rootScope) {
6144
7834
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6145
7835
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6146
7836
  };
6147
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
7837
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6148
7838
  }
6149
7839
  }
6150
7840
  }
@@ -7415,7 +9105,9 @@ function __initVirtualRuntime(rootScope) {
7415
9105
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7416
9106
  if (resolvedEntry) return resolvedEntry;
7417
9107
  }
7418
- } catch (_) {}
9108
+ } catch (err) {
9109
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
9110
+ }
7419
9111
  }
7420
9112
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7421
9113
  for (const idx of indexCandidates) {
@@ -7485,7 +9177,9 @@ function __initVirtualRuntime(rootScope) {
7485
9177
  if (found) return found;
7486
9178
  }
7487
9179
  }
7488
- } catch (_) {}
9180
+ } catch (err) {
9181
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
9182
+ }
7489
9183
  }
7490
9184
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7491
9185
  if (foundSub) return foundSub;
@@ -7527,7 +9221,9 @@ function __initVirtualRuntime(rootScope) {
7527
9221
  if (isLocal && activePortTable) {
7528
9222
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7529
9223
  }
7530
- } catch (_) {}
9224
+ } catch (err) {
9225
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
9226
+ }
7531
9227
 
7532
9228
  if (typeof globalThis.fetch === 'function') {
7533
9229
  return await globalThis.fetch(urlOrReq, init);
@@ -7694,7 +9390,9 @@ function __initVirtualRuntime(rootScope) {
7694
9390
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7695
9391
  try {
7696
9392
  return new AsyncFunction(...argNames, body);
7697
- } catch (_) {}
9393
+ } catch (asyncErr) {
9394
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
9395
+ }
7698
9396
  }
7699
9397
  if (
7700
9398
  err &&
@@ -7748,7 +9446,9 @@ function __initVirtualRuntime(rootScope) {
7748
9446
  if (signal && onAbort) {
7749
9447
  try {
7750
9448
  signal.removeEventListener('abort', onAbort);
7751
- } catch (_) {}
9449
+ } catch (err) {
9450
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
9451
+ }
7752
9452
  }
7753
9453
  };
7754
9454
 
@@ -7907,11 +9607,11 @@ function __initVirtualRuntime(rootScope) {
7907
9607
  }
7908
9608
  } finally {
7909
9609
  if (signal && signalListener) {
7910
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
9610
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7911
9611
  }
7912
9612
  if (!hasExited) {
7913
9613
  hasExited = true;
7914
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
9614
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7915
9615
  }
7916
9616
  for (const rawId of resourceTracker.allTimers) {
7917
9617
  clearTimeout(rawId);
@@ -8019,7 +9719,16 @@ function createWorkerRuntimeSource() {
8019
9719
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8020
9720
  }
8021
9721
 
8022
- const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
9722
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
9723
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
9724
+ ? _hostScope.CodeLabLogger.createLogger()
9725
+ : {
9726
+ debug() {},
9727
+ info() {},
9728
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
9729
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
9730
+ };
9731
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8023
9732
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8024
9733
 
8025
9734
  let _cachedWorkerUrl = null;
@@ -8043,7 +9752,7 @@ function _ensureWarmWorker() {
8043
9752
 
8044
9753
  function _destroyWarmWorker() {
8045
9754
  if (_warmWorker) {
8046
- try { _warmWorker.terminate(); } catch (_) {}
9755
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8047
9756
  _warmWorker = null;
8048
9757
  }
8049
9758
  _warmWorkerBusy = false;
@@ -8098,7 +9807,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8098
9807
 
8099
9808
  function releaseWorker(terminateWorker) {
8100
9809
  if (options.signal && abortListener) {
8101
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
9810
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8102
9811
  abortListener = null;
8103
9812
  }
8104
9813
  _activeWorkerJobs.delete(requestId);
@@ -8113,7 +9822,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8113
9822
  }
8114
9823
  }
8115
9824
  } else {
8116
- try { worker.terminate(); } catch (_) {}
9825
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8117
9826
  }
8118
9827
  }
8119
9828
 
@@ -8301,12 +10010,23 @@ if (typeof module !== 'undefined' && module.exports) {
8301
10010
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
8302
10011
  'use strict';
8303
10012
 
10013
+ const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
10014
+ ? root.CodeLabLogger.createLogger()
10015
+ : {
10016
+ debug() {},
10017
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
10018
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
10019
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
10020
+ };
10021
+
8304
10022
  function getRuntimeModule() {
8305
10023
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
8306
10024
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
8307
10025
  try {
8308
10026
  if (typeof require !== 'undefined') return require('./runtime.js');
8309
- } catch (_) {}
10027
+ } catch (err) {
10028
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
10029
+ }
8310
10030
  return null;
8311
10031
  }
8312
10032
 
@@ -8898,7 +10618,9 @@ if (typeof module !== 'undefined' && module.exports) {
8898
10618
  if (typeof vfs.statSync === 'function') {
8899
10619
  isDir = vfs.statSync(full).isDirectory();
8900
10620
  }
8901
- } catch (_) {}
10621
+ } catch (err) {
10622
+ _shellLogger.debug('Glob statSync failed.', full, err);
10623
+ }
8902
10624
 
8903
10625
  if (isDir) {
8904
10626
  traverse(full, rel);
@@ -10220,7 +11942,9 @@ if (typeof module !== 'undefined' && module.exports) {
10220
11942
  : name;
10221
11943
  try {
10222
11944
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
10223
- } catch (_) {}
11945
+ } catch (err) {
11946
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
11947
+ }
10224
11948
  }
10225
11949
  }
10226
11950
  }
@@ -10324,8 +12048,9 @@ if (typeof module !== 'undefined' && module.exports) {
10324
12048
  }
10325
12049
  }
10326
12050
  }
10327
- } catch (_) {
12051
+ } catch (err) {
10328
12052
  // Network or rate limit error on api.github.com; proceed to Strategy B
12053
+ _shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
10329
12054
  }
10330
12055
 
10331
12056
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -10352,7 +12077,9 @@ if (typeof module !== 'undefined' && module.exports) {
10352
12077
  }
10353
12078
  }
10354
12079
  }
10355
- } catch (_) {}
12080
+ } catch (err) {
12081
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
12082
+ }
10356
12083
  }
10357
12084
 
10358
12085
  if (repoNotFound || !rawTreeEntries) {
@@ -10500,7 +12227,9 @@ if (typeof module !== 'undefined' && module.exports) {
10500
12227
  }));
10501
12228
  }
10502
12229
  }
10503
- } catch (_) {}
12230
+ } catch (err) {
12231
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
12232
+ }
10504
12233
 
10505
12234
  if (commits.length === 0) {
10506
12235
  commits = [
@@ -10566,7 +12295,9 @@ if (typeof module !== 'undefined' && module.exports) {
10566
12295
  try {
10567
12296
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
10568
12297
  return { path: p, data: parsed };
10569
- } catch (_) {}
12298
+ } catch (err) {
12299
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
12300
+ }
10570
12301
  }
10571
12302
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
10572
12303
  }
@@ -10607,13 +12338,20 @@ if (typeof module !== 'undefined' && module.exports) {
10607
12338
  vfs.rmdirSync(dirPath);
10608
12339
  }
10609
12340
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
10610
- } catch (_) {}
12341
+ } catch (err) {
12342
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
12343
+ }
10611
12344
  }
10612
12345
 
10613
12346
  // ---------------------------------------------------------------------------
10614
12347
  // Real npm package installation via the jsDelivr CDN
10615
12348
  // ---------------------------------------------------------------------------
10616
12349
  const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
12350
+ const CDN_NPM_BASES = [
12351
+ 'https://cdn.jsdelivr.net/npm',
12352
+ 'https://unpkg.com',
12353
+ 'https://esm.sh'
12354
+ ];
10617
12355
 
10618
12356
  // Minimal offline registry, used only when the CDN is unreachable so common
10619
12357
  // demos still resolve without network access.
@@ -10759,16 +12497,23 @@ if (typeof module !== 'undefined' && module.exports) {
10759
12497
  }
10760
12498
 
10761
12499
  async function resolvePackageMetadata(fetchImpl, name, range) {
10762
- const urls = range
10763
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10764
- : [`${CDN_NPM_BASE}/${name}/package.json`];
10765
- for (const url of urls) {
10766
- const text = await fetchTextFromCdn(fetchImpl, url);
10767
- if (!text) continue;
10768
- try {
10769
- const parsed = JSON.parse(text);
10770
- if (parsed && parsed.version) return parsed;
10771
- } catch (_) {}
12500
+ for (const base of CDN_NPM_BASES) {
12501
+ const urls = range
12502
+ ? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
12503
+ : [`${base}/${name}/package.json`];
12504
+ for (const url of urls) {
12505
+ const text = await fetchTextFromCdn(fetchImpl, url);
12506
+ if (!text) continue;
12507
+ try {
12508
+ const parsed = JSON.parse(text);
12509
+ if (parsed && parsed.version) {
12510
+ parsed._resolvedCdnBase = base;
12511
+ return parsed;
12512
+ }
12513
+ } catch (err) {
12514
+ _shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
12515
+ }
12516
+ }
10772
12517
  }
10773
12518
  return null;
10774
12519
  }
@@ -10786,6 +12531,7 @@ if (typeof module !== 'undefined' && module.exports) {
10786
12531
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10787
12532
  }
10788
12533
 
12534
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
10789
12535
  const version = meta.version;
10790
12536
  const key = `${name}@${version}`;
10791
12537
  if (seen.has(key)) {
@@ -10833,7 +12579,7 @@ if (typeof module !== 'undefined' && module.exports) {
10833
12579
  frontier = [];
10834
12580
  if (batch.length === 0) break;
10835
12581
  const texts = await Promise.all(
10836
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
12582
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
10837
12583
  );
10838
12584
  for (let idx = 0; idx < batch.length; idx++) {
10839
12585
  const rel = batch[idx];
@@ -10857,7 +12603,7 @@ if (typeof module !== 'undefined' && module.exports) {
10857
12603
  }
10858
12604
  // The declared entry may be missing on the CDN; fall back to index.js.
10859
12605
  if (!files.some(f => f.rel === entry)) {
10860
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
12606
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
10861
12607
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10862
12608
  }
10863
12609
 
@@ -10904,7 +12650,9 @@ if (typeof module !== 'undefined' && module.exports) {
10904
12650
  // directory target would otherwise raise EISDIR).
10905
12651
  try {
10906
12652
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10907
- } catch (_) {}
12653
+ } catch (err) {
12654
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
12655
+ }
10908
12656
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10909
12657
  ctx.vfs.writeFileSync(full, f.content);
10910
12658
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10979,9 +12727,35 @@ if (typeof module !== 'undefined' && module.exports) {
10979
12727
  }
10980
12728
  }
10981
12729
 
10982
- pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10983
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10984
-
12730
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
12731
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
12732
+
12733
+ // Also maintain package-lock.json in the same directory for deterministic lockfile verification
12734
+ try {
12735
+ const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
12736
+ let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
12737
+ if (ctx.vfs.existsSync(lockPath)) {
12738
+ const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
12739
+ const parsedLock = JSON.parse(rawLock);
12740
+ if (parsedLock && typeof parsedLock === 'object') {
12741
+ lockData = parsedLock;
12742
+ if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
12743
+ }
12744
+ }
12745
+ for (const inst of installed) {
12746
+ if (inst && inst.name) {
12747
+ lockData.packages[`node_modules/${inst.name}`] = {
12748
+ version: inst.version || '1.0.0',
12749
+ resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
12750
+ };
12751
+ }
12752
+ }
12753
+ ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
12754
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
12755
+ } catch (err) {
12756
+ _shellLogger.debug('Could not write package-lock.json during installPackage.', err);
12757
+ }
12758
+
10985
12759
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10986
12760
  }
10987
12761
 
@@ -11179,7 +12953,9 @@ if (typeof module !== 'undefined' && module.exports) {
11179
12953
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
11180
12954
  if (parsed && parsed.version) return parsed.version;
11181
12955
  }
11182
- } catch (_) {}
12956
+ } catch (err) {
12957
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
12958
+ }
11183
12959
  try {
11184
12960
  for (const dir of [rootDir, '/workspace']) {
11185
12961
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -11188,7 +12964,9 @@ if (typeof module !== 'undefined' && module.exports) {
11188
12964
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
11189
12965
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
11190
12966
  }
11191
- } catch (_) {}
12967
+ } catch (err) {
12968
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
12969
+ }
11192
12970
  return 'latest';
11193
12971
  }
11194
12972
 
@@ -11226,7 +13004,7 @@ if (typeof module !== 'undefined' && module.exports) {
11226
13004
  if (dirFlag) {
11227
13005
  walk(full, depth + 1);
11228
13006
  } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
11229
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
13007
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
11230
13008
  }
11231
13009
  }
11232
13010
  };
@@ -11273,7 +13051,7 @@ if (typeof module !== 'undefined' && module.exports) {
11273
13051
 
11274
13052
  const handler = async (request) => {
11275
13053
  let pathname = '/';
11276
- try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
13054
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
11277
13055
  const rel = pathname.replace(/^\/+/, '');
11278
13056
  let target = PosixPath.join(rootDir, rel);
11279
13057
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -11312,7 +13090,9 @@ if (typeof module !== 'undefined' && module.exports) {
11312
13090
  if (rm && typeof rm.transpileForBrowser === 'function') {
11313
13091
  body = rm.transpileForBrowser(body, target);
11314
13092
  }
11315
- } catch (_) {}
13093
+ } catch (err) {
13094
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
13095
+ }
11316
13096
  }
11317
13097
 
11318
13098
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -11320,7 +13100,7 @@ if (typeof module !== 'undefined' && module.exports) {
11320
13100
 
11321
13101
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
11322
13102
  return portTable.registerServer(port, {
11323
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
13103
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
11324
13104
  fetch: handler,
11325
13105
  name: 'code-lab-serve',
11326
13106
  pid,
@@ -11433,7 +13213,9 @@ if (typeof module !== 'undefined' && module.exports) {
11433
13213
  let isDir = false;
11434
13214
  try {
11435
13215
  isDir = ctx.vfs.statSync(resolved).isDirectory();
11436
- } catch (_) {}
13216
+ } catch (err) {
13217
+ _shellLogger.debug('cd statSync failed.', resolved, err);
13218
+ }
11437
13219
 
11438
13220
  if (!isDir) {
11439
13221
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -11533,7 +13315,9 @@ if (typeof module !== 'undefined' && module.exports) {
11533
13315
  isDirectory = st.isDirectory();
11534
13316
  size = st.size;
11535
13317
  mtimeMs = st.mtimeMs || Date.now();
11536
- } catch (_) {}
13318
+ } catch (err) {
13319
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
13320
+ }
11537
13321
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
11538
13322
  });
11539
13323
 
@@ -11953,7 +13737,9 @@ if (typeof module !== 'undefined' && module.exports) {
11953
13737
  if (st.isDirectory()) walk(full);
11954
13738
  else targets.push(full);
11955
13739
  }
11956
- } catch (_) {}
13740
+ } catch (err) {
13741
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
13742
+ }
11957
13743
  }
11958
13744
  if (ctx.vfs.existsSync(absRoot)) {
11959
13745
  const st = ctx.vfs.statSync(absRoot);
@@ -12077,7 +13863,9 @@ if (typeof module !== 'undefined' && module.exports) {
12077
13863
  let isDir = false;
12078
13864
  try {
12079
13865
  isDir = ctx.vfs.statSync(full).isDirectory();
12080
- } catch (_) {}
13866
+ } catch (err) {
13867
+ _shellLogger.debug('find statSync skipped.', full, err);
13868
+ }
12081
13869
 
12082
13870
  const relPath = root === '.'
12083
13871
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -12096,7 +13884,7 @@ if (typeof module !== 'undefined' && module.exports) {
12096
13884
  // Root itself check
12097
13885
  if (ctx.vfs.existsSync(absRoot)) {
12098
13886
  let isDir = false;
12099
- try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (_) {}
13887
+ try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
12100
13888
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
12101
13889
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
12102
13890
  results.push(root);
@@ -13008,7 +14796,7 @@ if (typeof module !== 'undefined' && module.exports) {
13008
14796
  const isLast = i === entries.length - 1;
13009
14797
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
13010
14798
  let isDir = false;
13011
- try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (_) {}
14799
+ try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
13012
14800
 
13013
14801
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
13014
14802
 
@@ -13236,10 +15024,10 @@ if (typeof module !== 'undefined' && module.exports) {
13236
15024
  for (const s of ctx.shell.portTable.listServers()) {
13237
15025
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
13238
15026
  if (s.server && typeof s.server.close === 'function') {
13239
- try { s.server.close(); } catch (_) {}
15027
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
13240
15028
  }
13241
15029
  if (typeof s.stop === 'function') {
13242
- try { s.stop(); } catch (_) {}
15030
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
13243
15031
  }
13244
15032
  ctx.shell.portTable.unregisterServer(s.port);
13245
15033
  killedPort = true;
@@ -15570,6 +17358,16 @@ if (typeof module !== 'undefined' && module.exports) {
15570
17358
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
15571
17359
  'use strict';
15572
17360
 
17361
+ const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
17362
+ const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
17363
+ ? _termRoot.CodeLabLogger.createLogger()
17364
+ : {
17365
+ debug() {},
17366
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
17367
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
17368
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
17369
+ };
17370
+
15573
17371
  const ANSI_CODE_MAP = {
15574
17372
  1: 'cl-ansi-bold',
15575
17373
  2: 'cl-ansi-dim',
@@ -16110,7 +17908,7 @@ if (typeof module !== 'undefined' && module.exports) {
16110
17908
  if (!this.container || typeof this.container.querySelector !== 'function') return;
16111
17909
  const input = this.container.querySelector('#cl-repl-input');
16112
17910
  if (input && typeof input.focus === 'function') {
16113
- try { input.focus(); } catch (_) {}
17911
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
16114
17912
  }
16115
17913
  }
16116
17914
 
@@ -16134,9 +17932,9 @@ if (typeof module !== 'undefined' && module.exports) {
16134
17932
  }
16135
17933
  for (const entry of this._listeners) {
16136
17934
  if (typeof entry === 'function') {
16137
- try { entry(); } catch (_) {}
17935
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
16138
17936
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
16139
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
17937
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
16140
17938
  }
16141
17939
  }
16142
17940
  this._listeners = [];
@@ -16205,7 +18003,9 @@ if (typeof module !== 'undefined' && module.exports) {
16205
18003
  try {
16206
18004
  const res = this.onKey(e);
16207
18005
  if (res === false) return;
16208
- } catch (_) {}
18006
+ } catch (err) {
18007
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
18008
+ }
16209
18009
  }
16210
18010
 
16211
18011
  const key = e.key;
@@ -16358,7 +18158,7 @@ if (typeof module !== 'undefined' && module.exports) {
16358
18158
  this.replMode = false;
16359
18159
  }
16360
18160
  if (this.onInterrupt) {
16361
- try { this.onInterrupt(); } catch (_) {}
18161
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
16362
18162
  }
16363
18163
  this.render();
16364
18164
  return;
@@ -16559,7 +18359,9 @@ if (typeof module !== 'undefined' && module.exports) {
16559
18359
  if (typeof nextInput.setSelectionRange === 'function') {
16560
18360
  nextInput.setSelectionRange(this.cursor, this.cursor);
16561
18361
  }
16562
- } catch (_) {}
18362
+ } catch (err) {
18363
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
18364
+ }
16563
18365
  }
16564
18366
  }
16565
18367
  }
@@ -16597,13 +18399,26 @@ if (typeof module !== 'undefined' && module.exports) {
16597
18399
  (function (root) {
16598
18400
  'use strict';
16599
18401
 
16600
- let terminalModule = null;
16601
- let shellModule = null;
16602
- let runtimeModule = null;
18402
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
18403
+ (root && root.CodeLabLogger) ||
18404
+ null;
18405
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
18406
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
18407
+ : () => {};
18408
+
18409
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18410
+ let shellModule = (root && root.CodeLabShell) || null;
18411
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
16603
18412
  if (typeof require === 'function') {
16604
- try { terminalModule = require('./terminal.js'); } catch (_) {}
16605
- try { shellModule = require('./shell.js'); } catch (_) {}
16606
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
18413
+ if (!terminalModule) {
18414
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
18415
+ }
18416
+ if (!shellModule) {
18417
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
18418
+ }
18419
+ if (!runtimeModule) {
18420
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
18421
+ }
16607
18422
  }
16608
18423
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
16609
18424
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -16634,7 +18449,7 @@ if (typeof module !== 'undefined' && module.exports) {
16634
18449
 
16635
18450
  // The bundler rewrites this literal from package.json at build time. Keeping
16636
18451
  // the fallback in sync lets tests require src/workbench.js directly.
16637
- const CODELAB_VERSION = '0.1.7';
18452
+ const CODELAB_VERSION = '0.1.8';
16638
18453
 
16639
18454
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16640
18455
  const NODE_AMBIENT_DTS = `
@@ -16962,7 +18777,14 @@ declare module 'bun:sqlite' {
16962
18777
  }
16963
18778
  `;
16964
18779
 
18780
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
18781
+ (root && root.CodeLabHtml) ||
18782
+ null;
18783
+
16965
18784
  function escapeHtml(str) {
18785
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
18786
+ return _sharedHtmlMod.escapeHtml(str);
18787
+ }
16966
18788
  if (str == null) return '';
16967
18789
  return String(str)
16968
18790
  .replace(/&/g, '&amp;')
@@ -16972,6 +18794,18 @@ declare module 'bun:sqlite' {
16972
18794
  .replace(/'/g, '&#39;');
16973
18795
  }
16974
18796
 
18797
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
18798
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
18799
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
18800
+ let out = strings[0] || '';
18801
+ for (let i = 0; i < values.length; i++) {
18802
+ const val = values[i];
18803
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
18804
+ out += strings[i + 1] || '';
18805
+ }
18806
+ return raw(out);
18807
+ });
18808
+
16975
18809
  // Schemes that may appear in a rendered href. Everything else
16976
18810
  // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16977
18811
  const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
@@ -17190,11 +19024,11 @@ declare module 'bun:sqlite' {
17190
19024
  if (!str) return '';
17191
19025
  let text = String(str);
17192
19026
 
17193
- // Markdown Links: [label](url "title") or [label](url)
17194
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
19027
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
19028
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17195
19029
  const cleanUrl = sanitizeUrl(url);
17196
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17197
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
19030
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
19031
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
17198
19032
  });
17199
19033
 
17200
19034
  // Strikethrough: ~~del~~
@@ -17721,23 +19555,24 @@ declare module 'bun:sqlite' {
17721
19555
  let _workbenchInstanceCounter = 0;
17722
19556
  const _fallbackStorage = new Map();
17723
19557
 
17724
- // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17725
- // in src/preview-sw.js — keep both copies in sync.
17726
- const PREVIEW_CSP = [
17727
- "default-src 'self' data: blob:",
17728
- "base-uri 'self'",
17729
- "object-src 'none'",
17730
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17731
- "style-src 'self' 'unsafe-inline'",
17732
- "img-src 'self' data: blob:",
17733
- "font-src 'self' data:",
17734
- "connect-src 'self' data: blob:",
17735
- "media-src 'self' data: blob:",
17736
- "worker-src 'self' blob:",
17737
- "frame-src 'self' data: blob:",
17738
- "form-action 'self'",
17739
- "frame-ancestors 'self'"
17740
- ].join('; ');
19558
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
19559
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
19560
+ // there is exactly one policy implementation shared by both sides.
19561
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
19562
+ (root && root.CodeLabCsp) ||
19563
+ null;
19564
+
19565
+ function normalizePreviewCspOption(raw) {
19566
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
19567
+ return PreviewCsp.normalizePreviewCspConfig(raw);
19568
+ }
19569
+ return { mode: 'balanced', allow: {} };
19570
+ }
19571
+
19572
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
19573
+ // that ships, using it would silently *pretend* to isolate previews while the
19574
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
19575
+ const PREVIEW_RELAY_AVAILABLE = false;
17741
19576
 
17742
19577
  function normalizePreviewOrigin(raw) {
17743
19578
  if (raw === null || raw === undefined || raw === '') return null;
@@ -17750,12 +19585,26 @@ declare module 'bun:sqlite' {
17750
19585
  }
17751
19586
  }
17752
19587
 
17753
- const LOG_PREFIX = '[code-lab]';
19588
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
19589
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
19590
+ constructor(code, message, options = {}) {
19591
+ super(message);
19592
+ this.name = 'CodeLabError';
19593
+ this.code = code || 'E_CODELAB';
19594
+ this.module = options.module || 'workbench';
19595
+ this.context = options.context || {};
19596
+ if (options.cause !== undefined) this.cause = options.cause;
19597
+ }
19598
+ };
19599
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
17754
19600
 
17755
19601
  // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17756
19602
  // into their own telemetry; `options.debug` enables verbose output. Errors
17757
19603
  // are never silently discarded.
17758
19604
  function createLogger(options = {}) {
19605
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
19606
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
19607
+ }
17759
19608
  const sink = options.logger;
17760
19609
  const debugEnabled = options.debug === true;
17761
19610
 
@@ -17765,8 +19614,9 @@ declare module 'bun:sqlite' {
17765
19614
  try {
17766
19615
  sink[level](...args);
17767
19616
  return;
17768
- } catch (_) {
17769
- // A broken host logger must not break the IDE; fall through.
19617
+ } catch (sinkErr) {
19618
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
19619
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
17770
19620
  }
17771
19621
  }
17772
19622
  const fn = typeof console !== 'undefined' ? console[level] : null;
@@ -17798,7 +19648,7 @@ declare module 'bun:sqlite' {
17798
19648
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17799
19649
  }
17800
19650
 
17801
- function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
19651
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
17802
19652
  const str = String(value);
17803
19653
  try {
17804
19654
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
@@ -17806,6 +19656,9 @@ declare module 'bun:sqlite' {
17806
19656
  return true;
17807
19657
  }
17808
19658
  } catch (err) {
19659
+ if (typeof onError === 'function') {
19660
+ onError(err);
19661
+ }
17809
19662
  if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17810
19663
  if (!safeStorageSet._warnedKeys.has(key)) {
17811
19664
  safeStorageSet._warnedKeys.add(key);
@@ -17829,6 +19682,8 @@ declare module 'bun:sqlite' {
17829
19682
  this.options = options || {};
17830
19683
  this.logger = createLogger({ logger: options.logger, debug: options.debug });
17831
19684
  this._persistenceFailureReported = false;
19685
+ this.saveStatusState = 'saved';
19686
+ this.saveStatusError = null;
17832
19687
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17833
19688
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17834
19689
  this.title = options.title || this.labId;
@@ -17836,6 +19691,7 @@ declare module 'bun:sqlite' {
17836
19691
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17837
19692
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17838
19693
  this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
19694
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
17839
19695
  this._previewIsolationWarned = false;
17840
19696
  if (options.previewOrigin && !this.previewOrigin) {
17841
19697
  this.logger.warn(
@@ -17914,12 +19770,15 @@ declare module 'bun:sqlite' {
17914
19770
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
17915
19771
  loading: false,
17916
19772
  error: null,
17917
- srcdoc: ''
19773
+ srcdoc: '',
19774
+ violations: []
17918
19775
  };
17919
19776
  this.previewHistory = [];
17920
19777
  this.previewHistoryIdx = -1;
17921
19778
  this._previewSwReady = false;
17922
19779
  this._previewSwRegistration = null;
19780
+ this._previewViolationHandler = null;
19781
+ this._swMessageHandler = null;
17923
19782
  this._portToasts = new Map();
17924
19783
  this.isFullscreen = false;
17925
19784
  this.isRunning = false;
@@ -18019,7 +19878,9 @@ declare module 'bun:sqlite' {
18019
19878
  onCommand: (cmd) => this._handleReplCommand(cmd),
18020
19879
  onInterrupt: () => this._handleInterrupt()
18021
19880
  });
18022
- } catch (_) {}
19881
+ } catch (err) {
19882
+ this.logger.debug('PTY engine initialization skipped.', err);
19883
+ }
18023
19884
  }
18024
19885
 
18025
19886
  this.shell = null;
@@ -18045,7 +19906,7 @@ declare module 'bun:sqlite' {
18045
19906
  intoRoot: options.cloneIntoRoot !== false,
18046
19907
  branch: options.branch || undefined,
18047
19908
  fetchImpl: options.fetchImpl || undefined
18048
- }).catch(() => {});
19909
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
18049
19910
  }
18050
19911
  }
18051
19912
 
@@ -18070,7 +19931,9 @@ declare module 'bun:sqlite' {
18070
19931
  }
18071
19932
  });
18072
19933
  this._syncFilesToShellVfs();
18073
- } catch (_) {}
19934
+ } catch (err) {
19935
+ this.logger.debug('POSIX shell initialization skipped.', err);
19936
+ }
18074
19937
  }
18075
19938
  }
18076
19939
 
@@ -18096,7 +19959,9 @@ declare module 'bun:sqlite' {
18096
19959
  const u = new URL(fullUrl);
18097
19960
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
18098
19961
  reqPath = u.pathname + (u.search || '');
18099
- } catch (_) {}
19962
+ } catch (err) {
19963
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
19964
+ }
18100
19965
  const method = String((init && init.method) || 'GET').toUpperCase();
18101
19966
  try {
18102
19967
  const res = await origDispatch(url, init);
@@ -18108,7 +19973,9 @@ declare module 'bun:sqlite' {
18108
19973
  } else if (res && res.body !== undefined) {
18109
19974
  bodyText = String(res.body);
18110
19975
  }
18111
- } catch (_) {}
19976
+ } catch (err) {
19977
+ this.logger.debug('Could not read response body for HTTP trace.', err);
19978
+ }
18112
19979
  const responseHeaders = {};
18113
19980
  if (res && res.headers) {
18114
19981
  if (typeof res.headers.forEach === 'function') {
@@ -18120,7 +19987,9 @@ declare module 'bun:sqlite' {
18120
19987
  let formattedBody = bodyText;
18121
19988
  try {
18122
19989
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
18123
- } catch (_) {}
19990
+ } catch (err) {
19991
+ void err;
19992
+ }
18124
19993
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
18125
19994
  this.lastHttpTrace.push({
18126
19995
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -18169,7 +20038,9 @@ declare module 'bun:sqlite' {
18169
20038
  vfs.writeFileSync(absPath, String(content ?? ''));
18170
20039
  }
18171
20040
  }
18172
- } catch (_) {}
20041
+ } catch (err) {
20042
+ this.logger.debug('Could not sync files to shell VFS.', err);
20043
+ }
18173
20044
  }
18174
20045
 
18175
20046
  _emitEvent(name, detail) {
@@ -18191,7 +20062,9 @@ declare module 'bun:sqlite' {
18191
20062
  if (shortName !== fullName) {
18192
20063
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
18193
20064
  }
18194
- } catch (_) {}
20065
+ } catch (err) {
20066
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
20067
+ }
18195
20068
  }
18196
20069
 
18197
20070
  _resolvedTheme() {
@@ -18225,13 +20098,26 @@ declare module 'bun:sqlite' {
18225
20098
  }
18226
20099
  }
18227
20100
 
18228
- _reportPersistenceFailure() {
18229
- if (this._persistenceFailureReported) return;
20101
+ _reportPersistenceFailure(cause) {
20102
+ const error = isCodeLabError(cause)
20103
+ ? cause
20104
+ : new CodeLabError(
20105
+ 'E_SAVE',
20106
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
20107
+ { cause, recoverable: true, details: { labId: this.labId } }
20108
+ );
20109
+ this.saveStatusState = 'failed';
20110
+ this.saveStatusError = error;
20111
+ this._updateStatusBar();
20112
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
20113
+ if (this._persistenceFailureReported) return error;
18230
20114
  this._persistenceFailureReported = true;
18231
20115
  this.logger.warn(
18232
20116
  'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18233
20117
  );
18234
- this._emitEvent('persistence-error', { labId: this.labId });
20118
+ this._emitEvent('persistence-error', { labId: this.labId, error });
20119
+ this._emitEvent('error', error);
20120
+ return error;
18235
20121
  }
18236
20122
 
18237
20123
  _saveState() {
@@ -18255,22 +20141,35 @@ declare module 'bun:sqlite' {
18255
20141
  };
18256
20142
  this.savedState = state;
18257
20143
  if (this.options && this.options.persistState === false) {
20144
+ this.saveStatusState = 'saved';
20145
+ this.saveStatusError = null;
20146
+ this._updateStatusBar();
18258
20147
  return;
18259
20148
  }
20149
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
18260
20150
  const serialized = JSON.stringify(state);
20151
+ safeStorageSet._lastError = null;
20152
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
18261
20153
  const persisted = [
18262
- safeStorageSet(this._storageKey(), serialized, this.logger),
20154
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
18263
20155
  // Sync with host app sidebar & build overview progress trackers
18264
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18265
- safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
20156
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20157
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
18266
20158
  ];
18267
- if (persisted.includes(false)) this._reportPersistenceFailure();
20159
+ if (persisted.includes(false)) {
20160
+ this._reportPersistenceFailure(safeStorageSet._lastError);
20161
+ } else {
20162
+ this.saveStatusState = 'saved';
20163
+ this.saveStatusError = null;
20164
+ this._updateStatusBar();
20165
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
20166
+ }
18268
20167
  } catch (err) {
18269
20168
  this.logger.error(
18270
20169
  'Failed to save workbench state.',
18271
20170
  err && err.message ? err.message : err
18272
20171
  );
18273
- this._reportPersistenceFailure();
20172
+ this._reportPersistenceFailure(err);
18274
20173
  }
18275
20174
  }
18276
20175
 
@@ -18293,7 +20192,9 @@ declare module 'bun:sqlite' {
18293
20192
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
18294
20193
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
18295
20194
  }
18296
- } catch (_) {}
20195
+ } catch (err) {
20196
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
20197
+ }
18297
20198
  }
18298
20199
 
18299
20200
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -18340,6 +20241,7 @@ declare module 'bun:sqlite' {
18340
20241
  const dotEl = this.container.querySelector('#cl-status-dot');
18341
20242
  const textEl = this.container.querySelector('#cl-status-text');
18342
20243
  const fileEl = this.container.querySelector('#cl-status-file');
20244
+ const saveEl = this.container.querySelector('#cl-status-save');
18343
20245
  const durEl = this.container.querySelector('#cl-status-duration');
18344
20246
  const curEl = this.container.querySelector('#cl-status-cursor');
18345
20247
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -18351,6 +20253,24 @@ declare module 'bun:sqlite' {
18351
20253
  }
18352
20254
  if (textEl) textEl.textContent = this.runtimeStatusText;
18353
20255
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
20256
+ if (saveEl) {
20257
+ if (this.saveStatusState === 'failed') {
20258
+ saveEl.style.display = 'inline-flex';
20259
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
20260
+ saveEl.textContent = '⚠ Save failed (session-only)';
20261
+ const reason = this.saveStatusError && this.saveStatusError.message
20262
+ ? this.saveStatusError.message
20263
+ : 'localStorage is unavailable or quota exceeded';
20264
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
20265
+ saveEl.setAttribute('data-save-state', 'failed');
20266
+ } else {
20267
+ saveEl.style.display = 'none';
20268
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
20269
+ saveEl.textContent = '';
20270
+ saveEl.removeAttribute('title');
20271
+ saveEl.setAttribute('data-save-state', 'saved');
20272
+ }
20273
+ }
18354
20274
  if (durEl) {
18355
20275
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
18356
20276
  durEl.style.display = 'inline-flex';
@@ -18658,6 +20578,7 @@ declare module 'bun:sqlite' {
18658
20578
  </span>
18659
20579
  <span class="codelab-statusbar__sep">·</span>
18660
20580
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
20581
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
18661
20582
  </div>
18662
20583
  <div class="codelab-statusbar__right">
18663
20584
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -19912,7 +21833,9 @@ declare module 'bun:sqlite' {
19912
21833
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
19913
21834
  try {
19914
21835
  this.ptyEngine.writeStreamChunk(rawText, type);
19915
- } catch (_) {}
21836
+ } catch (err) {
21837
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
21838
+ }
19916
21839
  }
19917
21840
 
19918
21841
  this._activeStreamType = type;
@@ -20044,14 +21967,18 @@ declare module 'bun:sqlite' {
20044
21967
  if (this._activeCommandAbortController) {
20045
21968
  try {
20046
21969
  this._activeCommandAbortController.abort('SIGINT');
20047
- } catch (_) {}
21970
+ } catch (err) {
21971
+ this.logger.debug('AbortController.abort failed.', err);
21972
+ }
20048
21973
  this._activeCommandAbortController = null;
20049
21974
  }
20050
21975
 
20051
21976
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
20052
21977
  try {
20053
21978
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
20054
- } catch (_) {}
21979
+ } catch (err) {
21980
+ this.logger.debug('cancelWorkerExecution failed.', err);
21981
+ }
20055
21982
  }
20056
21983
 
20057
21984
  this.isRunning = false;
@@ -20620,7 +22547,9 @@ declare module 'bun:sqlite' {
20620
22547
  try {
20621
22548
  const parsed = JSON.parse(responseBody);
20622
22549
  formattedBody = JSON.stringify(parsed, null, 2);
20623
- } catch (_) {}
22550
+ } catch (_) {
22551
+ formattedBody = responseBody;
22552
+ }
20624
22553
 
20625
22554
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
20626
22555
  const traceItem = {
@@ -20693,7 +22622,9 @@ declare module 'bun:sqlite' {
20693
22622
  if (this.drawerTab === 'ports') this._renderDrawerBody();
20694
22623
  this._dismissPortToast(port);
20695
22624
  }));
20696
- } catch (_) {}
22625
+ } catch (err) {
22626
+ this.logger.warn('Failed to attach portTable event listeners.', err);
22627
+ }
20697
22628
  }
20698
22629
 
20699
22630
  _updatePortsPill() {
@@ -20767,16 +22698,55 @@ declare module 'bun:sqlite' {
20767
22698
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
20768
22699
  try {
20769
22700
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
22701
+ this._swMessageHandler = onMessage;
20770
22702
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
20771
22703
  navigator.serviceWorker.addEventListener('message', onMessage);
20772
22704
  } else {
20773
22705
  navigator.serviceWorker.onmessage = onMessage;
20774
22706
  }
20775
22707
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
20776
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
20777
- .catch(() => { this._previewSwReady = false; });
20778
- } catch (_) {
22708
+ .then((reg) => {
22709
+ this._previewSwRegistration = reg;
22710
+ this._previewSwReady = true;
22711
+ this._pushPreviewCsp(reg);
22712
+ })
22713
+ .catch((err) => {
22714
+ this._previewSwReady = false;
22715
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
22716
+ });
22717
+ } catch (err) {
20779
22718
  this._previewSwReady = false;
22719
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
22720
+ }
22721
+ }
22722
+
22723
+ /**
22724
+ * The service worker cannot read workbench options, so the resolved policy
22725
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
22726
+ * the srcdoc fallback and silently not the served previews.
22727
+ */
22728
+ _pushPreviewCsp(registration) {
22729
+ const policy = this._previewPolicy();
22730
+ const send = (worker) => {
22731
+ if (!worker || typeof worker.postMessage !== 'function') return;
22732
+ try {
22733
+ worker.postMessage({ type: 'codelab:config', csp: policy });
22734
+ } catch (err) {
22735
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
22736
+ }
22737
+ };
22738
+
22739
+ if (registration) {
22740
+ send(registration.active);
22741
+ send(registration.installing);
22742
+ send(registration.waiting);
22743
+ }
22744
+
22745
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
22746
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
22747
+ sw.ready
22748
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
22749
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
20780
22750
  }
20781
22751
  }
20782
22752
 
@@ -20809,11 +22779,15 @@ declare module 'bun:sqlite' {
20809
22779
  } else if (res && res.headers) {
20810
22780
  Object.assign(outHeaders, res.headers);
20811
22781
  }
20812
- } catch (_) {}
22782
+ } catch (err) {
22783
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
22784
+ }
20813
22785
  let bodyText = '';
20814
22786
  try {
20815
22787
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
20816
- } catch (_) {}
22788
+ } catch (err) {
22789
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
22790
+ }
20817
22791
  return {
20818
22792
  status: (res && res.status) || 200,
20819
22793
  statusText: (res && res.statusText) || 'OK',
@@ -20840,44 +22814,170 @@ declare module 'bun:sqlite' {
20840
22814
  const p = Number(port) || 3000;
20841
22815
  const rawPath = pathAndQuery || '/';
20842
22816
  const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20843
- const base = this.previewOrigin || '';
22817
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
22818
+ // relay exists on that origin; pretending otherwise yields a 503.
22819
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
20844
22820
  return `${base}/__preview/${p}${path}`;
20845
22821
  }
20846
22822
 
22823
+ /** Resolved CSP for preview documents served by this workbench. */
22824
+ _previewPolicy() {
22825
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
22826
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
22827
+ return "default-src 'self'; object-src 'none'";
22828
+ }
22829
+ return PreviewCsp.buildPreviewPolicy(
22830
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
22831
+ );
22832
+ }
22833
+
22834
+ /** Remote origins the current policy allows, for the preview toolbar. */
22835
+ _previewNetworkHosts() {
22836
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
22837
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
22838
+ }
22839
+
20847
22840
  _warnPreviewIsolation() {
20848
- if (this.previewOrigin || this._previewIsolationWarned) return;
22841
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
20849
22842
  this._previewIsolationWarned = true;
20850
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20851
- console.warn(
20852
- '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20853
- 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20854
- );
20855
- }
22843
+ if (PREVIEW_RELAY_AVAILABLE) return;
22844
+ this.logger.warn(
22845
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
22846
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
22847
+ 'the host origin: no host DOM, no host storage.'
22848
+ );
20856
22849
  }
20857
22850
 
20858
22851
  _injectPreviewCsp(html, port) {
20859
22852
  if (typeof html !== 'string' || !html) return html;
20860
- if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20861
22853
 
20862
- const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20863
- (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
22854
+ const tags = [];
22855
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
22856
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
22857
+ }
22858
+ if (!/<base\b/i.test(html)) {
22859
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
22860
+ }
22861
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
22862
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
22863
+ tags.push(PreviewCsp.buildPreviewShims());
22864
+ }
22865
+ if (tags.length === 0) return html;
20864
22866
 
22867
+ const injection = tags.join('');
20865
22868
  if (/<head\b[^>]*>/i.test(html)) {
20866
- return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
22869
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
20867
22870
  }
20868
22871
  if (/<html\b[^>]*>/i.test(html)) {
20869
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
22872
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
22873
+ }
22874
+ return `<head>${injection}</head>${html}`;
22875
+ }
22876
+
22877
+ /**
22878
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
22879
+ * string `"null"` and cannot be used to authenticate the sender. Match the
22880
+ * message source against the preview frame instead.
22881
+ */
22882
+ _installPreviewViolationListener() {
22883
+ if (this._previewViolationHandler) return;
22884
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
22885
+
22886
+ this._previewViolationHandler = (event) => {
22887
+ const data = event && event.data;
22888
+ if (!data || typeof data.type !== 'string') return;
22889
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
22890
+ if (!iframe) return;
22891
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
22892
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
22893
+
22894
+ if (data.type === 'codelab:preview-violation') {
22895
+ this._reportPreviewViolation(data);
22896
+ } else if (data.type === 'codelab:preview-console') {
22897
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
22898
+ const args = Array.isArray(data.args) ? data.args : [data.args];
22899
+ const text = args.map((a) => String(a ?? '')).join(' ');
22900
+ this.terminalLogs.push({
22901
+ type: level === 'error' ? 'stderr' : 'stdout',
22902
+ text: `[Preview ${level.toUpperCase()}] ${text}`
22903
+ });
22904
+ this._emitEvent('preview-console', { level, text, args });
22905
+ } else if (data.type === 'codelab:preview-error') {
22906
+ const msg = String(data.message || 'Uncaught runtime error');
22907
+ this.previewState.runtimeError = {
22908
+ message: msg,
22909
+ file: data.file ? String(data.file) : null,
22910
+ line: typeof data.line === 'number' ? data.line : null,
22911
+ col: typeof data.col === 'number' ? data.col : null,
22912
+ stack: data.stack ? String(data.stack) : null
22913
+ };
22914
+ this.terminalLogs.push({
22915
+ type: 'stderr',
22916
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
22917
+ });
22918
+ this._emitEvent('preview-error', this.previewState.runtimeError);
22919
+ } else if (data.type === 'codelab:preview-error-clear') {
22920
+ this.previewState.runtimeError = null;
22921
+ }
22922
+ };
22923
+ window.addEventListener('message', this._previewViolationHandler);
22924
+ }
22925
+
22926
+ _reportPreviewViolation(violation) {
22927
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
22928
+ const directive = String((violation && violation.directive) || '');
22929
+ const key = `${directive}|${blockedURI}`;
22930
+ const state = this.previewState;
22931
+ state.violations = state.violations || [];
22932
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
22933
+ state.violations.push({ key, directive, blockedURI });
22934
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
22935
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
22936
+ }
22937
+ this._updatePreviewCspStatus();
22938
+ }
22939
+
22940
+ _shortPreviewUrl(raw) {
22941
+ const value = String(raw || '');
22942
+ try {
22943
+ const parsed = new URL(value);
22944
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
22945
+ return `${parsed.host}${path === '/' ? '' : path}`;
22946
+ } catch (_) {
22947
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
22948
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
22949
+ }
22950
+ }
22951
+
22952
+ /** Update (or create) the CSP status chip in the preview toolbar. */
22953
+ _updatePreviewCspStatus() {
22954
+ if (!this.container) return;
22955
+ const chip = this.container.querySelector('#cl-preview-csp-status');
22956
+ if (!chip) return;
22957
+ const violations = (this.previewState && this.previewState.violations) || [];
22958
+ if (!violations.length) {
22959
+ chip.hidden = true;
22960
+ chip.textContent = '';
22961
+ chip.removeAttribute('title');
22962
+ return;
20870
22963
  }
20871
- return `<head>${tags}</head>${html}`;
22964
+ const last = violations[violations.length - 1];
22965
+ chip.hidden = false;
22966
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
22967
+ chip.title = violations
22968
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
22969
+ .join('\n');
20872
22970
  }
20873
22971
 
20874
22972
  _openWebPreview(port, path = '/') {
20875
22973
  const p = Number(port) || this._firstListeningPort() || 3000;
20876
22974
  this._warnPreviewIsolation();
22975
+ this._installPreviewViolationListener();
20877
22976
  this.previewState.port = p;
20878
22977
  this.previewState.path = path || '/';
20879
22978
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
20880
22979
  this.previewState.error = null;
22980
+ this.previewState.violations = [];
20881
22981
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20882
22982
  this.previewHistory.push(this.previewState.url);
20883
22983
  this.previewHistoryIdx = this.previewHistory.length - 1;
@@ -20968,7 +23068,7 @@ declare module 'bun:sqlite' {
20968
23068
  try {
20969
23069
  const win = window.open(url, '_blank');
20970
23070
  if (win) {
20971
- try { win.opener = null; } catch (_) {}
23071
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
20972
23072
  opened = true;
20973
23073
  }
20974
23074
  } catch (_) { opened = false; }
@@ -20990,7 +23090,9 @@ declare module 'bun:sqlite' {
20990
23090
  const u = new URL(url);
20991
23091
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
20992
23092
  path = u.pathname + (u.search || '') + (u.hash || '');
20993
- } catch (_) {}
23093
+ } catch (err) {
23094
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
23095
+ }
20994
23096
  this.previewState.port = port;
20995
23097
  this.previewState.path = path;
20996
23098
  this.previewState.url = url;
@@ -21022,7 +23124,9 @@ declare module 'bun:sqlite' {
21022
23124
  const u = new URL(url);
21023
23125
  this.previewState.port = Number(u.port || 80);
21024
23126
  this.previewState.path = u.pathname + (u.search || '');
21025
- } catch (_) {}
23127
+ } catch (err) {
23128
+ this.logger.debug('Failed to parse preview history URL.', err);
23129
+ }
21026
23130
  const input = this.container.querySelector('#cl-preview-url-input');
21027
23131
  if (input) input.value = url;
21028
23132
  this._renderWebPreviewControls();
@@ -21056,9 +23160,11 @@ declare module 'bun:sqlite' {
21056
23160
  try {
21057
23161
  const u = new URL(url);
21058
23162
  popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
21059
- } catch (_) {}
23163
+ } catch (err) {
23164
+ this.logger.debug('Failed to parse popout preview URL.', err);
23165
+ }
21060
23166
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
21061
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
23167
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
21062
23168
  }
21063
23169
  return popout;
21064
23170
  }
@@ -21085,6 +23191,19 @@ declare module 'bun:sqlite' {
21085
23191
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
21086
23192
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
21087
23193
 
23194
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
23195
+ const cspHosts = this._previewNetworkHosts();
23196
+ const cspBadge = cspMode === 'strict'
23197
+ ? 'CSP: strict'
23198
+ : !cspHosts.length
23199
+ ? 'CSP: custom'
23200
+ : cspHosts.length === 1
23201
+ ? `CSP: ${cspHosts[0]}`
23202
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
23203
+ const cspBadgeTitle = cspMode === 'strict'
23204
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23205
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23206
+
21088
23207
  bodyEl.innerHTML = `
21089
23208
  <div class="codelab-preview">
21090
23209
  <div class="codelab-preview-chrome">
@@ -21100,10 +23219,12 @@ declare module 'bun:sqlite' {
21100
23219
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'tablet' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="tablet" title="Tablet">${CL_ICONS.tablet || '▢'}</button>
21101
23220
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'mobile' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="mobile" title="Mobile">${CL_ICONS.smartphone || '▯'}</button>
21102
23221
  </div>
23222
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23223
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
21103
23224
  <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-popout" title="Open in a new browser tab">${CL_ICONS.externalLink || '↗'} <span>Pop Out</span></button>
21104
23225
  </div>
21105
23226
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
21106
- <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>
23227
+ <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="no-referrer-when-downgrade" title="Web Preview"></iframe>
21107
23228
  </div>
21108
23229
  ${servers.length
21109
23230
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -21116,6 +23237,7 @@ declare module 'bun:sqlite' {
21116
23237
  </div>`}
21117
23238
  </div>
21118
23239
  `;
23240
+ this._updatePreviewCspStatus();
21119
23241
  this._loadPreviewFrame();
21120
23242
  }
21121
23243
 
@@ -21143,7 +23265,9 @@ declare module 'bun:sqlite' {
21143
23265
  iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
21144
23266
  this.previewState.loading = false;
21145
23267
  return Promise.resolve();
21146
- } catch (_) {}
23268
+ } catch (err) {
23269
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
23270
+ }
21147
23271
  }
21148
23272
 
21149
23273
  // Fallback (no Service Worker): dispatch via the virtual port table and
@@ -21209,7 +23333,7 @@ declare module 'bun:sqlite' {
21209
23333
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
21210
23334
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
21211
23335
  let isDir = false;
21212
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
23336
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
21213
23337
  if (isDir) {
21214
23338
  shellWorkspaceFolders.add(rel);
21215
23339
  walk(full, rel);
@@ -21217,7 +23341,9 @@ declare module 'bun:sqlite' {
21217
23341
  try {
21218
23342
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
21219
23343
  shellWorkspaceFiles.set(rel, content);
21220
- } catch (_) {}
23344
+ } catch (err) {
23345
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
23346
+ }
21221
23347
  }
21222
23348
  }
21223
23349
  };
@@ -21519,6 +23645,27 @@ declare module 'bun:sqlite' {
21519
23645
  }
21520
23646
 
21521
23647
  _notifyCodeChange(filename, code) {
23648
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
23649
+ try {
23650
+ const clean = String(filename).replace(/^\/+/, '');
23651
+ const parts = clean.split('/');
23652
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
23653
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
23654
+ }
23655
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
23656
+ } catch (err) {
23657
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
23658
+ }
23659
+ }
23660
+ if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
23661
+ if (this._previewReloadTimer) {
23662
+ clearTimeout(this._previewReloadTimer);
23663
+ }
23664
+ this._previewReloadTimer = setTimeout(() => {
23665
+ this._previewReloadTimer = null;
23666
+ this._previewReload();
23667
+ }, 300);
23668
+ }
21522
23669
  if (this.onCodeChange) {
21523
23670
  try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21524
23671
  }
@@ -21576,7 +23723,7 @@ declare module 'bun:sqlite' {
21576
23723
  if (fallbackWrap) fallbackWrap.style.display = 'none';
21577
23724
  if (mdPreview) mdPreview.style.display = 'none';
21578
23725
  if (this.editor) {
21579
- try { this.editor.setModel(null); } catch (_) {}
23726
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
21580
23727
  }
21581
23728
  if (emptyEl) {
21582
23729
  emptyEl.style.display = 'flex';
@@ -21888,7 +24035,9 @@ declare module 'bun:sqlite' {
21888
24035
  textarea.select();
21889
24036
  document.execCommand('copy');
21890
24037
  document.body.removeChild(textarea);
21891
- } catch (_) {}
24038
+ } catch (err) {
24039
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
24040
+ }
21892
24041
  };
21893
24042
 
21894
24043
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -22246,6 +24395,7 @@ declare module 'bun:sqlite' {
22246
24395
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
22247
24396
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
22248
24397
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
24398
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
22249
24399
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
22250
24400
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
22251
24401
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -22256,6 +24406,9 @@ declare module 'bun:sqlite' {
22256
24406
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
22257
24407
  } },
22258
24408
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
24409
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
24410
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
24411
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
22259
24412
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
22260
24413
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
22261
24414
  ];
@@ -22288,7 +24441,9 @@ declare module 'bun:sqlite' {
22288
24441
  input.focus();
22289
24442
  try {
22290
24443
  input.setSelectionRange(initialVal.length, initialVal.length);
22291
- } catch (_) {}
24444
+ } catch (err) {
24445
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
24446
+ }
22292
24447
 
22293
24448
  input.addEventListener('input', () => {
22294
24449
  this.paletteSelectedIndex = 0;
@@ -22561,7 +24716,7 @@ declare module 'bun:sqlite' {
22561
24716
  const onUp = ev => {
22562
24717
  vSplitter.classList.remove('is-dragging');
22563
24718
  shell.classList.remove('is-resizing');
22564
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24719
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22565
24720
  vSplitter.removeEventListener('pointermove', onMove);
22566
24721
  vSplitter.removeEventListener('pointerup', onUp);
22567
24722
  };
@@ -22602,7 +24757,7 @@ declare module 'bun:sqlite' {
22602
24757
  const onUp = ev => {
22603
24758
  hSplitter.classList.remove('is-dragging');
22604
24759
  shell.classList.remove('is-resizing-row');
22605
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24760
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22606
24761
  hSplitter.removeEventListener('pointermove', onMove);
22607
24762
  hSplitter.removeEventListener('pointerup', onUp);
22608
24763
  };
@@ -22629,7 +24784,7 @@ declare module 'bun:sqlite' {
22629
24784
  e.preventDefault();
22630
24785
  fSplitter.classList.add('is-dragging');
22631
24786
  shell.classList.add('is-resizing');
22632
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
24787
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
22633
24788
 
22634
24789
  const onMove = ev => {
22635
24790
  const ws = this.container.querySelector('.codelab-workspace');
@@ -22643,7 +24798,7 @@ declare module 'bun:sqlite' {
22643
24798
  const onUp = ev => {
22644
24799
  fSplitter.classList.remove('is-dragging');
22645
24800
  shell.classList.remove('is-resizing');
22646
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
24801
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22647
24802
  fSplitter.removeEventListener('pointermove', onMove);
22648
24803
  fSplitter.removeEventListener('pointerup', onUp);
22649
24804
  this._saveState();
@@ -22986,7 +25141,9 @@ declare module 'bun:sqlite' {
22986
25141
  if (this.files['package.json']) {
22987
25142
  try {
22988
25143
  pkgJson = JSON.parse(this.files['package.json']);
22989
- } catch (_) {}
25144
+ } catch (err) {
25145
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
25146
+ }
22990
25147
  }
22991
25148
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
22992
25149
  pkgJson.dependencies = {};
@@ -23647,6 +25804,219 @@ declare module 'bun:sqlite' {
23647
25804
  return true;
23648
25805
  }
23649
25806
 
25807
+ exportProjectZip(options = {}) {
25808
+ const zipMod = root.CodeLabZip;
25809
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
25810
+ throw new Error('CodeLabZip engine is not loaded');
25811
+ }
25812
+ const bytes = zipMod.createZip(this.files || {});
25813
+ if (options && options.download) {
25814
+ try {
25815
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
25816
+ const blob = new Blob([bytes], { type: 'application/zip' });
25817
+ const url = URL.createObjectURL(blob);
25818
+ const a = document.createElement('a');
25819
+ a.href = url;
25820
+ a.download = `${this.labId || 'workspace'}.zip`;
25821
+ a.click();
25822
+ setTimeout(() => URL.revokeObjectURL(url), 500);
25823
+ }
25824
+ } catch (err) {
25825
+ this.logger.error('Failed to download project ZIP export.', err);
25826
+ }
25827
+ }
25828
+ return bytes;
25829
+ }
25830
+
25831
+ importProjectZip(zipBytes) {
25832
+ const zipMod = root.CodeLabZip;
25833
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
25834
+ throw new Error('CodeLabZip engine is not loaded');
25835
+ }
25836
+ const extracted = zipMod.extractZip(zipBytes);
25837
+ if (!extracted || typeof extracted !== 'object') return false;
25838
+ this.setFiles(extracted);
25839
+ this._syncFilesToShellVfs();
25840
+ return true;
25841
+ }
25842
+
25843
+ searchWorkspace(options) {
25844
+ const searchMod = root.CodeLabSearch;
25845
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
25846
+ throw new Error('CodeLabSearch engine is not loaded');
25847
+ }
25848
+ return searchMod.searchInFiles(this.files || {}, options);
25849
+ }
25850
+
25851
+ replaceInWorkspace(options) {
25852
+ const searchMod = root.CodeLabSearch;
25853
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
25854
+ throw new Error('CodeLabSearch engine is not loaded');
25855
+ }
25856
+ const res = searchMod.replaceInFiles(this.files || {}, options);
25857
+ if (res && res.files && res.filesModified > 0) {
25858
+ this.setFiles(res.files);
25859
+ this._syncFilesToShellVfs();
25860
+ }
25861
+ return res;
25862
+ }
25863
+
25864
+ getGitStatus() {
25865
+ const scmMod = root.CodeLabScm;
25866
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
25867
+ return [];
25868
+ }
25869
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
25870
+ return scmMod.computeGitStatus(gs, this.files || {});
25871
+ }
25872
+
25873
+ getDiagnostics() {
25874
+ const diagMod = root.CodeLabDiagnostics;
25875
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
25876
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
25877
+ }
25878
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
25879
+ return this._diagnosticsStore.getAll();
25880
+ }
25881
+ return [];
25882
+ }
25883
+
25884
+ showSearchModal(initialQuery = '') {
25885
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25886
+ if (!slot) return;
25887
+ const q = String(initialQuery || '');
25888
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
25889
+ const rowsHtml = (results.matches || []).map((m) => `
25890
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
25891
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
25892
+ </div>
25893
+ `).join('');
25894
+ slot.innerHTML = `
25895
+ <div class="codelab-modal-backdrop">
25896
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
25897
+ <div class="codelab-modal__header">
25898
+ <span>Search &amp; Replace Across Workspace</span>
25899
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25900
+ </div>
25901
+ <div class="codelab-modal__body">
25902
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
25903
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
25904
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
25905
+ </div>
25906
+ <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
25907
+ </div>
25908
+ </div>
25909
+ </div>
25910
+ `;
25911
+ }
25912
+
25913
+ showScmModal() {
25914
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25915
+ if (!slot) return;
25916
+ const statusList = this.getGitStatus();
25917
+ const rowsHtml = statusList.map((entry) => `
25918
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
25919
+ <span>${escapeHtml(entry.path)}</span>
25920
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
25921
+ </div>
25922
+ `).join('');
25923
+ slot.innerHTML = `
25924
+ <div class="codelab-modal-backdrop">
25925
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
25926
+ <div class="codelab-modal__header">
25927
+ <span>Source Control (Git Status)</span>
25928
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25929
+ </div>
25930
+ <div class="codelab-modal__body">
25931
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
25932
+ </div>
25933
+ </div>
25934
+ </div>
25935
+ `;
25936
+ }
25937
+
25938
+ showProblemsModal() {
25939
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
25940
+ if (!slot) return;
25941
+ const items = this.getDiagnostics();
25942
+ const rowsHtml = items.map((d) => `
25943
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
25944
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
25945
+ </div>
25946
+ `).join('');
25947
+ slot.innerHTML = `
25948
+ <div class="codelab-modal-backdrop">
25949
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
25950
+ <div class="codelab-modal__header">
25951
+ <span>Problems (${items.length})</span>
25952
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
25953
+ </div>
25954
+ <div class="codelab-modal__body">
25955
+ <div id="cl-problems-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">No problems have been detected in the workspace.</div>'}</div>
25956
+ </div>
25957
+ </div>
25958
+ </div>
25959
+ `;
25960
+ }
25961
+
25962
+ _ensureTerminalSessions() {
25963
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
25964
+ this._terminalSessions = [
25965
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
25966
+ ];
25967
+ this._activeTerminalSessionId = 'session-1';
25968
+ }
25969
+ return this._terminalSessions;
25970
+ }
25971
+
25972
+ listTerminalSessions() {
25973
+ const sessions = this._ensureTerminalSessions();
25974
+ return sessions.map((s) => ({
25975
+ id: s.id,
25976
+ name: s.name,
25977
+ active: s.id === this._activeTerminalSessionId,
25978
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
25979
+ }));
25980
+ }
25981
+
25982
+ createTerminalSession(name) {
25983
+ const sessions = this._ensureTerminalSessions();
25984
+ const nextNum = sessions.length + 1;
25985
+ const id = `session-${Date.now()}-${nextNum}`;
25986
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
25987
+ const newLogs = [];
25988
+ sessions.push({ id, name: label, logs: newLogs });
25989
+ this._activeTerminalSessionId = id;
25990
+ this.terminalLogs = newLogs;
25991
+ this._renderDrawerBody();
25992
+ return id;
25993
+ }
25994
+
25995
+ switchTerminalSession(id) {
25996
+ const sessions = this._ensureTerminalSessions();
25997
+ const target = sessions.find((s) => s.id === id || s.name === id);
25998
+ if (!target) return false;
25999
+ this._activeTerminalSessionId = target.id;
26000
+ this.terminalLogs = target.logs;
26001
+ this._renderDrawerBody();
26002
+ return true;
26003
+ }
26004
+
26005
+ closeTerminalSession(id) {
26006
+ const sessions = this._ensureTerminalSessions();
26007
+ if (sessions.length <= 1) return false;
26008
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
26009
+ if (idx === -1) return false;
26010
+ const removed = sessions.splice(idx, 1)[0];
26011
+ if (this._activeTerminalSessionId === removed.id) {
26012
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
26013
+ this._activeTerminalSessionId = next.id;
26014
+ this.terminalLogs = next.logs;
26015
+ }
26016
+ this._renderDrawerBody();
26017
+ return true;
26018
+ }
26019
+
23650
26020
  getFiles() {
23651
26021
  return { ...this.files };
23652
26022
  }
@@ -23654,7 +26024,7 @@ declare module 'bun:sqlite' {
23654
26024
  setFiles(filesMap) {
23655
26025
  if (!filesMap || typeof filesMap !== 'object') return;
23656
26026
  for (const model of this.models.values()) {
23657
- try { model.dispose(); } catch (_) {}
26027
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
23658
26028
  }
23659
26029
  this.models.clear();
23660
26030
  this.files = {};
@@ -23744,7 +26114,9 @@ declare module 'bun:sqlite' {
23744
26114
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
23745
26115
  try {
23746
26116
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
23747
- } catch (_) {}
26117
+ } catch (err) {
26118
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
26119
+ }
23748
26120
  }
23749
26121
  this._notifyCodeChange(clean, updated);
23750
26122
  }
@@ -23964,9 +26336,22 @@ declare module 'bun:sqlite' {
23964
26336
 
23965
26337
  destroy() {
23966
26338
  this.stopExecution();
26339
+ if (this._previewReloadTimer) {
26340
+ clearTimeout(this._previewReloadTimer);
26341
+ this._previewReloadTimer = null;
26342
+ }
23967
26343
  if (this._escHandler && typeof document !== 'undefined') {
23968
26344
  document.removeEventListener('keydown', this._escHandler);
23969
26345
  }
26346
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26347
+ window.removeEventListener('message', this._previewViolationHandler);
26348
+ }
26349
+ this._previewViolationHandler = null;
26350
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
26351
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
26352
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
26353
+ }
26354
+ this._swMessageHandler = null;
23970
26355
  if (this._themeObserver) {
23971
26356
  this._themeObserver.disconnect();
23972
26357
  }
@@ -24027,7 +26412,9 @@ declare module 'bun:sqlite' {
24027
26412
  if (jsonScript && jsonScript.textContent) {
24028
26413
  try {
24029
26414
  inlineConfig = JSON.parse(jsonScript.textContent);
24030
- } catch (_) {}
26415
+ } catch (err) {
26416
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
26417
+ }
24031
26418
  }
24032
26419
 
24033
26420
  // Parse optional files JSON attribute
@@ -24036,7 +26423,9 @@ declare module 'bun:sqlite' {
24036
26423
  if (filesAttr) {
24037
26424
  try {
24038
26425
  attrFiles = JSON.parse(filesAttr);
24039
- } catch (_) {}
26426
+ } catch (err) {
26427
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
26428
+ }
24040
26429
  }
24041
26430
 
24042
26431
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -24079,6 +26468,19 @@ declare module 'bun:sqlite' {
24079
26468
  reset() { if (this._instance) this._instance.reset(); }
24080
26469
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
24081
26470
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
26471
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
26472
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
26473
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
26474
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
26475
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
26476
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
26477
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
26478
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
26479
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
26480
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
26481
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
26482
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
26483
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
24082
26484
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
24083
26485
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
24084
26486
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -24113,9 +26515,42 @@ declare module 'bun:sqlite' {
24113
26515
  Workbench: CodeLabWorkbench,
24114
26516
  CodeLabWorkbench,
24115
26517
  CodeLabElement: CodeLabElementClass,
26518
+ CodeLabError,
26519
+ isCodeLabError,
26520
+ createLogger,
26521
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
26522
+ html,
26523
+ raw,
26524
+ isSafeHtml,
26525
+ escapeHtml,
26526
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
24116
26527
  Runtime: root.CodeLabRuntime,
24117
26528
  Shell: root.CodeLabShell,
24118
26529
  Terminal: root.CodeLabTerminal,
26530
+ zip: root.CodeLabZip || null,
26531
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
26532
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
26533
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
26534
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
26535
+ storage: root.CodeLabStorage || null,
26536
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
26537
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
26538
+ search: root.CodeLabSearch || null,
26539
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
26540
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
26541
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
26542
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
26543
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
26544
+ diagnostics: root.CodeLabDiagnostics || null,
26545
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
26546
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
26547
+ scm: root.CodeLabScm || null,
26548
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
26549
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
26550
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
26551
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
26552
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
26553
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
24119
26554
  renderMarkdown: renderSimpleMarkdown,
24120
26555
  renderSimpleMarkdown: renderSimpleMarkdown,
24121
26556
  extensions: {
@@ -24166,6 +26601,7 @@ const createVirtualFs = CodeLabRuntime.createVirtualFs;
24166
26601
  const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
24167
26602
  const createVirtualNet = CodeLabRuntime.createVirtualNet;
24168
26603
  const createVirtualPortTable = CodeLabRuntime.createVirtualPortTable;
26604
+ const createWorkerRuntimeSource = CodeLabRuntime.createWorkerRuntimeSource;
24169
26605
  const createPosixShell = CodeLabShell ? CodeLabShell.createPosixShell : null;
24170
26606
  const cloneGitHubRepository = CodeLabShell ? CodeLabShell.cloneGitHubRepository : null;
24171
26607
  const parseGitHubRepoUrl = CodeLabShell ? CodeLabShell.parseGitHubRepoUrl : null;
@@ -24176,11 +26612,46 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
24176
26612
  const mount = CodeLab ? CodeLab.mount : null;
24177
26613
  const create = CodeLab ? CodeLab.create : null;
24178
26614
  const unmount = CodeLab ? CodeLab.unmount : null;
24179
- const version = CodeLab ? CodeLab.version : '0.1.7';
26615
+ const version = CodeLab ? CodeLab.version : '0.1.8';
24180
26616
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
24181
26617
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
24182
26618
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
24183
26619
  const extensions = CodeLab ? CodeLab.extensions : null;
26620
+ const CodeLabError = CodeLabLogger.CodeLabError;
26621
+ const isCodeLabError = CodeLabLogger.isCodeLabError;
26622
+ const createLogger = CodeLabLogger.createLogger;
26623
+ const DEFAULT_LOGGER = CodeLabLogger.DEFAULT_LOGGER;
26624
+ const LOG_PREFIX = CodeLabLogger.LOG_PREFIX;
26625
+ const Logger = CodeLab ? CodeLab.Logger : CodeLabLogger;
26626
+ const html = CodeLabHtml.html;
26627
+ const raw = CodeLabHtml.raw;
26628
+ const isSafeHtml = CodeLabHtml.isSafeHtml;
26629
+ const escapeHtml = CodeLabHtml.escapeHtml;
26630
+ const Html = CodeLab ? CodeLab.Html : CodeLabHtml;
26631
+ const zip = CodeLabZip;
26632
+ const createZip = CodeLabZip.createZip;
26633
+ const extractZip = CodeLabZip.extractZip;
26634
+ const computeCrc32 = CodeLabZip.computeCrc32;
26635
+ const sanitizeZipPath = CodeLabZip.sanitizeZipPath;
26636
+ const storage = CodeLabStorage;
26637
+ const WorkspaceStorage = CodeLabStorage.WorkspaceStorage;
26638
+ const createWorkspaceStorage = CodeLabStorage.createWorkspaceStorage;
26639
+ const search = CodeLabSearch;
26640
+ const searchInFiles = CodeLabSearch.searchInFiles;
26641
+ const replaceInFiles = CodeLabSearch.replaceInFiles;
26642
+ const matchesGlob = CodeLabSearch.matchesGlob;
26643
+ const escapeRegex = CodeLabSearch.escapeRegex;
26644
+ const normalizeSearchPath = CodeLabSearch.normalizeSearchPath;
26645
+ const diagnostics = CodeLabDiagnostics;
26646
+ const DiagnosticsStore = CodeLabDiagnostics.DiagnosticsStore;
26647
+ const createDiagnosticsStore = CodeLabDiagnostics.createDiagnosticsStore;
26648
+ const scm = CodeLabScm;
26649
+ const createGitState = CodeLabScm.createGitState;
26650
+ const computeGitStatus = CodeLabScm.computeGitStatus;
26651
+ const stageFile = CodeLabScm.stageFile;
26652
+ const unstageFile = CodeLabScm.unstageFile;
26653
+ const commitChanges = CodeLabScm.commitChanges;
26654
+ const computeShortCommitHash = CodeLabScm.computeShortCommitHash;
24184
26655
 
24185
26656
  export {
24186
26657
  CodeLab,
@@ -24201,6 +26672,49 @@ export {
24201
26672
  renderSimpleMarkdown,
24202
26673
  cloneRepo,
24203
26674
  extensions,
26675
+ CodeLabCsp,
26676
+ CodeLabLogger,
26677
+ Logger,
26678
+ CodeLabHtml,
26679
+ Html,
26680
+ html,
26681
+ raw,
26682
+ isSafeHtml,
26683
+ escapeHtml,
26684
+ CodeLabError,
26685
+ isCodeLabError,
26686
+ createLogger,
26687
+ DEFAULT_LOGGER,
26688
+ LOG_PREFIX,
26689
+ CodeLabZip,
26690
+ zip,
26691
+ createZip,
26692
+ extractZip,
26693
+ computeCrc32,
26694
+ sanitizeZipPath,
26695
+ CodeLabStorage,
26696
+ storage,
26697
+ WorkspaceStorage,
26698
+ createWorkspaceStorage,
26699
+ CodeLabSearch,
26700
+ search,
26701
+ searchInFiles,
26702
+ replaceInFiles,
26703
+ matchesGlob,
26704
+ escapeRegex,
26705
+ normalizeSearchPath,
26706
+ CodeLabDiagnostics,
26707
+ diagnostics,
26708
+ DiagnosticsStore,
26709
+ createDiagnosticsStore,
26710
+ CodeLabScm,
26711
+ scm,
26712
+ createGitState,
26713
+ computeGitStatus,
26714
+ stageFile,
26715
+ unstageFile,
26716
+ commitChanges,
26717
+ computeShortCommitHash,
24204
26718
  createPosixShell,
24205
26719
  cloneGitHubRepository,
24206
26720
  parseGitHubRepoUrl,
@@ -24216,6 +26730,7 @@ export {
24216
26730
  createVirtualFs,
24217
26731
  createVirtualHttp,
24218
26732
  createVirtualNet,
24219
- createVirtualPortTable
26733
+ createVirtualPortTable,
26734
+ createWorkerRuntimeSource
24220
26735
  };
24221
26736
  export default CodeLab;