@innovatorved/code-lab 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/shell.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.10 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -3144,10 +3144,40 @@ var CodeLabLogger = (() => {
3144
3144
  return imports;
3145
3145
  }
3146
3146
 
3147
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3148
- const scripts = [];
3147
+ // Some templates pin a CDN URL in the source instead of importing a bare
3148
+ // specifier, e.g. `import React from "https://cdn.jsdelivr.net/npm/react@19.3.1/+esm"`.
3149
+ // Those URL specifiers are resolved by the browser directly, so they bypass the
3150
+ // generated import map (and with it the project's declared version and the
3151
+ // multi-CDN fallback). Import maps can remap URL specifiers, so alias each
3152
+ // literal URL found in the project to the resolved bare-specifier URL.
3153
+ // The pinned version is kept when the project has no dependency to resolve.
3154
+ const PINNED_CDN_URL_RE = /https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;
3155
+
3156
+ function aliasPinnedCdnUrls(vfs, rootDir, text, importMap) {
3157
+ if (!text || typeof text !== 'string') return;
3158
+ const re = new RegExp(PINNED_CDN_URL_RE.source, 'g');
3159
+ let match;
3160
+ while ((match = re.exec(text)) !== null) {
3161
+ const url = match[0];
3162
+ const pkgName = decodeURIComponent(match[1]);
3163
+ const rest = match[2];
3164
+ const pinnedVersion = rest.split(/[\/?]/)[0];
3165
+ const tail = rest.slice(pinnedVersion.length);
3166
+ const rawSubpath = tail.startsWith('/') && tail !== '/+esm' ? tail.slice(1).split(/[?#]/)[0] : '';
3167
+ const subpath = rawSubpath.replace(/^\/+|\/+$/g, '');
3168
+ const bare = subpath ? `${pkgName}/${subpath}` : pkgName;
3169
+
3170
+ const declared = resolveBareVersion(vfs, rootDir, pkgName);
3171
+ const version = declared && declared !== 'latest' ? declared : decodeURIComponent(pinnedVersion);
3172
+ const target = importMap[bare] || cdnEsmUrl(pkgName, version, subpath || undefined);
3173
+ if (target && target !== url) importMap[url] = target;
3174
+ }
3175
+ }
3176
+
3177
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
3178
+ const files = [];
3149
3179
  const walk = (dir, depth) => {
3150
- if (depth > 8 || scripts.length >= maxFiles) return;
3180
+ if (depth > 8 || files.length >= maxFiles) return;
3151
3181
  let entries = [];
3152
3182
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
3153
3183
  for (const name of entries) {
@@ -3158,13 +3188,23 @@ var CodeLabLogger = (() => {
3158
3188
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
3159
3189
  if (dirFlag) {
3160
3190
  walk(full, depth + 1);
3161
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
3162
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
3191
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
3192
+ try {
3193
+ const content = vfs.readFileSync(full, 'utf8');
3194
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
3195
+ files.push({ full, rel, content });
3196
+ } catch (err) {
3197
+ _shellLogger.debug('Preview script read skipped.', full, err);
3198
+ }
3163
3199
  }
3164
3200
  }
3165
3201
  };
3166
3202
  walk(rootDir, 0);
3167
- return scripts;
3203
+ return files;
3204
+ }
3205
+
3206
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3207
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
3168
3208
  }
3169
3209
 
3170
3210
  function injectPreviewExtras(html, importMap) {
@@ -3189,12 +3229,6 @@ var CodeLabLogger = (() => {
3189
3229
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
3190
3230
  while (taken.has(port)) port++;
3191
3231
 
3192
- const specifiers = new Set();
3193
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
3194
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
3195
- }
3196
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3197
-
3198
3232
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
3199
3233
  const isDir = (p) => {
3200
3234
  try {
@@ -3202,8 +3236,111 @@ var CodeLabLogger = (() => {
3202
3236
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
3203
3237
  } catch (_) { return false; }
3204
3238
  };
3239
+ const isFile = (p) => exists(p) && !isDir(p);
3205
3240
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3206
3241
 
3242
+ const resolveLocalTarget = (baseDir, rawSpec) => {
3243
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
3244
+ const clean = rawSpec.split(/[?#]/)[0].trim();
3245
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
3246
+ const candidateBase = clean.startsWith('/')
3247
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3248
+ : PosixPath.join(baseDir, clean);
3249
+ if (isFile(candidateBase)) return candidateBase;
3250
+ const cands = [
3251
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
3252
+ candidateBase + '.mjs', candidateBase + '.cjs',
3253
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
3254
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3255
+ ];
3256
+ for (const c of cands) {
3257
+ if (isFile(c)) return c;
3258
+ }
3259
+ return null;
3260
+ };
3261
+
3262
+ const toLocalImportKey = (fullPath) => {
3263
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
3264
+ return `@codelab-local/${rel}`;
3265
+ };
3266
+
3267
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
3268
+ let out = code;
3269
+ try {
3270
+ const rm = getRuntimeModule();
3271
+ if (rm && typeof rm.transpileForBrowser === 'function') {
3272
+ out = rm.transpileForBrowser(out, sourcePath);
3273
+ }
3274
+ } catch (err) {
3275
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
3276
+ }
3277
+ const fromDir = PosixPath.dirname(sourcePath);
3278
+ const rewriteSpec = (spec) => {
3279
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
3280
+ const resolved = resolveLocalTarget(fromDir, spec);
3281
+ return resolved ? toLocalImportKey(resolved) : spec;
3282
+ };
3283
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3284
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3285
+ return out;
3286
+ };
3287
+
3288
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
3289
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
3290
+ const specifiers = new Set();
3291
+ for (const f of scriptFiles) {
3292
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
3293
+ }
3294
+ // Also scan inline module scripts in HTML for bare specifiers
3295
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
3296
+ let inlineMatch;
3297
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
3298
+ if (inlineMatch[1]) {
3299
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
3300
+ }
3301
+ }
3302
+
3303
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3304
+ for (const f of scriptFiles) aliasPinnedCdnUrls(ctx.vfs, rootDir, f.content, importMap);
3305
+ aliasPinnedCdnUrls(ctx.vfs, rootDir, htmlBody, importMap);
3306
+ for (const f of scriptFiles) {
3307
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3308
+ const key = toLocalImportKey(f.full);
3309
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
3310
+ }
3311
+
3312
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
3313
+ let transformedHtml = htmlBody;
3314
+
3315
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
3316
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
3317
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
3318
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
3319
+ if (!hrefMatch) return fullTag;
3320
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
3321
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
3322
+ const cssContent = readText(cssTarget);
3323
+ if (cssContent === null) return fullTag;
3324
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
3325
+ });
3326
+
3327
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
3328
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
3329
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
3330
+ if (!srcMatch) return fullTag;
3331
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
3332
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3333
+ const rawScript = readText(scriptTarget);
3334
+ if (rawScript === null) return fullTag;
3335
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3336
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
3337
+ const typeAttr = isMod ? ' type="module"' : '';
3338
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
3339
+ });
3340
+
3341
+ return injectPreviewExtras(transformedHtml, importMap);
3342
+ };
3343
+
3207
3344
  const handler = async (request) => {
3208
3345
  let pathname = '/';
3209
3346
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -3238,7 +3375,7 @@ var CodeLabLogger = (() => {
3238
3375
  let body = readText(target);
3239
3376
  if (body === null) body = '';
3240
3377
  if (/\.html?$/i.test(target)) {
3241
- body = injectPreviewExtras(body, importMap);
3378
+ body = buildHtmlPreviewResponse(body, target);
3242
3379
  } else if (isPreviewScriptPath(target)) {
3243
3380
  try {
3244
3381
  const rm = getRuntimeModule();
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.10 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
package/dist/terminal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.10 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@innovatorved/code-lab",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "Standalone browser-native IDE Workbench, POSIX Shell & Coreutils, PTY Terminal, and Web Worker Node.js/Bun Virtual Runtime.",
5
5
  "main": "./dist/code-lab.js",
6
6
  "module": "./dist/code-lab.esm.js",