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