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