@innovatorved/code-lab 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +34 -16
- package/README.md +17 -7
- package/dist/code-lab.css +683 -0
- package/dist/code-lab.d.ts +271 -1
- package/dist/code-lab.esm.js +3326 -193
- package/dist/code-lab.js +3286 -191
- package/dist/csp.d.ts +86 -0
- package/dist/diagnostics.d.ts +43 -0
- package/dist/extensions/guided-lab.esm.js +63 -0
- package/dist/extensions/guided-lab.js +63 -0
- package/dist/html.d.ts +24 -0
- package/dist/index.d.ts +9 -1
- package/dist/logger.d.ts +60 -0
- package/dist/preview-sw.js +604 -46
- package/dist/runtime.esm.js +169 -31
- package/dist/runtime.js +169 -31
- package/dist/schemas.d.ts +357 -25
- package/dist/schemas.esm.js +70 -0
- package/dist/schemas.js +70 -0
- package/dist/scm.d.ts +77 -0
- package/dist/search.d.ts +75 -0
- package/dist/shell.esm.js +333 -48
- package/dist/shell.js +333 -48
- package/dist/storage.d.ts +57 -0
- package/dist/terminal.esm.js +122 -7
- package/dist/terminal.js +122 -7
- package/dist/zip.d.ts +42 -0
- package/package.json +3 -1
- package/src/code-lab.css +683 -0
- package/src/csp.ts +588 -0
- package/src/diagnostics.ts +116 -0
- package/src/html.ts +88 -0
- package/src/index.ts +39 -1
- package/src/logger.ts +139 -0
- package/src/preview-sw.js +84 -46
- package/src/runtime.ts +67 -30
- package/src/schemas.ts +91 -1
- package/src/scm.ts +268 -0
- package/src/search.ts +389 -0
- package/src/shell.ts +231 -47
- package/src/storage.ts +377 -0
- package/src/terminal.ts +20 -6
- package/src/workbench.ts +1061 -107
- package/src/zip.ts +326 -0
package/dist/shell.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
3
|
+
* @innovatorved/code-lab v0.1.9 — Standalone Browser Code IDE & Virtual Runtime
|
|
4
4
|
* ============================================================
|
|
5
5
|
* Features:
|
|
6
6
|
* - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
|
|
@@ -15,6 +15,107 @@
|
|
|
15
15
|
* ============================================================
|
|
16
16
|
*/
|
|
17
17
|
const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : {};
|
|
18
|
+
var CodeLabLogger = (() => {
|
|
19
|
+
var __defProp = Object.defineProperty;
|
|
20
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
21
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
22
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
23
|
+
var __export = (target, all) => {
|
|
24
|
+
for (var name in all)
|
|
25
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
26
|
+
};
|
|
27
|
+
var __copyProps = (to, from, except, desc) => {
|
|
28
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
29
|
+
for (let key of __getOwnPropNames(from))
|
|
30
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
31
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
32
|
+
}
|
|
33
|
+
return to;
|
|
34
|
+
};
|
|
35
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
36
|
+
|
|
37
|
+
// src/logger.ts
|
|
38
|
+
var logger_exports = {};
|
|
39
|
+
__export(logger_exports, {
|
|
40
|
+
CodeLabError: () => CodeLabError,
|
|
41
|
+
DEFAULT_LOGGER: () => DEFAULT_LOGGER,
|
|
42
|
+
LOG_PREFIX: () => LOG_PREFIX,
|
|
43
|
+
createLogger: () => createLogger,
|
|
44
|
+
default: () => logger_default,
|
|
45
|
+
isCodeLabError: () => isCodeLabError
|
|
46
|
+
});
|
|
47
|
+
var LOG_PREFIX = "[code-lab]";
|
|
48
|
+
var CodeLabError = class extends Error {
|
|
49
|
+
code;
|
|
50
|
+
options;
|
|
51
|
+
cause;
|
|
52
|
+
recoverable;
|
|
53
|
+
details;
|
|
54
|
+
context;
|
|
55
|
+
constructor(code, message, options = {}) {
|
|
56
|
+
super(message);
|
|
57
|
+
this.name = "CodeLabError";
|
|
58
|
+
this.code = code;
|
|
59
|
+
this.options = options;
|
|
60
|
+
this.cause = options.cause;
|
|
61
|
+
this.recoverable = options.recoverable !== false;
|
|
62
|
+
const meta = options.details ?? options.context;
|
|
63
|
+
if (meta !== void 0) {
|
|
64
|
+
this.details = meta;
|
|
65
|
+
this.context = meta;
|
|
66
|
+
}
|
|
67
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
function isCodeLabError(value) {
|
|
71
|
+
return Boolean(
|
|
72
|
+
value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
function createLogger(options = {}) {
|
|
76
|
+
const sink = options.logger ?? null;
|
|
77
|
+
const debugEnabled = options.debug === true;
|
|
78
|
+
const prefix = options.prefix || LOG_PREFIX;
|
|
79
|
+
const write = (level, args) => {
|
|
80
|
+
if (level === "debug" && !debugEnabled) return;
|
|
81
|
+
if (sink && typeof sink[level] === "function") {
|
|
82
|
+
let sinkError = null;
|
|
83
|
+
try {
|
|
84
|
+
sink[level](...args);
|
|
85
|
+
return;
|
|
86
|
+
} catch (err) {
|
|
87
|
+
sinkError = err;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const consoleObj = typeof console !== "undefined" ? console : null;
|
|
91
|
+
const fn = consoleObj ? consoleObj[level] : null;
|
|
92
|
+
if (typeof fn === "function") {
|
|
93
|
+
fn.call(consoleObj, prefix, ...args);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
return {
|
|
97
|
+
debug: (...args) => write("debug", args),
|
|
98
|
+
info: (...args) => write("info", args),
|
|
99
|
+
warn: (...args) => write("warn", args),
|
|
100
|
+
error: (...args) => write("error", args)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
var DEFAULT_LOGGER = createLogger();
|
|
104
|
+
var _loggerNamespace = {
|
|
105
|
+
LOG_PREFIX,
|
|
106
|
+
CodeLabError,
|
|
107
|
+
isCodeLabError,
|
|
108
|
+
createLogger,
|
|
109
|
+
DEFAULT_LOGGER
|
|
110
|
+
};
|
|
111
|
+
var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
|
|
112
|
+
if (_globalRoot && !_globalRoot.CodeLabLogger) {
|
|
113
|
+
_globalRoot.CodeLabLogger = _loggerNamespace;
|
|
114
|
+
}
|
|
115
|
+
var logger_default = _loggerNamespace;
|
|
116
|
+
return __toCommonJS(logger_exports);
|
|
117
|
+
})();
|
|
118
|
+
|
|
18
119
|
(function () {
|
|
19
120
|
// @ts-nocheck
|
|
20
121
|
/**
|
|
@@ -63,12 +164,23 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
63
164
|
})(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
|
|
64
165
|
'use strict';
|
|
65
166
|
|
|
167
|
+
const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
|
|
168
|
+
? root.CodeLabLogger.createLogger()
|
|
169
|
+
: {
|
|
170
|
+
debug() {},
|
|
171
|
+
info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
|
|
172
|
+
warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
|
|
173
|
+
error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
|
|
174
|
+
};
|
|
175
|
+
|
|
66
176
|
function getRuntimeModule() {
|
|
67
177
|
if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
|
|
68
178
|
if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
|
|
69
179
|
try {
|
|
70
180
|
if (typeof require !== 'undefined') return require('./runtime.js');
|
|
71
|
-
} catch (
|
|
181
|
+
} catch (err) {
|
|
182
|
+
_shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
|
|
183
|
+
}
|
|
72
184
|
return null;
|
|
73
185
|
}
|
|
74
186
|
|
|
@@ -660,7 +772,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
660
772
|
if (typeof vfs.statSync === 'function') {
|
|
661
773
|
isDir = vfs.statSync(full).isDirectory();
|
|
662
774
|
}
|
|
663
|
-
} catch (
|
|
775
|
+
} catch (err) {
|
|
776
|
+
_shellLogger.debug('Glob statSync failed.', full, err);
|
|
777
|
+
}
|
|
664
778
|
|
|
665
779
|
if (isDir) {
|
|
666
780
|
traverse(full, rel);
|
|
@@ -1982,7 +2096,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
1982
2096
|
: name;
|
|
1983
2097
|
try {
|
|
1984
2098
|
snap[rel] = String(vfs.readFileSync(full, 'utf8'));
|
|
1985
|
-
} catch (
|
|
2099
|
+
} catch (err) {
|
|
2100
|
+
_shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
|
|
2101
|
+
}
|
|
1986
2102
|
}
|
|
1987
2103
|
}
|
|
1988
2104
|
}
|
|
@@ -2086,8 +2202,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2086
2202
|
}
|
|
2087
2203
|
}
|
|
2088
2204
|
}
|
|
2089
|
-
} catch (
|
|
2205
|
+
} catch (err) {
|
|
2090
2206
|
// Network or rate limit error on api.github.com; proceed to Strategy B
|
|
2207
|
+
_shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
|
|
2091
2208
|
}
|
|
2092
2209
|
|
|
2093
2210
|
// Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
|
|
@@ -2114,7 +2231,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2114
2231
|
}
|
|
2115
2232
|
}
|
|
2116
2233
|
}
|
|
2117
|
-
} catch (
|
|
2234
|
+
} catch (err) {
|
|
2235
|
+
_shellLogger.debug('jsDelivr flat tree fetch failed.', err);
|
|
2236
|
+
}
|
|
2118
2237
|
}
|
|
2119
2238
|
|
|
2120
2239
|
if (repoNotFound || !rawTreeEntries) {
|
|
@@ -2262,7 +2381,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2262
2381
|
}));
|
|
2263
2382
|
}
|
|
2264
2383
|
}
|
|
2265
|
-
} catch (
|
|
2384
|
+
} catch (err) {
|
|
2385
|
+
_shellLogger.debug('Optional commit history fetch skipped.', err);
|
|
2386
|
+
}
|
|
2266
2387
|
|
|
2267
2388
|
if (commits.length === 0) {
|
|
2268
2389
|
commits = [
|
|
@@ -2328,7 +2449,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2328
2449
|
try {
|
|
2329
2450
|
const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
|
|
2330
2451
|
return { path: p, data: parsed };
|
|
2331
|
-
} catch (
|
|
2452
|
+
} catch (err) {
|
|
2453
|
+
_shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
|
|
2454
|
+
}
|
|
2332
2455
|
}
|
|
2333
2456
|
return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
|
|
2334
2457
|
}
|
|
@@ -2369,13 +2492,20 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2369
2492
|
vfs.rmdirSync(dirPath);
|
|
2370
2493
|
}
|
|
2371
2494
|
if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
|
|
2372
|
-
} catch (
|
|
2495
|
+
} catch (err) {
|
|
2496
|
+
_shellLogger.debug('removeDirRecursive failed.', dirPath, err);
|
|
2497
|
+
}
|
|
2373
2498
|
}
|
|
2374
2499
|
|
|
2375
2500
|
// ---------------------------------------------------------------------------
|
|
2376
2501
|
// Real npm package installation via the jsDelivr CDN
|
|
2377
2502
|
// ---------------------------------------------------------------------------
|
|
2378
2503
|
const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2504
|
+
const CDN_NPM_BASES = [
|
|
2505
|
+
'https://cdn.jsdelivr.net/npm',
|
|
2506
|
+
'https://unpkg.com',
|
|
2507
|
+
'https://esm.sh'
|
|
2508
|
+
];
|
|
2379
2509
|
|
|
2380
2510
|
// Minimal offline registry, used only when the CDN is unreachable so common
|
|
2381
2511
|
// demos still resolve without network access.
|
|
@@ -2521,16 +2651,23 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2521
2651
|
}
|
|
2522
2652
|
|
|
2523
2653
|
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
2524
|
-
const
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
const
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2654
|
+
for (const base of CDN_NPM_BASES) {
|
|
2655
|
+
const urls = range
|
|
2656
|
+
? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
|
|
2657
|
+
: [`${base}/${name}/package.json`];
|
|
2658
|
+
for (const url of urls) {
|
|
2659
|
+
const text = await fetchTextFromCdn(fetchImpl, url);
|
|
2660
|
+
if (!text) continue;
|
|
2661
|
+
try {
|
|
2662
|
+
const parsed = JSON.parse(text);
|
|
2663
|
+
if (parsed && parsed.version) {
|
|
2664
|
+
parsed._resolvedCdnBase = base;
|
|
2665
|
+
return parsed;
|
|
2666
|
+
}
|
|
2667
|
+
} catch (err) {
|
|
2668
|
+
_shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2534
2671
|
}
|
|
2535
2672
|
return null;
|
|
2536
2673
|
}
|
|
@@ -2548,6 +2685,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2548
2685
|
return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
|
|
2549
2686
|
}
|
|
2550
2687
|
|
|
2688
|
+
const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
|
|
2551
2689
|
const version = meta.version;
|
|
2552
2690
|
const key = `${name}@${version}`;
|
|
2553
2691
|
if (seen.has(key)) {
|
|
@@ -2595,7 +2733,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2595
2733
|
frontier = [];
|
|
2596
2734
|
if (batch.length === 0) break;
|
|
2597
2735
|
const texts = await Promise.all(
|
|
2598
|
-
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${
|
|
2736
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
|
|
2599
2737
|
);
|
|
2600
2738
|
for (let idx = 0; idx < batch.length; idx++) {
|
|
2601
2739
|
const rel = batch[idx];
|
|
@@ -2619,7 +2757,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2619
2757
|
}
|
|
2620
2758
|
// The declared entry may be missing on the CDN; fall back to index.js.
|
|
2621
2759
|
if (!files.some(f => f.rel === entry)) {
|
|
2622
|
-
const idxText = await fetchTextFromCdn(fetchImpl, `${
|
|
2760
|
+
const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
|
|
2623
2761
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2624
2762
|
}
|
|
2625
2763
|
|
|
@@ -2666,7 +2804,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2666
2804
|
// directory target would otherwise raise EISDIR).
|
|
2667
2805
|
try {
|
|
2668
2806
|
if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
|
|
2669
|
-
} catch (
|
|
2807
|
+
} catch (err) {
|
|
2808
|
+
_shellLogger.debug('Package install statSync check skipped.', full, err);
|
|
2809
|
+
}
|
|
2670
2810
|
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2671
2811
|
ctx.vfs.writeFileSync(full, f.content);
|
|
2672
2812
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
@@ -2744,6 +2884,32 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2744
2884
|
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2745
2885
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2746
2886
|
|
|
2887
|
+
// Also maintain package-lock.json in the same directory for deterministic lockfile verification
|
|
2888
|
+
try {
|
|
2889
|
+
const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
|
|
2890
|
+
let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
|
|
2891
|
+
if (ctx.vfs.existsSync(lockPath)) {
|
|
2892
|
+
const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
|
|
2893
|
+
const parsedLock = JSON.parse(rawLock);
|
|
2894
|
+
if (parsedLock && typeof parsedLock === 'object') {
|
|
2895
|
+
lockData = parsedLock;
|
|
2896
|
+
if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
for (const inst of installed) {
|
|
2900
|
+
if (inst && inst.name) {
|
|
2901
|
+
lockData.packages[`node_modules/${inst.name}`] = {
|
|
2902
|
+
version: inst.version || '1.0.0',
|
|
2903
|
+
resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
|
|
2904
|
+
};
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
|
|
2908
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
|
|
2909
|
+
} catch (err) {
|
|
2910
|
+
_shellLogger.debug('Could not write package-lock.json during installPackage.', err);
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2747
2913
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2748
2914
|
}
|
|
2749
2915
|
|
|
@@ -2941,7 +3107,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2941
3107
|
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2942
3108
|
if (parsed && parsed.version) return parsed.version;
|
|
2943
3109
|
}
|
|
2944
|
-
} catch (
|
|
3110
|
+
} catch (err) {
|
|
3111
|
+
_shellLogger.debug('Could not read installed module package.json.', pkgName, err);
|
|
3112
|
+
}
|
|
2945
3113
|
try {
|
|
2946
3114
|
for (const dir of [rootDir, '/workspace']) {
|
|
2947
3115
|
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
@@ -2950,7 +3118,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2950
3118
|
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2951
3119
|
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2952
3120
|
}
|
|
2953
|
-
} catch (
|
|
3121
|
+
} catch (err) {
|
|
3122
|
+
_shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
|
|
3123
|
+
}
|
|
2954
3124
|
return 'latest';
|
|
2955
3125
|
}
|
|
2956
3126
|
|
|
@@ -2973,10 +3143,10 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2973
3143
|
return imports;
|
|
2974
3144
|
}
|
|
2975
3145
|
|
|
2976
|
-
function
|
|
2977
|
-
const
|
|
3146
|
+
function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
|
|
3147
|
+
const files = [];
|
|
2978
3148
|
const walk = (dir, depth) => {
|
|
2979
|
-
if (depth > 8 ||
|
|
3149
|
+
if (depth > 8 || files.length >= maxFiles) return;
|
|
2980
3150
|
let entries = [];
|
|
2981
3151
|
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2982
3152
|
for (const name of entries) {
|
|
@@ -2987,13 +3157,23 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
2987
3157
|
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2988
3158
|
if (dirFlag) {
|
|
2989
3159
|
walk(full, depth + 1);
|
|
2990
|
-
} else if (isPreviewScriptPath(name) &&
|
|
2991
|
-
try {
|
|
3160
|
+
} else if (isPreviewScriptPath(name) && files.length < maxFiles) {
|
|
3161
|
+
try {
|
|
3162
|
+
const content = vfs.readFileSync(full, 'utf8');
|
|
3163
|
+
const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
|
|
3164
|
+
files.push({ full, rel, content });
|
|
3165
|
+
} catch (err) {
|
|
3166
|
+
_shellLogger.debug('Preview script read skipped.', full, err);
|
|
3167
|
+
}
|
|
2992
3168
|
}
|
|
2993
3169
|
}
|
|
2994
3170
|
};
|
|
2995
3171
|
walk(rootDir, 0);
|
|
2996
|
-
return
|
|
3172
|
+
return files;
|
|
3173
|
+
}
|
|
3174
|
+
|
|
3175
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
3176
|
+
return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
|
|
2997
3177
|
}
|
|
2998
3178
|
|
|
2999
3179
|
function injectPreviewExtras(html, importMap) {
|
|
@@ -3018,12 +3198,6 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3018
3198
|
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
3019
3199
|
while (taken.has(port)) port++;
|
|
3020
3200
|
|
|
3021
|
-
const specifiers = new Set();
|
|
3022
|
-
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
3023
|
-
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
3024
|
-
}
|
|
3025
|
-
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
3026
|
-
|
|
3027
3201
|
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
3028
3202
|
const isDir = (p) => {
|
|
3029
3203
|
try {
|
|
@@ -3031,11 +3205,112 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3031
3205
|
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
3032
3206
|
} catch (_) { return false; }
|
|
3033
3207
|
};
|
|
3208
|
+
const isFile = (p) => exists(p) && !isDir(p);
|
|
3034
3209
|
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
3035
3210
|
|
|
3211
|
+
const resolveLocalTarget = (baseDir, rawSpec) => {
|
|
3212
|
+
if (!rawSpec || typeof rawSpec !== 'string') return null;
|
|
3213
|
+
const clean = rawSpec.split(/[?#]/)[0].trim();
|
|
3214
|
+
if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
|
|
3215
|
+
const candidateBase = clean.startsWith('/')
|
|
3216
|
+
? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
|
|
3217
|
+
: PosixPath.join(baseDir, clean);
|
|
3218
|
+
if (isFile(candidateBase)) return candidateBase;
|
|
3219
|
+
const cands = [
|
|
3220
|
+
candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
|
|
3221
|
+
candidateBase + '.mjs', candidateBase + '.cjs',
|
|
3222
|
+
PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
|
|
3223
|
+
PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
|
|
3224
|
+
];
|
|
3225
|
+
for (const c of cands) {
|
|
3226
|
+
if (isFile(c)) return c;
|
|
3227
|
+
}
|
|
3228
|
+
return null;
|
|
3229
|
+
};
|
|
3230
|
+
|
|
3231
|
+
const toLocalImportKey = (fullPath) => {
|
|
3232
|
+
const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
|
|
3233
|
+
return `@codelab-local/${rel}`;
|
|
3234
|
+
};
|
|
3235
|
+
|
|
3236
|
+
const transpileAndRewriteLocalImports = (code, sourcePath) => {
|
|
3237
|
+
let out = code;
|
|
3238
|
+
try {
|
|
3239
|
+
const rm = getRuntimeModule();
|
|
3240
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3241
|
+
out = rm.transpileForBrowser(out, sourcePath);
|
|
3242
|
+
}
|
|
3243
|
+
} catch (err) {
|
|
3244
|
+
_shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
|
|
3245
|
+
}
|
|
3246
|
+
const fromDir = PosixPath.dirname(sourcePath);
|
|
3247
|
+
const rewriteSpec = (spec) => {
|
|
3248
|
+
if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
|
|
3249
|
+
const resolved = resolveLocalTarget(fromDir, spec);
|
|
3250
|
+
return resolved ? toLocalImportKey(resolved) : spec;
|
|
3251
|
+
};
|
|
3252
|
+
out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
|
|
3253
|
+
out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
|
|
3254
|
+
return out;
|
|
3255
|
+
};
|
|
3256
|
+
|
|
3257
|
+
const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
|
|
3258
|
+
const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
|
|
3259
|
+
const specifiers = new Set();
|
|
3260
|
+
for (const f of scriptFiles) {
|
|
3261
|
+
for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
|
|
3262
|
+
}
|
|
3263
|
+
// Also scan inline module scripts in HTML for bare specifiers
|
|
3264
|
+
const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
|
|
3265
|
+
let inlineMatch;
|
|
3266
|
+
while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
|
|
3267
|
+
if (inlineMatch[1]) {
|
|
3268
|
+
for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
|
|
3272
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
3273
|
+
for (const f of scriptFiles) {
|
|
3274
|
+
const compiled = transpileAndRewriteLocalImports(f.content, f.full);
|
|
3275
|
+
const key = toLocalImportKey(f.full);
|
|
3276
|
+
importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
|
|
3277
|
+
}
|
|
3278
|
+
|
|
3279
|
+
const htmlDir = PosixPath.dirname(htmlTargetPath);
|
|
3280
|
+
let transformedHtml = htmlBody;
|
|
3281
|
+
|
|
3282
|
+
// Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
|
|
3283
|
+
transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
|
|
3284
|
+
if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
|
|
3285
|
+
const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
3286
|
+
if (!hrefMatch) return fullTag;
|
|
3287
|
+
const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
|
|
3288
|
+
if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
|
|
3289
|
+
const cssContent = readText(cssTarget);
|
|
3290
|
+
if (cssContent === null) return fullTag;
|
|
3291
|
+
return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '"')}">\n${cssContent}\n</style>`;
|
|
3292
|
+
});
|
|
3293
|
+
|
|
3294
|
+
// Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
|
|
3295
|
+
transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
|
|
3296
|
+
const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
3297
|
+
if (!srcMatch) return fullTag;
|
|
3298
|
+
const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
|
|
3299
|
+
if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
|
|
3300
|
+
const rawScript = readText(scriptTarget);
|
|
3301
|
+
if (rawScript === null) return fullTag;
|
|
3302
|
+
const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
|
|
3303
|
+
const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
|
|
3304
|
+
const typeAttr = isMod ? ' type="module"' : '';
|
|
3305
|
+
return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '"')}">\n${compiled}\n</script>`;
|
|
3306
|
+
});
|
|
3307
|
+
|
|
3308
|
+
return injectPreviewExtras(transformedHtml, importMap);
|
|
3309
|
+
};
|
|
3310
|
+
|
|
3036
3311
|
const handler = async (request) => {
|
|
3037
3312
|
let pathname = '/';
|
|
3038
|
-
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (
|
|
3313
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
|
|
3039
3314
|
const rel = pathname.replace(/^\/+/, '');
|
|
3040
3315
|
let target = PosixPath.join(rootDir, rel);
|
|
3041
3316
|
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
@@ -3067,14 +3342,16 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3067
3342
|
let body = readText(target);
|
|
3068
3343
|
if (body === null) body = '';
|
|
3069
3344
|
if (/\.html?$/i.test(target)) {
|
|
3070
|
-
body =
|
|
3345
|
+
body = buildHtmlPreviewResponse(body, target);
|
|
3071
3346
|
} else if (isPreviewScriptPath(target)) {
|
|
3072
3347
|
try {
|
|
3073
3348
|
const rm = getRuntimeModule();
|
|
3074
3349
|
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3075
3350
|
body = rm.transpileForBrowser(body, target);
|
|
3076
3351
|
}
|
|
3077
|
-
} catch (
|
|
3352
|
+
} catch (err) {
|
|
3353
|
+
_shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
|
|
3354
|
+
}
|
|
3078
3355
|
}
|
|
3079
3356
|
|
|
3080
3357
|
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
@@ -3082,7 +3359,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3082
3359
|
|
|
3083
3360
|
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
3084
3361
|
return portTable.registerServer(port, {
|
|
3085
|
-
server: { close() { try { portTable.unregisterServer(port); } catch (
|
|
3362
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
|
|
3086
3363
|
fetch: handler,
|
|
3087
3364
|
name: 'code-lab-serve',
|
|
3088
3365
|
pid,
|
|
@@ -3195,7 +3472,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3195
3472
|
let isDir = false;
|
|
3196
3473
|
try {
|
|
3197
3474
|
isDir = ctx.vfs.statSync(resolved).isDirectory();
|
|
3198
|
-
} catch (
|
|
3475
|
+
} catch (err) {
|
|
3476
|
+
_shellLogger.debug('cd statSync failed.', resolved, err);
|
|
3477
|
+
}
|
|
3199
3478
|
|
|
3200
3479
|
if (!isDir) {
|
|
3201
3480
|
return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
|
|
@@ -3295,7 +3574,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3295
3574
|
isDirectory = st.isDirectory();
|
|
3296
3575
|
size = st.size;
|
|
3297
3576
|
mtimeMs = st.mtimeMs || Date.now();
|
|
3298
|
-
} catch (
|
|
3577
|
+
} catch (err) {
|
|
3578
|
+
_shellLogger.debug('ls statSync skipped.', itemPath, err);
|
|
3579
|
+
}
|
|
3299
3580
|
return { name, isDirectory, size, mtimeMs, absPath: itemPath };
|
|
3300
3581
|
});
|
|
3301
3582
|
|
|
@@ -3715,7 +3996,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3715
3996
|
if (st.isDirectory()) walk(full);
|
|
3716
3997
|
else targets.push(full);
|
|
3717
3998
|
}
|
|
3718
|
-
} catch (
|
|
3999
|
+
} catch (err) {
|
|
4000
|
+
_shellLogger.debug('grep directory walk skipped.', dir, err);
|
|
4001
|
+
}
|
|
3719
4002
|
}
|
|
3720
4003
|
if (ctx.vfs.existsSync(absRoot)) {
|
|
3721
4004
|
const st = ctx.vfs.statSync(absRoot);
|
|
@@ -3839,7 +4122,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3839
4122
|
let isDir = false;
|
|
3840
4123
|
try {
|
|
3841
4124
|
isDir = ctx.vfs.statSync(full).isDirectory();
|
|
3842
|
-
} catch (
|
|
4125
|
+
} catch (err) {
|
|
4126
|
+
_shellLogger.debug('find statSync skipped.', full, err);
|
|
4127
|
+
}
|
|
3843
4128
|
|
|
3844
4129
|
const relPath = root === '.'
|
|
3845
4130
|
? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
|
|
@@ -3858,7 +4143,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
3858
4143
|
// Root itself check
|
|
3859
4144
|
if (ctx.vfs.existsSync(absRoot)) {
|
|
3860
4145
|
let isDir = false;
|
|
3861
|
-
try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (
|
|
4146
|
+
try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
|
|
3862
4147
|
if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
|
|
3863
4148
|
if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
|
|
3864
4149
|
results.push(root);
|
|
@@ -4770,7 +5055,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
4770
5055
|
const isLast = i === entries.length - 1;
|
|
4771
5056
|
const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
|
|
4772
5057
|
let isDir = false;
|
|
4773
|
-
try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (
|
|
5058
|
+
try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
|
|
4774
5059
|
|
|
4775
5060
|
stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
|
|
4776
5061
|
|
|
@@ -4998,10 +5283,10 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
4998
5283
|
for (const s of ctx.shell.portTable.listServers()) {
|
|
4999
5284
|
if (s.pid !== undefined && String(s.pid) === String(pid)) {
|
|
5000
5285
|
if (s.server && typeof s.server.close === 'function') {
|
|
5001
|
-
try { s.server.close(); } catch (
|
|
5286
|
+
try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
|
|
5002
5287
|
}
|
|
5003
5288
|
if (typeof s.stop === 'function') {
|
|
5004
|
-
try { s.stop(); } catch (
|
|
5289
|
+
try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
|
|
5005
5290
|
}
|
|
5006
5291
|
ctx.shell.portTable.unregisterServer(s.port);
|
|
5007
5292
|
killedPort = true;
|