@innovatorved/code-lab 0.1.5 → 0.1.6

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.
@@ -829,9 +829,78 @@ function __initVirtualRuntime(rootScope) {
829
829
  crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
830
830
  }
831
831
  return (crc ^ 0xffffffff) >>> 0;
832
+ },
833
+ // The full Node zlib constant surface. Packages such as axios read these at
834
+ // module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
835
+ // actually compress, so a missing table breaks the whole module graph.
836
+ constants: {
837
+ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
838
+ Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
839
+ Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
840
+ Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
841
+ Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
842
+ Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
843
+ GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
844
+ BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
845
+ Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
846
+ Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
847
+ Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
832
848
  }
833
849
  };
834
850
 
851
+ // Compression: delegate to the host's real zlib when the runtime is embedded in
852
+ // Node (same process). In a pure browser worker there is no synchronous zlib, so
853
+ // the async APIs use CompressionStream/DecompressionStream and the *Sync variants
854
+ // throw a descriptive error instead of silently corrupting data.
855
+ (() => {
856
+ let hostZlib = null;
857
+ try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
858
+ const names = [
859
+ 'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
860
+ 'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
861
+ 'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
862
+ ];
863
+ if (hostZlib) {
864
+ for (const n of names) {
865
+ if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
866
+ }
867
+ return;
868
+ }
869
+ const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
870
+ const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
871
+ const p = (async () => {
872
+ if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
873
+ throw new Error('zlib.' + kind + ' is not supported in this environment');
874
+ }
875
+ const decompress = /^(gunzip|unzip|inflate)/.test(kind);
876
+ const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
877
+ const writer = stream.writable.getWriter();
878
+ const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
879
+ writer.write(input);
880
+ writer.close();
881
+ const ab = await new Response(stream.readable).arrayBuffer();
882
+ return VirtualBuffer.from(ab);
883
+ })();
884
+ if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
885
+ return p;
886
+ };
887
+ VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
888
+ VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
889
+ VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
890
+ VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
891
+ VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
892
+ VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
893
+ VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
894
+ const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
895
+ VirtualZlib.gzipSync = unsupported('gzipSync');
896
+ VirtualZlib.gunzipSync = unsupported('gunzipSync');
897
+ VirtualZlib.deflateSync = unsupported('deflateSync');
898
+ VirtualZlib.inflateSync = unsupported('inflateSync');
899
+ VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
900
+ VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
901
+ VirtualZlib.unzipSync = unsupported('unzipSync');
902
+ })();
903
+
835
904
  // =========================================================================
836
905
  // 4. PATH & OS SHIMS
837
906
  // =========================================================================
@@ -4870,7 +4939,13 @@ function __initVirtualRuntime(rootScope) {
4870
4939
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4871
4940
  });
4872
4941
  code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = (function(m){ return m && m.__esModule ? m.default : m; })(require($2));');
4873
- code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4942
+ // Dynamic `import("pkg")` — resolve through the CJS loader instead of the
4943
+ // host's dynamic import, which cannot see the virtual filesystem.
4944
+ code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
4945
+ // Side-effect import `import"pkg"` / `import "pkg"`. By this point the
4946
+ // specifier is literal-masked, and minified modules emit no whitespace
4947
+ // between `import` and the string, so `\s*` (not `\s+`) is required.
4948
+ code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4874
4949
 
4875
4950
  // Convert ES module exports
4876
4951
  const exportedNames = [];
@@ -5003,8 +5078,12 @@ function __initVirtualRuntime(rootScope) {
5003
5078
  const builtinSet = new Set([
5004
5079
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
5005
5080
  'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
5006
- 'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
5007
- 'stream', 'stream/promises', 'test', 'perf_hooks', 'timers', 'timers/promises', 'buffer',
5081
+ 'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
5082
+ 'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
5083
+ 'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
5084
+ 'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
5085
+ 'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
5086
+ 'wasi', 'console',
5008
5087
  'bun', 'bun:test', 'bun:sqlite'
5009
5088
  ]);
5010
5089
 
@@ -6914,6 +6993,285 @@ function __initVirtualRuntime(rootScope) {
6914
6993
  })();
6915
6994
 
6916
6995
  // Built-in Node module table
