@innovatorved/code-lab 0.1.4 → 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/src/runtime.js CHANGED
@@ -809,9 +809,78 @@ function __initVirtualRuntime(rootScope) {
809
809
  crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
810
810
  }
811
811
  return (crc ^ 0xffffffff) >>> 0;
812
+ },
813
+ // The full Node zlib constant surface. Packages such as axios read these at
814
+ // module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
815
+ // actually compress, so a missing table breaks the whole module graph.
816
+ constants: {
817
+ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
818
+ Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
819
+ Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
820
+ Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
821
+ Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
822
+ Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
823
+ GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
824
+ BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
825
+ Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
826
+ Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
827
+ Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
812
828
  }
813
829
  };
814
830
 
831
+ // Compression: delegate to the host's real zlib when the runtime is embedded in
832
+ // Node (same process). In a pure browser worker there is no synchronous zlib, so
833
+ // the async APIs use CompressionStream/DecompressionStream and the *Sync variants
834
+ // throw a descriptive error instead of silently corrupting data.
835
+ (() => {
836
+ let hostZlib = null;
837
+ try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
838
+ const names = [
839
+ 'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
840
+ 'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
841
+ 'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
842
+ ];
843
+ if (hostZlib) {
844
+ for (const n of names) {
845
+ if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
846
+ }
847
+ return;
848
+ }
849
+ const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
850
+ const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
851
+ const p = (async () => {
852
+ if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
853
+ throw new Error('zlib.' + kind + ' is not supported in this environment');
854
+ }
855
+ const decompress = /^(gunzip|unzip|inflate)/.test(kind);
856
+ const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
857
+ const writer = stream.writable.getWriter();
858
+ const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
859
+ writer.write(input);
860
+ writer.close();
861
+ const ab = await new Response(stream.readable).arrayBuffer();
862
+ return VirtualBuffer.from(ab);
863
+ })();
864
+ if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
865
+ return p;
866
+ };
867
+ VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
868
+ VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
869
+ VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
870
+ VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
871
+ VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
872
+ VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
873
+ VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
874
+ const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
875
+ VirtualZlib.gzipSync = unsupported('gzipSync');
876
+ VirtualZlib.gunzipSync = unsupported('gunzipSync');
877
+ VirtualZlib.deflateSync = unsupported('deflateSync');
878
+ VirtualZlib.inflateSync = unsupported('inflateSync');
879
+ VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
880
+ VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
881
+ VirtualZlib.unzipSync = unsupported('unzipSync');
882
+ })();
883
+
815
884
  // =========================================================================
816
885
  // 4. PATH & OS SHIMS
817
886
  // =========================================================================
@@ -3954,14 +4023,316 @@ function __initVirtualRuntime(rootScope) {
3954
4023
  };
3955
4024
  }
3956
4025
 