6996
+ // ── Additional Node builtin shims ────────────────────────────────────────
6997
+ // Widely-used packages require these at load time (e.g. `debug` requires
6998
+ // `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
6999
+ // whole app fails to start. Implementations are deliberately minimal but
7000
+ // shape-compatible; anything that genuinely cannot work in the sandbox
7001
+ // throws an explicit, descriptive error rather than silently misbehaving.
7002
+ const VirtualTty = {
7003
+ isatty() { return false; },
7004
+ ReadStream: class TtyReadStream extends EventEmitter {},
7005
+ WriteStream: class TtyWriteStream extends EventEmitter {
7006
+ constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
7007
+ getColorDepth() { return 1; }
7008
+ hasColors() { return false; }
7009
+ cursorTo() { return true; }
7010
+ clearLine() { return true; }
7011
+ moveCursor() { return true; }
7012
+ }
7013
+ };
7014
+
7015
+ function makeReadlineInterface() {
7016
+ const iface = new EventEmitter();
7017
+ iface.terminal = false;
7018
+ iface.line = '';
7019
+ iface.cursor = 0;
7020
+ iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
7021
+ iface.prompt = () => {};
7022
+ iface.setPrompt = () => {};
7023
+ iface.getPrompt = () => '';
7024
+ iface.write = () => {};
7025
+ iface.pause = () => iface;
7026
+ iface.resume = () => iface;
7027
+ iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
7028
+ iface[Symbol.asyncIterator] = async function* () {};
7029
+ return iface;
7030
+ }
7031
+ const VirtualReadline = {
7032
+ createInterface: makeReadlineInterface,
7033
+ Interface: class ReadlineInterface extends EventEmitter {},
7034
+ clearLine: () => true,
7035
+ clearScreenDown: () => true,
7036
+ cursorTo: () => true,
7037
+ moveCursor: () => true,
7038
+ emitKeypressEvents: () => {}
7039
+ };
7040
+ const VirtualReadlinePromises = {
7041
+ createInterface: () => {
7042
+ const iface = makeReadlineInterface();
7043
+ iface.question = () => Promise.resolve('');
7044
+ return iface;
7045
+ },
7046
+ Interface: class ReadlinePromisesInterface extends EventEmitter {}
7047
+ };
7048
+
7049
+ const VirtualAsyncHooks = {
7050
+ AsyncLocalStorage: class AsyncLocalStorage {
7051
+ constructor() { this._store = undefined; }
7052
+ getStore() { return this._store; }
7053
+ run(store, fn, ...args) {
7054
+ const prev = this._store;
7055
+ this._store = store;
7056
+ try { return fn(...args); } finally { this._store = prev; }
7057
+ }
7058
+ exit(fn, ...args) {
7059
+ const prev = this._store;
7060
+ this._store = undefined;
7061
+ try { return fn(...args); } finally { this._store = prev; }
7062
+ }
7063
+ enterWith(store) { this._store = store; }
7064
+ disable() { this._store = undefined; }
7065
+ },
7066
+ AsyncResource: class AsyncResource {
7067
+ constructor(type) { this.type = type || 'AsyncResource'; }
7068
+ runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
7069
+ emitDestroy() { return this; }
7070
+ asyncId() { return 0; }
7071
+ triggerAsyncId() { return 0; }
7072
+ static bind(fn) { return fn; }
7073
+ },
7074
+ createHook() { return { enable() {}, disable() {} }; },
7075
+ executionAsyncId() { return 0; },
7076
+ triggerAsyncId() { return 0; },
7077
+ executionAsyncResource() { return null; }
7078
+ };
7079
+
7080
+ const VirtualWorkerThreads = {
7081
+ isMainThread: true,
7082
+ threadId: 0,
7083
+ parentPort: null,
7084
+ workerData: null,
7085
+ resourceLimits: {},
7086
+ SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
7087
+ receiveMessageOnPort() { return undefined; },
7088
+ Worker: class Worker extends EventEmitter {
7089
+ constructor(filename) {
7090
+ super();
7091
+ this.threadId = -1;
7092
+ this.filename = filename;
7093
+ queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
7094
+ }
7095
+ postMessage() {}
7096
+ terminate() { return Promise.resolve(0); }
7097
+ ref() { return this; }
7098
+ unref() { return this; }
7099
+ },
7100
+ MessageChannel: class MessageChannel {},
7101
+ MessagePort: class MessagePort extends EventEmitter {}
7102
+ };
7103
+
7104
+ const VirtualV8 = {
7105
+ serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
7106
+ deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
7107
+ getHeapStatistics() {
7108
+ return {
7109
+ total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
7110
+ total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
7111
+ malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
7112
+ number_of_native_contexts: 1, number_of_detached_contexts: 0
7113
+ };
7114
+ },
7115
+ getHeapSpaceStatistics() { return []; },
7116
+ setFlagsFromString() {},
7117
+ cachedDataVersionTag() { return 0; },
7118
+ Serializer: class Serializer {
7119
+ constructor() { this._value = undefined; }
7120
+ writeHeader() {}
7121
+ writeValue(value) { this._value = value; }
7122
+ releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
7123
+ },
7124
+ Deserializer: class Deserializer {
7125
+ constructor(buffer) { this._buffer = buffer; }
7126
+ readHeader() { return true; }
7127
+ readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
7128
+ }
7129
+ };
7130
+
7131
+ const VirtualVm = {
7132
+ createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
7133
+ isContext() { return false; },
7134
+ createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
7135
+ runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
7136
+ runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
7137
+ runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
7138
+ compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
7139
+ Script: class Script {
7140
+ runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7141
+ runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7142
+ runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7143
+ }
7144
+ };
7145
+
7146
+ const VirtualDomain = {
7147
+ create() {
7148
+ const d = new EventEmitter();
7149
+ d.members = [];
7150
+ d.add = () => d;
7151
+ d.remove = () => d;
7152
+ d.bind = (fn) => fn;
7153
+ d.intercept = (fn) => fn;
7154
+ d.run = (fn, ...args) => fn(...args);
7155
+ d.dispose = () => d;
7156
+ return d;
7157
+ },
7158
+ createDomain() { return VirtualDomain.create(); }
7159
+ };
7160
+
7161
+ const VirtualDiagnosticsChannel = {
7162
+ _channels: new Map(),
7163
+ channel(name) {
7164
+ const key = String(name);
7165
+ if (!VirtualDiagnosticsChannel._channels.has(key)) {
7166
+ const ch = new EventEmitter();
7167
+ ch.name = key;
7168
+ ch.hasSubscribers = false;
7169
+ ch.subscribe = () => { ch.hasSubscribers = true; };
7170
+ ch.unsubscribe = () => { ch.hasSubscribers = false; };
7171
+ VirtualDiagnosticsChannel._channels.set(key, ch);
7172
+ }
7173
+ return VirtualDiagnosticsChannel._channels.get(key);
7174
+ },
7175
+ subscribe(name, cb) {
7176
+ const ch = VirtualDiagnosticsChannel.channel(name);
7177
+ ch.subscribe();
7178
+ if (typeof cb === 'function') ch.on('message', cb);
7179
+ },
7180
+ unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
7181
+ Channel: class Channel extends EventEmitter {}
7182
+ };
7183
+
7184
+ const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
7185
+ const VirtualTls = {
7186
+ DEFAULT_MIN_VERSION: 'TLSv1.2',
7187
+ DEFAULT_MAX_VERSION: 'TLSv1.3',
7188
+ rootCertificates: [],
7189
+ createSecureContext() { return { context: {} }; },
7190
+ SecureContext: class SecureContext {},
7191
+ TLSSocket: class TLSSocket extends EventEmitter {},
7192
+ Server: class TLSServer extends EventEmitter {},
7193
+ checkServerIdentity() { return undefined; },
7194
+ connect: notSupported('tls.connect'),
7195
+ createServer: notSupported('tls.createServer')
7196
+ };
7197
+ const VirtualDgram = {
7198
+ createSocket(type) {
7199
+ const sock = new EventEmitter();
7200
+ sock.type = type || 'udp4';
7201
+ sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
7202
+ sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
7203
+ sock.send = notSupported('dgram.send');
7204
+ sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
7205
+ sock.setBroadcast = () => sock;
7206
+ sock.setTTL = () => sock;
7207
+ sock.addMembership = () => {};
7208
+ sock.dropMembership = () => {};
7209
+ return sock;
7210
+ },
7211
+ Socket: class Socket extends EventEmitter {}
7212
+ };
7213
+ const VirtualHttp2 = {
7214
+ constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
7215
+ connect: notSupported('http2.connect'),
7216
+ createServer: notSupported('http2.createServer'),
7217
+ createSecureServer: notSupported('http2.createSecureServer')
7218
+ };
7219
+ const VirtualCluster = {
7220
+ isPrimary: true,
7221
+ isMaster: true,
7222
+ isWorker: false,
7223
+ workers: {},
7224
+ fork: notSupported('cluster.fork'),
7225
+ setupPrimary: notSupported('cluster.setupPrimary'),
7226
+ setupMaster: notSupported('cluster.setupMaster'),
7227
+ disconnect: () => {}
7228
+ };
7229
+ const VirtualRepl = { start: notSupported('repl.start') };
7230
+ const VirtualInspector = {
7231
+ open: () => null,
7232
+ close: () => {},
7233
+ url: () => '',
7234
+ Session: class Session { connect() {} disconnect() {} post() {} }
7235
+ };
7236
+ const VirtualTraceEvents = {
7237
+ createTracing: () => ({ enable() {}, disable() {} }),
7238
+ getEnabledCategories: () => ''
7239
+ };
7240
+ const VirtualWasi = {
7241
+ WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
7242
+ };
7243
+
7244
+ const VirtualStreamWeb = {
7245
+ ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
7246
+ WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
7247
+ TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
7248
+ };
7249
+ async function consumeStream(kind, stream) {
7250
+ const chunks = [];
7251
+ if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
7252
+ for await (const chunk of stream) chunks.push(chunk);
7253
+ } else if (stream && typeof stream.on === 'function') {
7254
+ await new Promise((resolve, reject) => {
7255
+ stream.on('data', (c) => chunks.push(c));
7256
+ stream.on('end', resolve);
7257
+ stream.on('error', reject);
7258
+ });
7259
+ }
7260
+ const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
7261
+ const buf = VirtualBuffer.concat(bufs);
7262
+ if (kind === 'buffer') return buf;
7263
+ if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
7264
+ if (kind === 'text') return buf.toString('utf8');
7265
+ if (kind === 'json') return JSON.parse(buf.toString('utf8'));
7266
+ return buf;
7267
+ }
7268
+ const VirtualStreamConsumers = {
7269
+ text: (s) => consumeStream('text', s),
7270
+ json: (s) => consumeStream('json', s),
7271
+ buffer: (s) => consumeStream('buffer', s),
7272
+ arrayBuffer: (s) => consumeStream('arrayBuffer', s)
7273
+ };
7274
+
6917
7275
  const builtinModules = {
6918
7276
  fs: vfs,
6919
7277
  'node:fs': vfs,
@@ -6974,8 +7332,58 @@ function __initVirtualRuntime(rootScope) {
6974
7332
  bun: BunObj,
6975
7333
  'node:bun': BunObj,
6976
7334
  'bun:test': bunTestModule,
6977
- 'bun:sqlite': { Database: SqliteDatabase }
7335
+ 'bun:sqlite': { Database: SqliteDatabase },
7336
+ tty: VirtualTty,
7337
+ tls: VirtualTls,
7338
+ dgram: VirtualDgram,
7339
+ readline: VirtualReadline,
7340
+ 'readline/promises': VirtualReadlinePromises,
7341
+ async_hooks: VirtualAsyncHooks,
7342
+ worker_threads: VirtualWorkerThreads,
7343
+ v8: VirtualV8,
7344
+ vm: VirtualVm,
7345
+ domain: VirtualDomain,
7346
+ diagnostics_channel: VirtualDiagnosticsChannel,
7347
+ http2: VirtualHttp2,
7348
+ cluster: VirtualCluster,
7349
+ repl: VirtualRepl,
7350
+ inspector: VirtualInspector,
7351
+ trace_events: VirtualTraceEvents,
7352
+ wasi: VirtualWasi,
7353
+ constants: vfs.constants,
7354
+ 'util/types': VirtualUtil.types,
7355
+ 'stream/web': VirtualStreamWeb,
7356
+ 'stream/consumers': VirtualStreamConsumers
7357
+ };
7358
+
7359
+ // Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
7360
+ // so both spellings resolve identically without hand-maintaining two lists.
7361
+ for (const __builtinName of Object.keys(builtinModules)) {
7362
+ if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
7363
+ builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
7364
+ }
7365
+ }
7366
+
7367
+ // `module` must reference the now-complete builtin table, so it is attached
7368
+ // after the object literal above.
7369
+ const VirtualModule = {
7370
+ builtinModules: Object.keys(builtinModules),
7371
+ Module: class Module {},
7372
+ isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
7373
+ createRequire(from) {
7374
+ const base = typeof from === 'string' ? from : '/workspace';
7375
+ const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
7376
+ const req = (id) => {
7377
+ if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
7378
+ return loadModule(resolveModulePath(id, dir), false);
7379
+ };
7380
+ req.resolve = (id) => resolveModulePath(id, dir);
7381
+ req.cache = {};
7382
+ return req;
7383
+ }
6978
7384
  };