4026
+ // =========================================================================
4027
+ // 7b. JSX / TSX SUPPORT
4028
+ // -------------------------------------------------------------------------
4029
+ // Rewrites JSX syntax into classic `createElement(...)` calls. This runs
4030
+ // BEFORE the string-masking pass so that JSX text (which routinely contains
4031
+ // quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
4032
+ // JS strings, comments and template literals are skipped untouched.
4033
+ // =========================================================================
4034
+ function detectJsxSyntax(source, filename) {
4035
+ if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
4036
+ if (!source || source.indexOf('<') === -1) return false;
4037
+ if (/@jsx\b/.test(source)) return true;
4038
+ if (source.indexOf('<>') !== -1) return true;
4039
+ if (/<\/[A-Za-z]/.test(source)) return true;
4040
+ return false;
4041
+ }
4042
+
4043
+ function readJsxPragma(source) {
4044
+ let pragma = 'React.createElement';
4045
+ let frag = null;
4046
+ const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
4047
+ if (m) pragma = m[1];
4048
+ const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
4049
+ if (fm) frag = fm[1];
4050
+ if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
4051
+ return { pragma, frag };
4052
+ }
4053
+
4054
+ const JSX_WS_RE = /\s/;
4055
+ const JSX_NAME_START_RE = /[A-Za-z_$]/;
4056
+ const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
4057
+
4058
+ function jsxThrow(message) {
4059
+ const err = new Error(message);
4060
+ err.jsxParse = true;
4061
+ throw err;
4062
+ }
4063
+
4064
+ // Returns the exclusive end index if a JS string / template / comment starts
4065
+ // at `i`, otherwise -1. Regexes are deliberately ignored.
4066
+ function jsxSkipJsLiteral(source, i) {
4067
+ const ch = source[i];
4068
+ const next = source[i + 1];
4069
+ const len = source.length;
4070
+ if (ch === '/' && next === '/') {
4071
+ const e = source.indexOf('\n', i);
4072
+ return e === -1 ? len : e;
4073
+ }
4074
+ if (ch === '/' && next === '*') {
4075
+ const e = source.indexOf('*/', i + 2);
4076
+ return e === -1 ? len : e + 2;
4077
+ }
4078
+ if (ch === '"' || ch === "'") {
4079
+ let j = i + 1;
4080
+ while (j < len) {
4081
+ const c = source[j];
4082
+ if (c === '\\') { j += 2; continue; }
4083
+ if (c === ch) { j++; break; }
4084
+ if (c === '\n') break;
4085
+ j++;
4086
+ }
4087
+ return j;
4088
+ }
4089
+ if (ch === '`') {
4090
+ let j = i + 1;
4091
+ let depth = 0;
4092
+ while (j < len) {
4093
+ const c = source[j];
4094
+ if (c === '\\') { j += 2; continue; }
4095
+ if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4096
+ if (c === '}' && depth > 0) { depth--; j++; continue; }
4097
+ if (c === '`' && depth === 0) { j++; break; }
4098
+ j++;
4099
+ }
4100
+ return j;
4101
+ }
4102
+ return -1;
4103
+ }
4104
+
4105
+ function jsxReadName(source, i) {
4106
+ if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
4107
+ let j = i;
4108
+ while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
4109
+ return { name: source.slice(i, j), next: j };
4110
+ }
4111
+
4112
+ function jsxSkipWs(source, i) {
4113
+ while (i < source.length && JSX_WS_RE.test(source[i])) i++;
4114
+ return i;
4115
+ }
4116
+
4117
+ function normalizeJsxText(raw) {
4118
+ if (!raw) return '';
4119
+ let t = raw.replace(/\r/g, '');
4120
+ if (t.indexOf('\n') !== -1) {
4121
+ t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
4122
+ } else if (!/\S/.test(t)) {
4123
+ return '';
4124
+ } else {
4125
+ t = t.replace(/[ \t]+/g, ' ');
4126
+ }
4127
+ return t ? JSON.stringify(t) : '';
4128
+ }
4129
+
4130
+ // Reads a balanced `{ ... }` expression container, skipping nested JSX and
4131
+ // JS literals. Returns the raw inner source (later re-transformed) plus the
4132
+ // index just past the closing brace.
4133
+ function jsxReadBraced(source, i, opts) {
4134
+ let depth = 0;
4135
+ let j = i;
4136
+ while (j < source.length) {
4137
+ const lit = jsxSkipJsLiteral(source, j);
4138
+ if (lit !== -1) { j = lit; continue; }
4139
+ const c = source[j];
4140
+ if (c === '{') { depth++; j++; continue; }
4141
+ if (c === '}') {
4142
+ depth--;
4143
+ j++;
4144
+ if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
4145
+ continue;
4146
+ }
4147
+ if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
4148
+ try {
4149
+ const el = jsxParseElement(source, j, opts);
4150
+ j = el.next;
4151
+ continue;
4152
+ } catch (e) {
4153
+ if (!e || !e.jsxParse) throw e;
4154
+ }
4155
+ }
4156
+ j++;
4157
+ }
4158
+ jsxThrow('jsx: unterminated expression container');
4159
+ }
4160
+
4161
+ function jsxParseElement(source, i, opts) {
4162
+ const o = opts || readJsxPragma(source);
4163
+ let j = i + 1;
4164
+ let isFragment = false;
4165
+ let typeExpr;
4166
+ if (source[j] === '>') {
4167
+ isFragment = true;
4168
+ typeExpr = o.frag;
4169
+ j++;
4170
+ } else {
4171
+ const nm = jsxReadName(source, j);
4172
+ j = nm.next;
4173
+ const raw = nm.name;
4174
+ const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
4175
+ if (isReference) {
4176
+ typeExpr = raw.replace(/:/g, '.');
4177
+ } else {
4178
+ typeExpr = JSON.stringify(raw);
4179
+ }
4180
+ }
4181
+
4182
+ const props = [];
4183
+ let selfClosing = false;
4184
+ if (!isFragment) {
4185
+ for (;;) {
4186
+ j = jsxSkipWs(source, j);
4187
+ if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
4188
+ const c = source[j];
4189
+ if (c === '/') {
4190
+ if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
4191
+ j += 2;
4192
+ selfClosing = true;
4193
+ break;
4194
+ }
4195
+ if (c === '>') { j++; break; }
4196
+ if (c === '{') {
4197
+ const br = jsxReadBraced(source, j, o);
4198
+ const inner = br.inner.trim();
4199
+ if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
4200
+ props.push({ spread: jsxTransform(inner.slice(3), o) });
4201
+ j = br.next;
4202
+ continue;
4203
+ }
4204
+ if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
4205
+ const am = jsxReadName(source, j);
4206
+ const attrName = am.name;
4207
+ j = jsxSkipWs(source, am.next);
4208
+ let valueExpr = 'true';
4209
+ if (source[j] === '=') {
4210
+ j = jsxSkipWs(source, j + 1);
4211
+ const vc = source[j];
4212
+ if (vc === '"' || vc === "'") {
4213
+ let k = j + 1;
4214
+ while (k < source.length && source[k] !== vc) {
4215
+ if (source[k] === '\\') k++;
4216
+ k++;
4217
+ }
4218
+ if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
4219
+ valueExpr = JSON.stringify(source.slice(j + 1, k));
4220
+ j = k + 1;
4221
+ } else if (vc === '{') {
4222
+ const br = jsxReadBraced(source, j, o);
4223
+ valueExpr = jsxTransform(br.inner, o) || 'undefined';
4224
+ j = br.next;
4225
+ } else if (vc === '<') {
4226
+ const el = jsxParseElement(source, j, o);
4227
+ valueExpr = el.code;
4228
+ j = el.next;
4229
+ } else {
4230
+ jsxThrow('jsx: unsupported attribute value');
4231
+ }
4232
+ }
4233
+ const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
4234
+ props.push({ key: propKey, value: valueExpr });
4235
+ }
4236
+ }
4237
+
4238
+ const children = [];
4239
+ if (!selfClosing) {
4240
+ for (;;) {
4241
+ if (j >= source.length) jsxThrow('jsx: missing closing tag');
4242
+ const c = source[j];
4243
+ if (c === '<' && source[j + 1] === '/') {
4244
+ j = jsxSkipWs(source, j + 2);
4245
+ if (source[j] === '>') { j++; break; }
4246
+ const cm = jsxReadName(source, j);
4247
+ j = jsxSkipWs(source, cm.next);
4248
+ if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
4249
+ j++;
4250
+ break;
4251
+ }
4252
+ if (c === '<') {
4253
+ const el = jsxParseElement(source, j, o);
4254
+ children.push(el.code);
4255
+ j = el.next;
4256
+ continue;
4257
+ }
4258
+ if (c === '{') {
4259
+ const br = jsxReadBraced(source, j, o);
4260
+ const inner = jsxTransform(br.inner, o);
4261
+ if (inner && inner.trim()) children.push(inner);
4262
+ j = br.next;
4263
+ continue;
4264
+ }
4265
+ let k = j;
4266
+ while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
4267
+ const text = normalizeJsxText(source.slice(j, k));
4268
+ if (text) children.push(text);
4269
+ j = k;
4270
+ }
4271
+ }
4272
+
4273
+ let propsCode = 'null';
4274
+ if (props.length) {
4275
+ const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
4276
+ propsCode = '{ ' + parts.join(', ') + ' }';
4277
+ }
4278
+
4279
+ const args = [typeExpr, propsCode].concat(children);
4280
+ return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
4281
+ }
4282
+
4283
+ function jsxTransform(source, opts) {
4284
+ const o = opts || readJsxPragma(source);
4285
+ let i = 0;
4286
+ let out = '';
4287
+ while (i < source.length) {
4288
+ const lit = jsxSkipJsLiteral(source, i);
4289
+ if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
4290
+ const ch = source[i];
4291
+ if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
4292
+ try {
4293
+ const el = jsxParseElement(source, i, o);
4294
+ out += el.code;
4295
+ i = el.next;
4296
+ continue;
4297
+ } catch (e) {
4298
+ if (!e || !e.jsxParse) throw e;
4299
+ }
4300
+ }
4301
+ out += ch;
4302
+ i++;
4303
+ }
4304
+ return out;
4305
+ }
4306
+
3957
4307
  // =========================================================================
3958
4308
  // 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
3959
4309
  // =========================================================================
3960
- function transpileTS(source, filename = 'module.ts') {
4310
+ function transpileTS(source, filename = 'module.ts', opts = {}) {
4311
+ // `keepEsm` leaves `import`/`export` statements intact so the output can run
4312
+ // natively in a browser as an ES module (used by the built-in preview server).
4313
+ const keepEsm = Boolean(opts && opts.keepEsm);
3961
4314
  const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
3962
- || /\b(interface\s+[A-Za-z_$]|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$]|abstract\s+class\s+|declare\s+(?:const|let|var|function|class|type|interface)\b|public\s+|private\s+|protected\s+|readonly\s+|satisfies\s+[A-Za-z_${]|\bas\s+(?:const|unknown|any|[A-Za-z_${]))/m.test(source);
3963
- const hasESM = /^\s*(import|export)\s+/m.test(source);
3964
- if (!isTS && !hasESM) return source;
4315
+ || /^[ \t]*(?:export\s+)?(?:abstract\s+class\s+[A-Za-z_$]|declare\s+(?:const|let|var|function|class|namespace|module|global)\b|interface\s+[A-Za-z_$][A-Za-z0-9_$]*|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{|namespace\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{)/m.test(source);
4316
+ const hasESM = /^\s*(?:import|export)\b/m.test(source)
4317
+ || /\bexport\s*\{/.test(source)
4318
+ || /\bimport\s*\{/.test(source)
4319
+ || /\bexport\s+default\b/.test(source);
4320
+ const hasJsx = detectJsxSyntax(source, filename);
4321
+ if (!isTS && !hasESM && !hasJsx) return source;
4322
+
4323
+ // JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
4324
+ if (hasJsx) {
4325
+ const { pragma, frag } = readJsxPragma(source);
4326
+ const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
4327
+ const transformed = jsxTransform(source, { pragma, frag });
4328
+ if (transformed !== source) {
4329
+ source = transformed;
4330
+ // The classic runtime needs a React binding available to the JSX output.
4331
+ if (needsReact) {
4332
+ source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
4333
+ }
4334
+ }
4335
+ }
3965
4336
 
3966
4337
  // Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
3967
4338
  const placeholders = [];
@@ -4524,10 +4895,10 @@ function __initVirtualRuntime(rootScope) {
4524
4895
  } while (code !== prevCode);
4525
4896
  }
4526
4897
 
4527
- if (hasESM || isTS) {
4898
+ if ((hasESM || isTS) && !keepEsm) {
4528
4899
  // Convert ES module imports (including multi-line `{ ... }`)
4529
- code = code.replace(/^\s*import\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = require($2);');
4530
- code = code.replace(/^\s*import\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4900
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4901
+ code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4531
4902
  const cleaned = specifiers
4532
4903
  .split(',')
4533
4904
  .map((s) => s.trim())
@@ -4538,7 +4909,7 @@ function __initVirtualRuntime(rootScope) {
4538
4909
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4539
4910
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4540
4911
  });
4541
- code = code.replace(/^\s*import\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4912
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4542
4913
  const cleaned = specifiers
4543
4914
  .split(',')
4544
4915
  .map((s) => s.trim())
@@ -4547,42 +4918,48 @@ function __initVirtualRuntime(rootScope) {
4547
4918
  .join(', ');
4548
4919
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4549
4920
  });
4550
- code = code.replace(/^\s*import\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));');
4551
- code = code.replace(/^\s*import\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4921
+ 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));');
4922
+ // Dynamic `import("pkg")` — resolve through the CJS loader instead of the
4923
+ // host's dynamic import, which cannot see the virtual filesystem.
4924
+ code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
4925
+ // Side-effect import `import"pkg"` / `import "pkg"`. By this point the
4926
+ // specifier is literal-masked, and minified modules emit no whitespace
4927
+ // between `import` and the string, so `\s*` (not `\s+`) is required.
4928
+ code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4552
4929
 
4553
4930
  // Convert ES module exports
4554
4931
  const exportedNames = [];
4555
4932
  let defaultExportName = null;
4556
4933
  let hasEsmExport = false;
4557
4934
 
4558
- code = code.replace(/^\s*export\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4935
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4559
4936
  hasEsmExport = true;
4560
4937
  return `exports.${ns} = require(${mod.trim()});`;
4561
4938
  });
4562
- code = code.replace(/^\s*export\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4939
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4563
4940
  hasEsmExport = true;
4564
4941
  return `Object.assign(exports, require(${mod.trim()}));`;
4565
4942
  });
4566
- code = code.replace(/^\s*export\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4943
+ code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4567
4944
  hasEsmExport = true;
4568
4945
  defaultExportName = name;
4569
4946
  return `${kw} ${name}`;
4570
4947
  });
4571
- code = code.replace(/^\s*export\s+default\s+/gm, () => {
4948
+ code = code.replace(/\bexport\s+default\s+/gm, () => {
4572
4949
  hasEsmExport = true;
4573
4950
  return 'exports.default = ';
4574
4951
  });
4575
- code = code.replace(/^\s*export\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4952
+ code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4576
4953
  hasEsmExport = true;
4577
4954
  exportedNames.push(name);
4578
4955
  return `${kw} ${name}`;
4579
4956
  });
4580
- code = code.replace(/^\s*export\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4957
+ code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4581
4958
  hasEsmExport = true;
4582
4959
  exportedNames.push(name);
4583
4960
  return `${kw} ${name}`;
4584
4961
  });
4585
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4962
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4586
4963
  hasEsmExport = true;
4587
4964
  const mTrim = mod.trim();
4588
4965
  return list.split(',').map((item) => {
@@ -4594,7 +4971,7 @@ function __initVirtualRuntime(rootScope) {
4594
4971
  return `exports.${exported} = require(${mTrim}).${local};`;
4595
4972
  }).join(' ');
4596
4973
  });
4597
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4974
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4598
4975
  hasEsmExport = true;
4599
4976
  return list.split(',').map((item) => {
4600
4977
  const trimmed = item.trim();
@@ -4681,8 +5058,12 @@ function __initVirtualRuntime(rootScope) {
4681
5058
  const builtinSet = new Set([
4682
5059
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
4683
5060
  'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
4684
- 'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
4685
- 'stream', 'stream/promises', 'test', 'perf_hooks', 'timers', 'timers/promises', 'buffer',
5061
+ 'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
5062
+ 'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
5063
+ 'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
5064
+ 'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
5065
+ 'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
5066
+ 'wasi', 'console',
4686
5067
  'bun', 'bun:test', 'bun:sqlite'
4687
5068
  ]);
4688
5069
 
@@ -6592,6 +6973,285 @@ function __initVirtualRuntime(rootScope) {
6592
6973
  })();
6593
6974
 
6594
6975
  // Built-in Node module table
6976
+ // ── Additional Node builtin shims ────────────────────────────────────────
6977
+ // Widely-used packages require these at load time (e.g. `debug` requires
6978
+ // `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
6979
+ // whole app fails to start. Implementations are deliberately minimal but
6980
+ // shape-compatible; anything that genuinely cannot work in the sandbox
6981
+ // throws an explicit, descriptive error rather than silently misbehaving.
6982
+ const VirtualTty = {
6983
+ isatty() { return false; },
6984
+ ReadStream: class TtyReadStream extends EventEmitter {},
6985
+ WriteStream: class TtyWriteStream extends EventEmitter {
6986
+ constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
6987
+ getColorDepth() { return 1; }
6988
+ hasColors() { return false; }
6989
+ cursorTo() { return true; }
6990
+ clearLine() { return true; }
6991
+ moveCursor() { return true; }
6992
+ }
6993
+ };
6994
+
6995
+ function makeReadlineInterface() {
6996
+ const iface = new EventEmitter();
6997
+ iface.terminal = false;
6998
+ iface.line = '';
6999
+ iface.cursor = 0;
7000
+ iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
7001
+ iface.prompt = () => {};
7002
+ iface.setPrompt = () => {};
7003
+ iface.getPrompt = () => '';
7004
+ iface.write = () => {};
7005
+ iface.pause = () => iface;
7006
+ iface.resume = () => iface;
7007
+ iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
7008
+ iface[Symbol.asyncIterator] = async function* () {};
7009
+ return iface;
7010
+ }
7011
+ const VirtualReadline = {
7012
+ createInterface: makeReadlineInterface,
7013
+ Interface: class ReadlineInterface extends EventEmitter {},
7014
+ clearLine: () => true,
7015
+ clearScreenDown: () => true,
7016
+ cursorTo: () => true,
7017
+ moveCursor: () => true,
7018
+ emitKeypressEvents: () => {}
7019
+ };
7020
+ const VirtualReadlinePromises = {
7021
+ createInterface: () => {
7022
+ const iface = makeReadlineInterface();
7023
+ iface.question = () => Promise.resolve('');
7024
+ return iface;
7025
+ },
7026
+ Interface: class ReadlinePromisesInterface extends EventEmitter {}
7027
+ };
7028
+
7029
+ const VirtualAsyncHooks = {
7030
+ AsyncLocalStorage: class AsyncLocalStorage {
7031
+ constructor() { this._store = undefined; }
7032
+ getStore() { return this._store; }
7033
+ run(store, fn, ...args) {
7034
+ const prev = this._store;
7035
+ this._store = store;
7036
+ try { return fn(...args); } finally { this._store = prev; }
7037
+ }
7038
+ exit(fn, ...args) {
7039
+ const prev = this._store;
7040
+ this._store = undefined;
7041
+ try { return fn(...args); } finally { this._store = prev; }
7042
+ }
7043
+ enterWith(store) { this._store = store; }
7044
+ disable() { this._store = undefined; }
7045
+ },
7046
+ AsyncResource: class AsyncResource {
7047
+ constructor(type) { this.type = type || 'AsyncResource'; }
7048
+ runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
7049
+ emitDestroy() { return this; }
7050
+ asyncId() { return 0; }
7051
+ triggerAsyncId() { return 0; }
7052
+ static bind(fn) { return fn; }
7053
+ },
7054
+ createHook() { return { enable() {}, disable() {} }; },
7055
+ executionAsyncId() { return 0; },
7056
+ triggerAsyncId() { return 0; },
7057
+ executionAsyncResource() { return null; }
7058
+ };
7059
+
7060
+ const VirtualWorkerThreads = {
7061
+ isMainThread: true,
7062
+ threadId: 0,
7063
+ parentPort: null,
7064
+ workerData: null,
7065
+ resourceLimits: {},
7066
+ SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
7067
+ receiveMessageOnPort() { return undefined; },
7068
+ Worker: class Worker extends EventEmitter {
7069
+ constructor(filename) {
7070
+ super();
7071
+ this.threadId = -1;
7072
+ this.filename = filename;
7073
+ queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
7074
+ }
7075
+ postMessage() {}
7076
+ terminate() { return Promise.resolve(0); }
7077
+ ref() { return this; }
7078
+ unref() { return this; }
7079
+ },
7080
+ MessageChannel: class MessageChannel {},
7081
+ MessagePort: class MessagePort extends EventEmitter {}
7082
+ };
7083
+
7084
+ const VirtualV8 = {
7085
+ serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
7086
+ deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
7087
+ getHeapStatistics() {
7088
+ return {
7089
+ total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
7090
+ total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
7091
+ malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
7092
+ number_of_native_contexts: 1, number_of_detached_contexts: 0
7093
+ };
7094
+ },
7095
+ getHeapSpaceStatistics() { return []; },
7096
+ setFlagsFromString() {},
7097
+ cachedDataVersionTag() { return 0; },
7098
+ Serializer: class Serializer {
7099
+ constructor() { this._value = undefined; }
7100
+ writeHeader() {}
7101
+ writeValue(value) { this._value = value; }
7102
+ releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
7103
+ },
7104
+ Deserializer: class Deserializer {
7105
+ constructor(buffer) { this._buffer = buffer; }
7106
+ readHeader() { return true; }
7107
+ readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
7108
+ }
7109
+ };
7110
+
7111
+ const VirtualVm = {
7112
+ createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
7113
+ isContext() { return false; },
7114
+ createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
7115
+ runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
7116
+ runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
7117
+ runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
7118
+ compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
7119
+ Script: class Script {
7120
+ runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7121
+ runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7122
+ runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7123
+ }
7124
+ };
7125
+
7126
+ const VirtualDomain = {
7127
+ create() {
7128
+ const d = new EventEmitter();
7129
+ d.members = [];
7130
+ d.add = () => d;
7131
+ d.remove = () => d;
7132
+ d.bind = (fn) => fn;
7133
+ d.intercept = (fn) => fn;
7134
+ d.run = (fn, ...args) => fn(...args);
7135
+ d.dispose = () => d;
7136
+ return d;
7137
+ },
7138
+ createDomain() { return VirtualDomain.create(); }
7139
+ };
7140
+
7141
+ const VirtualDiagnosticsChannel = {
7142
+ _channels: new Map(),
7143
+ channel(name) {
7144
+ const key = String(name);
7145
+ if (!VirtualDiagnosticsChannel._channels.has(key)) {
7146
+ const ch = new EventEmitter();
7147
+ ch.name = key;
7148
+ ch.hasSubscribers = false;
7149
+ ch.subscribe = () => { ch.hasSubscribers = true; };
7150
+ ch.unsubscribe = () => { ch.hasSubscribers = false; };
7151
+ VirtualDiagnosticsChannel._channels.set(key, ch);
7152
+ }
7153
+ return VirtualDiagnosticsChannel._channels.get(key);
7154
+ },
7155
+ subscribe(name, cb) {
7156
+ const ch = VirtualDiagnosticsChannel.channel(name);
7157
+ ch.subscribe();
7158
+ if (typeof cb === 'function') ch.on('message', cb);
7159
+ },
7160
+ unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
7161
+ Channel: class Channel extends EventEmitter {}
7162
+ };
7163
+
7164
+ const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
7165
+ const VirtualTls = {
7166
+ DEFAULT_MIN_VERSION: 'TLSv1.2',
7167
+ DEFAULT_MAX_VERSION: 'TLSv1.3',
7168
+ rootCertificates: [],
7169
+ createSecureContext() { return { context: {} }; },
7170
+ SecureContext: class SecureContext {},
7171
+ TLSSocket: class TLSSocket extends EventEmitter {},
7172
+ Server: class TLSServer extends EventEmitter {},
7173
+ checkServerIdentity() { return undefined; },
7174
+ connect: notSupported('tls.connect'),
7175
+ createServer: notSupported('tls.createServer')
7176
+ };
7177
+ const VirtualDgram = {
7178
+ createSocket(type) {
7179
+ const sock = new EventEmitter();
7180
+ sock.type = type || 'udp4';
7181
+ sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
7182
+ sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
7183
+ sock.send = notSupported('dgram.send');
7184
+ sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
7185
+ sock.setBroadcast = () => sock;
7186
+ sock.setTTL = () => sock;
7187
+ sock.addMembership = () => {};
7188
+ sock.dropMembership = () => {};
7189
+ return sock;
7190
+ },
7191
+ Socket: class Socket extends EventEmitter {}
7192
+ };
7193
+ const VirtualHttp2 = {
7194
+ constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
7195
+ connect: notSupported('http2.connect'),
7196
+ createServer: notSupported('http2.createServer'),
7197
+ createSecureServer: notSupported('http2.createSecureServer')
7198
+ };
7199
+ const VirtualCluster = {
7200
+ isPrimary: true,
7201
+ isMaster: true,
7202
+ isWorker: false,
7203
+ workers: {},
7204
+ fork: notSupported('cluster.fork'),
7205
+ setupPrimary: notSupported('cluster.setupPrimary'),
7206
+ setupMaster: notSupported('cluster.setupMaster'),
7207
+ disconnect: () => {}
7208
+ };
7209
+ const VirtualRepl = { start: notSupported('repl.start') };
7210
+ const VirtualInspector = {
7211
+ open: () => null,
7212
+ close: () => {},
7213
+ url: () => '',
7214
+ Session: class Session { connect() {} disconnect() {} post() {} }
7215
+ };
7216
+ const VirtualTraceEvents = {
7217
+ createTracing: () => ({ enable() {}, disable() {} }),
7218
+ getEnabledCategories: () => ''
7219
+ };
7220
+ const VirtualWasi = {
7221
+ WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
7222
+ };
7223
+
7224
+ const VirtualStreamWeb = {
7225
+ ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
7226
+ WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
7227
+ TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
7228
+ };
7229
+ async function consumeStream(kind, stream) {
7230
+ const chunks = [];
7231
+ if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
7232
+ for await (const chunk of stream) chunks.push(chunk);
7233
+ } else if (stream && typeof stream.on === 'function') {
7234
+ await new Promise((resolve, reject) => {
7235
+ stream.on('data', (c) => chunks.push(c));
7236
+ stream.on('end', resolve);
7237
+ stream.on('error', reject);
7238
+ });
7239
+ }
7240
+ const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
7241
+ const buf = VirtualBuffer.concat(bufs);
7242
+ if (kind === 'buffer') return buf;
7243
+ if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
7244
+ if (kind === 'text') return buf.toString('utf8');
7245
+ if (kind === 'json') return JSON.parse(buf.toString('utf8'));
7246
+ return buf;
7247
+ }
7248
+ const VirtualStreamConsumers = {
7249
+ text: (s) => consumeStream('text', s),
7250
+ json: (s) => consumeStream('json', s),
7251
+ buffer: (s) => consumeStream('buffer', s),
7252
+ arrayBuffer: (s) => consumeStream('arrayBuffer', s)
7253
+ };
7254
+
6595
7255
  const builtinModules = {
6596
7256
  fs: vfs,
6597
7257
  'node:fs': vfs,
@@ -6652,9 +7312,59 @@ function __initVirtualRuntime(rootScope) {
6652
7312
  bun: BunObj,
6653
7313
  'node:bun': BunObj,
6654
7314
  'bun:test': bunTestModule,
6655
- 'bun:sqlite': { Database: SqliteDatabase }
7315
+ 'bun:sqlite': { Database: SqliteDatabase },
7316
+ tty: VirtualTty,
7317
+ tls: VirtualTls,
7318
+ dgram: VirtualDgram,
7319
+ readline: VirtualReadline,
7320
+ 'readline/promises': VirtualReadlinePromises,
7321
+ async_hooks: VirtualAsyncHooks,
7322
+ worker_threads: VirtualWorkerThreads,
7323
+ v8: VirtualV8,
7324
+ vm: VirtualVm,
7325
+ domain: VirtualDomain,
7326
+ diagnostics_channel: VirtualDiagnosticsChannel,
7327
+ http2: VirtualHttp2,
7328
+ cluster: VirtualCluster,
7329
+ repl: VirtualRepl,
7330
+ inspector: VirtualInspector,
7331
+ trace_events: VirtualTraceEvents,
7332
+ wasi: VirtualWasi,
7333
+ constants: vfs.constants,
7334
+ 'util/types': VirtualUtil.types,
7335
+ 'stream/web': VirtualStreamWeb,
7336
+ 'stream/consumers': VirtualStreamConsumers
6656
7337
  };
6657
7338
 
7339
+ // Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
7340
+ // so both spellings resolve identically without hand-maintaining two lists.
7341
+ for (const __builtinName of Object.keys(builtinModules)) {
7342
+ if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
7343
+ builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
7344
+ }
7345
+ }
7346
+
7347
+ // `module` must reference the now-complete builtin table, so it is attached
7348
+ // after the object literal above.
7349
+ const VirtualModule = {
7350
+ builtinModules: Object.keys(builtinModules),
7351
+ Module: class Module {},
7352
+ isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
7353
+ createRequire(from) {
7354
+ const base = typeof from === 'string' ? from : '/workspace';
7355
+ const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
7356
+ const req = (id) => {
7357
+ if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
7358
+ return loadModule(resolveModulePath(id, dir), false);
7359
+ };
7360
+ req.resolve = (id) => resolveModulePath(id, dir);
7361
+ req.cache = {};
7362
+ return req;
7363
+ }
7364
+ };
7365
+ builtinModules.module = VirtualModule;
7366
+ builtinModules['node:module'] = VirtualModule;
7367
+
6658
7368
  const moduleCache = new Map();
6659
7369
  let mainModule = null;
6660
7370
 
@@ -7219,6 +7929,14 @@ function __initVirtualRuntime(rootScope) {
7219
7929
  };
7220
7930
  }
7221
7931
 
7932
+ // Transpile a source file so it can run natively in a browser as an ES module:
7933
+ // JSX is compiled to the classic runtime (auto-importing React when needed) and
7934
+ // TypeScript annotations are stripped, but `import`/`export` are preserved so an
7935
+ // import map can resolve bare specifiers to CDN ESM builds.
7936
+ function transpileForBrowser(source, filename = 'module.js') {
7937
+ return transpileTS(source, filename, { keepEsm: true });
7938
+ }
7939
+
7222
7940
  return {
7223
7941
  VirtualBuffer,
7224
7942
  VirtualCrypto,
@@ -7238,6 +7956,7 @@ function __initVirtualRuntime(rootScope) {
7238
7956
  createVirtualHttp,
7239
7957
  createVirtualNet,
7240
7958
  transpileTS,
7959
+ transpileForBrowser,
7241
7960
  preloadNpmPackages,
7242
7961
  createVirtualPortTable,
7243
7962
  executeInVirtualRuntime