7385
+ builtinModules.module = VirtualModule;
7386
+ builtinModules['node:module'] = VirtualModule;
6979
7387
 
6980
7388
  const moduleCache = new Map();
6981
7389
  let mainModule = null;
@@ -10219,6 +10627,15 @@ if (typeof module !== 'undefined' && module.exports) {
10219
10627
 
10220
10628
  function pickConditionalEntry(value) {
10221
10629
  if (typeof value === 'string') return value;
10630
+ // `exports` subpaths may be an array of fallbacks, e.g.
10631
+ // `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
10632
+ if (Array.isArray(value)) {
10633
+ for (const item of value) {
10634
+ const picked = pickConditionalEntry(item);
10635
+ if (picked) return picked;
10636
+ }
10637
+ return null;
10638
+ }
10222
10639
  if (!value || typeof value !== 'object') return null;
10223
10640
  // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
10224
10641
  for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
@@ -10275,17 +10692,50 @@ if (typeof module !== 'undefined' && module.exports) {
10275
10692
  return parts.join('/');
10276
10693
  }
10277
10694
 
10695
+ // Small promise-based delay. Used only for CDN retry backoff; falls back to an
10696
+ // immediate resolve if `setTimeout` is unavailable in the host.
10697
+ function cdnBackoff(ms) {
10698
+ return new Promise((resolve) => {
10699
+ if (typeof setTimeout === 'function') setTimeout(resolve, ms);
10700
+ else resolve();
10701
+ });
10702
+ }
10703
+
10278
10704
  async function fetchTextFromCdn(fetchImpl, url) {
10279
- try {
10280
- const res = await fetchImpl(url);
10281
- if (!res) return null;
10282
- const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
10283
- if (!ok) return null;
10284
- if (typeof res.text === 'function') return await res.text();
10285
- return String(res.body != null ? res.body : '');
10286
- } catch (_) {
10287
- return null;
10705
+ // A single flaky jsDelivr response used to silently produce an *incomplete*
10706
+ // install (the module graph then failed at require-time). Retry transient
10707
+ // failures (network error, 429/408, 5xx) but treat 4xx as final.
10708
+ const maxAttempts = 3;
10709
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
10710
+ try {
10711
+ const res = await fetchImpl(url);
10712
+ if (!res) {
10713
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
10714
+ return null;
10715
+ }
10716
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
10717
+ if (!ok) {
10718
+ const transient = res.status >= 500 || res.status === 429 || res.status === 408;
10719
+ if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
10720
+ return null;
10721
+ }
10722
+ // jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
10723
+ // and an HTML directory listing. Storing that as a module both corrupts the
10724
+ // package and later collides with the real directory (EISDIR).
10725
+ const contentType = (res.headers && typeof res.headers.get === 'function')
10726
+ ? (res.headers.get('content-type') || '')
10727
+ : '';
10728
+ const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
10729
+ if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
10730
+ const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
10731
+ if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
10732
+ return text;
10733
+ } catch (_) {
10734
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
10735
+ return null;
10736
+ }
10288
10737
  }
10738
+ return null;
10289
10739
  }
10290
10740
 
10291
10741
  async function resolvePackageMetadata(fetchImpl, name, range) {
@@ -10328,14 +10778,25 @@ if (typeof module !== 'undefined' && module.exports) {
10328
10778
  const visited = new Set();
10329
10779
  // Seed with the package entry plus any declared `exports` subpaths, so a
10330
10780
  // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
10331
- const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
10781
+ // A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
10782
+ // resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
10783
+ // too or the package installs with only its manifest.
10784
+ const seed = [
10785
+ entry,
10786
+ `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
10787
+ `${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
10788
+ ];
10332
10789
  const expMap = meta.exports;
10333
10790
  if (expMap && typeof expMap === 'object') {
10334
- let subCount = 0;
10791
+ // Seed *every* declared subpath. A low cap silently dropped the tail of
10792
+ // packages that list each file in `exports` (lit-html has 29 keys, so
10793
+ // `lit-html/is-server.js` was never fetched and `require` failed later).
10794
+ // Wildcard keys (`./*`) need no seeding — their files are reached through
10795
+ // the relative-require closure or fetched on demand.
10335
10796
  for (const key of Object.keys(expMap)) {
10336
- if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
10797
+ if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
10337
10798
  const target = pickConditionalEntry(expMap[key]);
10338
- if (target) { seed.push(target); subCount++; }
10799
+ if (target) seed.push(target);
10339
10800
  }
10340
10801
  }
10341
10802
  let frontier = seed;
@@ -10343,7 +10804,9 @@ if (typeof module !== 'undefined' && module.exports) {
10343
10804
  const batch = [];
10344
10805
  for (const raw of frontier) {
10345
10806
  const rel = stripRelPath(raw);
10346
- if (!rel || visited.has(rel)) continue;
10807
+ // Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
10808
+ // be fetched as files — that is what produced the EISDIR crash.
10809
+ if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
10347
10810
  visited.add(rel);
10348
10811
  batch.push(rel);
10349
10812
  }
@@ -10379,15 +10842,29 @@ if (typeof module !== 'undefined' && module.exports) {
10379
10842
  }
10380
10843
 
10381
10844
  // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
10382
- // so e.g. `npm install react-dom` also pulls in `react`.
10383
- const depNames = Object.keys(meta.dependencies || {});
10845
+ // so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
10846
+ // preserved (not just the names) so transitives resolve to the version the
10847
+ // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
10848
+ // needs color-convert. Resolving transitive names as "latest" silently breaks
10849
+ // the tree (ansi-styles@6 has no deps at all).
10850
+ const depSpecs = [];
10851
+ const depSeen = new Set();
10852
+ const declared = meta.dependencies || {};
10853
+ for (const depName of Object.keys(declared)) {
10854
+ if (depSeen.has(depName)) continue;
10855
+ depSeen.add(depName);
10856
+ depSpecs.push({ name: depName, range: declared[depName] || null });
10857
+ }
10384
10858
  const peerMeta = meta.peerDependenciesMeta || {};
10385
- for (const peer of Object.keys(meta.peerDependencies || {})) {
10859
+ const peers = meta.peerDependencies || {};
10860
+ for (const peer of Object.keys(peers)) {
10386
10861
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
10387
- if (depNames.indexOf(peer) === -1) depNames.push(peer);
10862
+ if (depSeen.has(peer)) continue;
10863
+ depSeen.add(peer);
10864
+ depSpecs.push({ name: peer, range: peers[peer] || null });
10388
10865
  }
10389
10866
 
10390
- return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
10867
+ return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
10391
10868
  }
10392
10869
 
10393
10870
  function installTargetDirs(ctx, name) {
@@ -10401,7 +10878,13 @@ if (typeof module !== 'undefined' && module.exports) {
10401
10878
  for (const dir of dirs) {
10402
10879
  ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10403
10880
  for (const f of info.files) {
10881
+ if (!f || !f.rel || f.rel.endsWith('/')) continue;
10404
10882
  const full = PosixPath.join(dir, f.rel);
10883
+ // Never overwrite a directory with a file body (defensive: a stray
10884
+ // directory target would otherwise raise EISDIR).
10885
+ try {
10886
+ if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10887
+ } catch (_) {}
10405
10888
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10406
10889
  ctx.vfs.writeFileSync(full, f.content);
10407
10890
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10467,10 +10950,11 @@ if (typeof module !== 'undefined' && module.exports) {
10467
10950
  if (item.direct) directVersion = info.version || null;
10468
10951
 
10469
10952
  for (const dep of (info.deps || [])) {
10470
- const parsed = parsePackageSpec(dep);
10471
- if (parsed.name && !requested.has(parsed.name)) {
10472
- requested.add(parsed.name);
10473
- queue.push({ name: parsed.name, range: null, direct: false });
10953
+ const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
10954
+ const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
10955
+ if (depName && !requested.has(depName)) {
10956
+ requested.add(depName);
10957
+ queue.push({ name: depName, range: depRange || null, direct: false });
10474
10958
  }
10475
10959
  }
10476
10960
  }
@@ -10827,21 +11311,29 @@ if (typeof module !== 'undefined' && module.exports) {
10827
11311
  // Common dev-server commands that cannot run inside the virtual runtime are
10828
11312
  // transparently redirected to the built-in preview server.
10829
11313
  const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
11314
+ // The same tools, when typed directly at the prompt (`ng serve`, `vite`).
11315
+ // `serve` is omitted: it is a first-class builtin shell command.
11316
+ const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
10830
11317
 
10831
- function tryDevScriptFallback(scriptName, cmd, ctx) {
11318
+ function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
10832
11319
  if (!PREVIEW_TOOL_RE.test(cmd)) return null;
10833
11320
  // Only fall back when the referenced tool is not actually installed.
10834
11321
  const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
11322
+ const force = Boolean(opts && opts.force);
10835
11323
  const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
10836
- if (ctx.vfs.existsSync(binPath)) return null;
11324
+ if (!force && ctx.vfs.existsSync(binPath)) return null;
10837
11325
  const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
10838
11326
  const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
10839
11327
  const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
10840
- const entry = registerPreviewServer(ctx, ctx.cwd, port);
11328
+ const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
11329
+ const entry = registerPreviewServer(ctx, rootDir, port);
10841
11330
  if (!entry) return null;
11331
+ const note = force
11332
+ ? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
11333
+ : `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
10842
11334
  return {
10843
11335
  code: 0,
10844
- stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${bin} is not available in this virtual runtime — using the CodeLab preview server instead.\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
11336
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
10845
11337
  stderr: ''
10846
11338
  };
10847
11339
  }
@@ -14940,6 +15432,13 @@ if (typeof module !== 'undefined' && module.exports) {
14940
15432
  Object.assign(context.env, this.env);
14941
15433
  context.cwd = this.cwd;
14942
15434
  }
15435
+ } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
15436
+ // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
15437
+ // this runtime — whether or not it was installed — so route it to the
15438
+ // built-in preview server rather than reporting a misleading "command
15439
+ // not found".
15440
+ const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
15441
+ res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
14943
15442
  } else if (typeof this.options.onProcessSpawn === 'function') {
14944
15443
  const spawned = await this.options.onProcessSpawn(cmdName, args, {
14945
15444
  cwd: this.cwd,
@@ -23434,6 +23933,7 @@ const executeInWorker = CodeLabRuntime.executeInWorker;
23434
23933
  const cancelWorkerExecution = CodeLabRuntime.cancelWorkerExecution;
23435
23934
  const preloadNpmPackages = CodeLabRuntime.preloadNpmPackages;
23436
23935
  const transpileTS = CodeLabRuntime.transpileTS;
23936
+ const transpileForBrowser = CodeLabRuntime.transpileForBrowser;
23437
23937
  const createVirtualFs = CodeLabRuntime.createVirtualFs;
23438
23938
  const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
23439
23939
  const createVirtualNet = CodeLabRuntime.createVirtualNet;
@@ -23448,7 +23948,11 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
23448
23948
  const mount = CodeLab ? CodeLab.mount : null;
23449
23949
  const create = CodeLab ? CodeLab.create : null;
23450
23950
  const unmount = CodeLab ? CodeLab.unmount : null;
23451
- const version = CodeLab ? CodeLab.version : '1.4.0';
23951
+ const version = CodeLab ? CodeLab.version : '2.0.0';
23952
+ const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
23953
+ const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
23954
+ const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
23955
+ const extensions = CodeLab ? CodeLab.extensions : null;
23452
23956
 
23453
23957
  export {
23454
23958
  CodeLab,
@@ -23465,6 +23969,10 @@ export {
23465
23969
  create,
23466
23970
  unmount,
23467
23971
  version,
23972
+ renderMarkdown,
23973
+ renderSimpleMarkdown,
23974
+ cloneRepo,
23975
+ extensions,
23468
23976
  createPosixShell,
23469
23977
  cloneGitHubRepository,
23470
23978
  parseGitHubRepoUrl,
@@ -23476,6 +23984,7 @@ export {
23476
23984
  cancelWorkerExecution,
23477
23985
  preloadNpmPackages,
23478
23986
  transpileTS,
23987
+ transpileForBrowser,
23479
23988
  createVirtualFs,
23480
23989
  createVirtualHttp,
23481
23990
  createVirtualNet,