@innovatorved/code-lab 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +2 -1
- package/README.md +4 -2
- package/dist/code-lab.css +49 -0
- package/dist/code-lab.esm.js +946 -70
- package/dist/code-lab.js +946 -70
- package/dist/runtime.esm.js +329 -18
- package/dist/runtime.js +329 -18
- package/dist/shell.esm.js +553 -51
- package/dist/shell.js +553 -51
- package/package.json +6 -2
- package/src/code-lab.css +49 -0
- package/src/runtime.js +329 -18
- package/src/runtime.ts +329 -18
- package/src/shell.js +553 -51
- package/src/shell.ts +553 -51
- package/src/workbench.js +64 -1
- package/src/workbench.ts +64 -1
package/dist/code-lab.esm.js
CHANGED
|
@@ -3974,14 +3974,316 @@ function __initVirtualRuntime(rootScope) {
|
|
|
3974
3974
|
};
|
|
3975
3975
|
}
|
|
3976
3976
|
|
|
3977
|
+
// =========================================================================
|
|
3978
|
+
// 7b. JSX / TSX SUPPORT
|
|
3979
|
+
// -------------------------------------------------------------------------
|
|
3980
|
+
// Rewrites JSX syntax into classic `createElement(...)` calls. This runs
|
|
3981
|
+
// BEFORE the string-masking pass so that JSX text (which routinely contains
|
|
3982
|
+
// quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
|
|
3983
|
+
// JS strings, comments and template literals are skipped untouched.
|
|
3984
|
+
// =========================================================================
|
|
3985
|
+
function detectJsxSyntax(source, filename) {
|
|
3986
|
+
if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
|
|
3987
|
+
if (!source || source.indexOf('<') === -1) return false;
|
|
3988
|
+
if (/@jsx\b/.test(source)) return true;
|
|
3989
|
+
if (source.indexOf('<>') !== -1) return true;
|
|
3990
|
+
if (/<\/[A-Za-z]/.test(source)) return true;
|
|
3991
|
+
return false;
|
|
3992
|
+
}
|
|
3993
|
+
|
|
3994
|
+
function readJsxPragma(source) {
|
|
3995
|
+
let pragma = 'React.createElement';
|
|
3996
|
+
let frag = null;
|
|
3997
|
+
const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
|
|
3998
|
+
if (m) pragma = m[1];
|
|
3999
|
+
const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
|
|
4000
|
+
if (fm) frag = fm[1];
|
|
4001
|
+
if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
|
|
4002
|
+
return { pragma, frag };
|
|
4003
|
+
}
|
|
4004
|
+
|
|
4005
|
+
const JSX_WS_RE = /\s/;
|
|
4006
|
+
const JSX_NAME_START_RE = /[A-Za-z_$]/;
|
|
4007
|
+
const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
|
|
4008
|
+
|
|
4009
|
+
function jsxThrow(message) {
|
|
4010
|
+
const err = new Error(message);
|
|
4011
|
+
err.jsxParse = true;
|
|
4012
|
+
throw err;
|
|
4013
|
+
}
|
|
4014
|
+
|
|
4015
|
+
// Returns the exclusive end index if a JS string / template / comment starts
|
|
4016
|
+
// at `i`, otherwise -1. Regexes are deliberately ignored.
|
|
4017
|
+
function jsxSkipJsLiteral(source, i) {
|
|
4018
|
+
const ch = source[i];
|
|
4019
|
+
const next = source[i + 1];
|
|
4020
|
+
const len = source.length;
|
|
4021
|
+
if (ch === '/' && next === '/') {
|
|
4022
|
+
const e = source.indexOf('\n', i);
|
|
4023
|
+
return e === -1 ? len : e;
|
|
4024
|
+
}
|
|
4025
|
+
if (ch === '/' && next === '*') {
|
|
4026
|
+
const e = source.indexOf('*/', i + 2);
|
|
4027
|
+
return e === -1 ? len : e + 2;
|
|
4028
|
+
}
|
|
4029
|
+
if (ch === '"' || ch === "'") {
|
|
4030
|
+
let j = i + 1;
|
|
4031
|
+
while (j < len) {
|
|
4032
|
+
const c = source[j];
|
|
4033
|
+
if (c === '\\') { j += 2; continue; }
|
|
4034
|
+
if (c === ch) { j++; break; }
|
|
4035
|
+
if (c === '\n') break;
|
|
4036
|
+
j++;
|
|
4037
|
+
}
|
|
4038
|
+
return j;
|
|
4039
|
+
}
|
|
4040
|
+
if (ch === '`') {
|
|
4041
|
+
let j = i + 1;
|
|
4042
|
+
let depth = 0;
|
|
4043
|
+
while (j < len) {
|
|
4044
|
+
const c = source[j];
|
|
4045
|
+
if (c === '\\') { j += 2; continue; }
|
|
4046
|
+
if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
|
|
4047
|
+
if (c === '}' && depth > 0) { depth--; j++; continue; }
|
|
4048
|
+
if (c === '`' && depth === 0) { j++; break; }
|
|
4049
|
+
j++;
|
|
4050
|
+
}
|
|
4051
|
+
return j;
|
|
4052
|
+
}
|
|
4053
|
+
return -1;
|
|
4054
|
+
}
|
|
4055
|
+
|
|
4056
|
+
function jsxReadName(source, i) {
|
|
4057
|
+
if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
|
|
4058
|
+
let j = i;
|
|
4059
|
+
while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
|
|
4060
|
+
return { name: source.slice(i, j), next: j };
|
|
4061
|
+
}
|
|
4062
|
+
|
|
4063
|
+
function jsxSkipWs(source, i) {
|
|
4064
|
+
while (i < source.length && JSX_WS_RE.test(source[i])) i++;
|
|
4065
|
+
return i;
|
|
4066
|
+
}
|
|
4067
|
+
|
|
4068
|
+
function normalizeJsxText(raw) {
|
|
4069
|
+
if (!raw) return '';
|
|
4070
|
+
let t = raw.replace(/\r/g, '');
|
|
4071
|
+
if (t.indexOf('\n') !== -1) {
|
|
4072
|
+
t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
|
|
4073
|
+
} else if (!/\S/.test(t)) {
|
|
4074
|
+
return '';
|
|
4075
|
+
} else {
|
|
4076
|
+
t = t.replace(/[ \t]+/g, ' ');
|
|
4077
|
+
}
|
|
4078
|
+
return t ? JSON.stringify(t) : '';
|
|
4079
|
+
}
|
|
4080
|
+
|
|
4081
|
+
// Reads a balanced `{ ... }` expression container, skipping nested JSX and
|
|
4082
|
+
// JS literals. Returns the raw inner source (later re-transformed) plus the
|
|
4083
|
+
// index just past the closing brace.
|
|
4084
|
+
function jsxReadBraced(source, i, opts) {
|
|
4085
|
+
let depth = 0;
|
|
4086
|
+
let j = i;
|
|
4087
|
+
while (j < source.length) {
|
|
4088
|
+
const lit = jsxSkipJsLiteral(source, j);
|
|
4089
|
+
if (lit !== -1) { j = lit; continue; }
|
|
4090
|
+
const c = source[j];
|
|
4091
|
+
if (c === '{') { depth++; j++; continue; }
|
|
4092
|
+
if (c === '}') {
|
|
4093
|
+
depth--;
|
|
4094
|
+
j++;
|
|
4095
|
+
if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
|
|
4096
|
+
continue;
|
|
4097
|
+
}
|
|
4098
|
+
if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
|
|
4099
|
+
try {
|
|
4100
|
+
const el = jsxParseElement(source, j, opts);
|
|
4101
|
+
j = el.next;
|
|
4102
|
+
continue;
|
|
4103
|
+
} catch (e) {
|
|
4104
|
+
if (!e || !e.jsxParse) throw e;
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
j++;
|
|
4108
|
+
}
|
|
4109
|
+
jsxThrow('jsx: unterminated expression container');
|
|
4110
|
+
}
|
|
4111
|
+
|
|
4112
|
+
function jsxParseElement(source, i, opts) {
|
|
4113
|
+
const o = opts || readJsxPragma(source);
|
|
4114
|
+
let j = i + 1;
|
|
4115
|
+
let isFragment = false;
|
|
4116
|
+
let typeExpr;
|
|
4117
|
+
if (source[j] === '>') {
|
|
4118
|
+
isFragment = true;
|
|
4119
|
+
typeExpr = o.frag;
|
|
4120
|
+
j++;
|
|
4121
|
+
} else {
|
|
4122
|
+
const nm = jsxReadName(source, j);
|
|
4123
|
+
j = nm.next;
|
|
4124
|
+
const raw = nm.name;
|
|
4125
|
+
const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
|
|
4126
|
+
if (isReference) {
|
|
4127
|
+
typeExpr = raw.replace(/:/g, '.');
|
|
4128
|
+
} else {
|
|
4129
|
+
typeExpr = JSON.stringify(raw);
|
|
4130
|
+
}
|
|
4131
|
+
}
|
|
4132
|
+
|
|
4133
|
+
const props = [];
|
|
4134
|
+
let selfClosing = false;
|
|
4135
|
+
if (!isFragment) {
|
|
4136
|
+
for (;;) {
|
|
4137
|
+
j = jsxSkipWs(source, j);
|
|
4138
|
+
if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
|
|
4139
|
+
const c = source[j];
|
|
4140
|
+
if (c === '/') {
|
|
4141
|
+
if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
|
|
4142
|
+
j += 2;
|
|
4143
|
+
selfClosing = true;
|
|
4144
|
+
break;
|
|
4145
|
+
}
|
|
4146
|
+
if (c === '>') { j++; break; }
|
|
4147
|
+
if (c === '{') {
|
|
4148
|
+
const br = jsxReadBraced(source, j, o);
|
|
4149
|
+
const inner = br.inner.trim();
|
|
4150
|
+
if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
|
|
4151
|
+
props.push({ spread: jsxTransform(inner.slice(3), o) });
|
|
4152
|
+
j = br.next;
|
|
4153
|
+
continue;
|
|
4154
|
+
}
|
|
4155
|
+
if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
|
|
4156
|
+
const am = jsxReadName(source, j);
|
|
4157
|
+
const attrName = am.name;
|
|
4158
|
+
j = jsxSkipWs(source, am.next);
|
|
4159
|
+
let valueExpr = 'true';
|
|
4160
|
+
if (source[j] === '=') {
|
|
4161
|
+
j = jsxSkipWs(source, j + 1);
|
|
4162
|
+
const vc = source[j];
|
|
4163
|
+
if (vc === '"' || vc === "'") {
|
|
4164
|
+
let k = j + 1;
|
|
4165
|
+
while (k < source.length && source[k] !== vc) {
|
|
4166
|
+
if (source[k] === '\\') k++;
|
|
4167
|
+
k++;
|
|
4168
|
+
}
|
|
4169
|
+
if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
|
|
4170
|
+
valueExpr = JSON.stringify(source.slice(j + 1, k));
|
|
4171
|
+
j = k + 1;
|
|
4172
|
+
} else if (vc === '{') {
|
|
4173
|
+
const br = jsxReadBraced(source, j, o);
|
|
4174
|
+
valueExpr = jsxTransform(br.inner, o) || 'undefined';
|
|
4175
|
+
j = br.next;
|
|
4176
|
+
} else if (vc === '<') {
|
|
4177
|
+
const el = jsxParseElement(source, j, o);
|
|
4178
|
+
valueExpr = el.code;
|
|
4179
|
+
j = el.next;
|
|
4180
|
+
} else {
|
|
4181
|
+
jsxThrow('jsx: unsupported attribute value');
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4184
|
+
const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
|
|
4185
|
+
props.push({ key: propKey, value: valueExpr });
|
|
4186
|
+
}
|
|
4187
|
+
}
|
|
4188
|
+
|
|
4189
|
+
const children = [];
|
|
4190
|
+
if (!selfClosing) {
|
|
4191
|
+
for (;;) {
|
|
4192
|
+
if (j >= source.length) jsxThrow('jsx: missing closing tag');
|
|
4193
|
+
const c = source[j];
|
|
4194
|
+
if (c === '<' && source[j + 1] === '/') {
|
|
4195
|
+
j = jsxSkipWs(source, j + 2);
|
|
4196
|
+
if (source[j] === '>') { j++; break; }
|
|
4197
|
+
const cm = jsxReadName(source, j);
|
|
4198
|
+
j = jsxSkipWs(source, cm.next);
|
|
4199
|
+
if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
|
|
4200
|
+
j++;
|
|
4201
|
+
break;
|
|
4202
|
+
}
|
|
4203
|
+
if (c === '<') {
|
|
4204
|
+
const el = jsxParseElement(source, j, o);
|
|
4205
|
+
children.push(el.code);
|
|
4206
|
+
j = el.next;
|
|
4207
|
+
continue;
|
|
4208
|
+
}
|
|
4209
|
+
if (c === '{') {
|
|
4210
|
+
const br = jsxReadBraced(source, j, o);
|
|
4211
|
+
const inner = jsxTransform(br.inner, o);
|
|
4212
|
+
if (inner && inner.trim()) children.push(inner);
|
|
4213
|
+
j = br.next;
|
|
4214
|
+
continue;
|
|
4215
|
+
}
|
|
4216
|
+
let k = j;
|
|
4217
|
+
while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
|
|
4218
|
+
const text = normalizeJsxText(source.slice(j, k));
|
|
4219
|
+
if (text) children.push(text);
|
|
4220
|
+
j = k;
|
|
4221
|
+
}
|
|
4222
|
+
}
|
|
4223
|
+
|
|
4224
|
+
let propsCode = 'null';
|
|
4225
|
+
if (props.length) {
|
|
4226
|
+
const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
|
|
4227
|
+
propsCode = '{ ' + parts.join(', ') + ' }';
|
|
4228
|
+
}
|
|
4229
|
+
|
|
4230
|
+
const args = [typeExpr, propsCode].concat(children);
|
|
4231
|
+
return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
|
|
4232
|
+
}
|
|
4233
|
+
|
|
4234
|
+
function jsxTransform(source, opts) {
|
|
4235
|
+
const o = opts || readJsxPragma(source);
|
|
4236
|
+
let i = 0;
|
|
4237
|
+
let out = '';
|
|
4238
|
+
while (i < source.length) {
|
|
4239
|
+
const lit = jsxSkipJsLiteral(source, i);
|
|
4240
|
+
if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
|
|
4241
|
+
const ch = source[i];
|
|
4242
|
+
if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
|
|
4243
|
+
try {
|
|
4244
|
+
const el = jsxParseElement(source, i, o);
|
|
4245
|
+
out += el.code;
|
|
4246
|
+
i = el.next;
|
|
4247
|
+
continue;
|
|
4248
|
+
} catch (e) {
|
|
4249
|
+
if (!e || !e.jsxParse) throw e;
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
out += ch;
|
|
4253
|
+
i++;
|
|
4254
|
+
}
|
|
4255
|
+
return out;
|
|
4256
|
+
}
|
|
4257
|
+
|
|
3977
4258
|
// =========================================================================
|
|
3978
4259
|
// 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
|
|
3979
4260
|
// =========================================================================
|
|
3980
|
-
function transpileTS(source, filename = 'module.ts') {
|
|
4261
|
+
function transpileTS(source, filename = 'module.ts', opts = {}) {
|
|
4262
|
+
// `keepEsm` leaves `import`/`export` statements intact so the output can run
|
|
4263
|
+
// natively in a browser as an ES module (used by the built-in preview server).
|
|
4264
|
+
const keepEsm = Boolean(opts && opts.keepEsm);
|
|
3981
4265
|
const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
|
|
3982
|
-
||
|
|
3983
|
-
const hasESM = /^\s*(import|export)\
|
|
3984
|
-
|
|
4266
|
+
|| /^[ \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);
|
|
4267
|
+
const hasESM = /^\s*(?:import|export)\b/m.test(source)
|
|
4268
|
+
|| /\bexport\s*\{/.test(source)
|
|
4269
|
+
|| /\bimport\s*\{/.test(source)
|
|
4270
|
+
|| /\bexport\s+default\b/.test(source);
|
|
4271
|
+
const hasJsx = detectJsxSyntax(source, filename);
|
|
4272
|
+
if (!isTS && !hasESM && !hasJsx) return source;
|
|
4273
|
+
|
|
4274
|
+
// JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
|
|
4275
|
+
if (hasJsx) {
|
|
4276
|
+
const { pragma, frag } = readJsxPragma(source);
|
|
4277
|
+
const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
|
|
4278
|
+
const transformed = jsxTransform(source, { pragma, frag });
|
|
4279
|
+
if (transformed !== source) {
|
|
4280
|
+
source = transformed;
|
|
4281
|
+
// The classic runtime needs a React binding available to the JSX output.
|
|
4282
|
+
if (needsReact) {
|
|
4283
|
+
source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
|
|
4284
|
+
}
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
3985
4287
|
|
|
3986
4288
|
// Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
|
|
3987
4289
|
const placeholders = [];
|
|
@@ -4544,10 +4846,10 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4544
4846
|
} while (code !== prevCode);
|
|
4545
4847
|
}
|
|
4546
4848
|
|
|
4547
|
-
if (hasESM || isTS) {
|
|
4849
|
+
if ((hasESM || isTS) && !keepEsm) {
|
|
4548
4850
|
// Convert ES module imports (including multi-line `{ ... }`)
|
|
4549
|
-
code = code.replace(
|
|
4550
|
-
code = code.replace(
|
|
4851
|
+
code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
|
|
4852
|
+
code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
|
|
4551
4853
|
const cleaned = specifiers
|
|
4552
4854
|
.split(',')
|
|
4553
4855
|
.map((s) => s.trim())
|
|
@@ -4558,7 +4860,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4558
4860
|
return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
|
|
4559
4861
|
(cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
|
|
4560
4862
|
});
|
|
4561
|
-
code = code.replace(
|
|
4863
|
+
code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
|
|
4562
4864
|
const cleaned = specifiers
|
|
4563
4865
|
.split(',')
|
|
4564
4866
|
.map((s) => s.trim())
|
|
@@ -4567,42 +4869,42 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4567
4869
|
.join(', ');
|
|
4568
4870
|
return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
|
|
4569
4871
|
});
|
|
4570
|
-
code = code.replace(
|
|
4571
|
-
code = code.replace(
|
|
4872
|
+
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);');
|
|
4572
4874
|
|
|
4573
4875
|
// Convert ES module exports
|
|
4574
4876
|
const exportedNames = [];
|
|
4575
4877
|
let defaultExportName = null;
|
|
4576
4878
|
let hasEsmExport = false;
|
|
4577
4879
|
|
|
4578
|
-
code = code.replace(
|
|
4880
|
+
code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
|
|
4579
4881
|
hasEsmExport = true;
|
|
4580
4882
|
return `exports.${ns} = require(${mod.trim()});`;
|
|
4581
4883
|
});
|
|
4582
|
-
code = code.replace(
|
|
4884
|
+
code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
|
|
4583
4885
|
hasEsmExport = true;
|
|
4584
4886
|
return `Object.assign(exports, require(${mod.trim()}));`;
|
|
4585
4887
|
});
|
|
4586
|
-
code = code.replace(
|
|
4888
|
+
code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4587
4889
|
hasEsmExport = true;
|
|
4588
4890
|
defaultExportName = name;
|
|
4589
4891
|
return `${kw} ${name}`;
|
|
4590
4892
|
});
|
|
4591
|
-
code = code.replace(
|
|
4893
|
+
code = code.replace(/\bexport\s+default\s+/gm, () => {
|
|
4592
4894
|
hasEsmExport = true;
|
|
4593
4895
|
return 'exports.default = ';
|
|
4594
4896
|
});
|
|
4595
|
-
code = code.replace(
|
|
4897
|
+
code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4596
4898
|
hasEsmExport = true;
|
|
4597
4899
|
exportedNames.push(name);
|
|
4598
4900
|
return `${kw} ${name}`;
|
|
4599
4901
|
});
|
|
4600
|
-
code = code.replace(
|
|
4902
|
+
code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4601
4903
|
hasEsmExport = true;
|
|
4602
4904
|
exportedNames.push(name);
|
|
4603
4905
|
return `${kw} ${name}`;
|
|
4604
4906
|
});
|
|
4605
|
-
code = code.replace(
|
|
4907
|
+
code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
|
|
4606
4908
|
hasEsmExport = true;
|
|
4607
4909
|
const mTrim = mod.trim();
|
|
4608
4910
|
return list.split(',').map((item) => {
|
|
@@ -4614,7 +4916,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4614
4916
|
return `exports.${exported} = require(${mTrim}).${local};`;
|
|
4615
4917
|
}).join(' ');
|
|
4616
4918
|
});
|
|
4617
|
-
code = code.replace(
|
|
4919
|
+
code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
|
|
4618
4920
|
hasEsmExport = true;
|
|
4619
4921
|
return list.split(',').map((item) => {
|
|
4620
4922
|
const trimmed = item.trim();
|
|
@@ -7239,6 +7541,14 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7239
7541
|
};
|
|
7240
7542
|
}
|
|
7241
7543
|
|
|
7544
|
+
// Transpile a source file so it can run natively in a browser as an ES module:
|
|
7545
|
+
// JSX is compiled to the classic runtime (auto-importing React when needed) and
|
|
7546
|
+
// TypeScript annotations are stripped, but `import`/`export` are preserved so an
|
|
7547
|
+
// import map can resolve bare specifiers to CDN ESM builds.
|
|
7548
|
+
function transpileForBrowser(source, filename = 'module.js') {
|
|
7549
|
+
return transpileTS(source, filename, { keepEsm: true });
|
|
7550
|
+
}
|
|
7551
|
+
|
|
7242
7552
|
return {
|
|
7243
7553
|
VirtualBuffer,
|
|
7244
7554
|
VirtualCrypto,
|
|
@@ -7258,6 +7568,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7258
7568
|
createVirtualHttp,
|
|
7259
7569
|
createVirtualNet,
|
|
7260
7570
|
transpileTS,
|
|
7571
|
+
transpileForBrowser,
|
|
7261
7572
|
preloadNpmPackages,
|
|
7262
7573
|
createVirtualPortTable,
|
|
7263
7574
|
executeInVirtualRuntime
|
|
@@ -9906,9 +10217,31 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9906
10217
|
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
9907
10218
|
}
|
|
9908
10219
|
|
|
10220
|
+
function pickConditionalEntry(value) {
|
|
10221
|
+
if (typeof value === 'string') return value;
|
|
10222
|
+
if (!value || typeof value !== 'object') return null;
|
|
10223
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
10224
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
10225
|
+
if (value[key] !== undefined) {
|
|
10226
|
+
const picked = pickConditionalEntry(value[key]);
|
|
10227
|
+
if (picked) return picked;
|
|
10228
|
+
}
|
|
10229
|
+
}
|
|
10230
|
+
return null;
|
|
10231
|
+
}
|
|
10232
|
+
|
|
9909
10233
|
function resolveEntryRelPath(pkgJson) {
|
|
9910
|
-
let entry =
|
|
9911
|
-
|
|
10234
|
+
let entry = null;
|
|
10235
|
+
const exp = pkgJson && pkgJson.exports;
|
|
10236
|
+
if (typeof exp === 'string') {
|
|
10237
|
+
entry = exp;
|
|
10238
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
10239
|
+
entry = pickConditionalEntry(exp['.']);
|
|
10240
|
+
}
|
|
10241
|
+
if (!entry) {
|
|
10242
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
10243
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
10244
|
+
}
|
|
9912
10245
|
entry = String(entry).replace(/^[./]+/, '');
|
|
9913
10246
|
return entry || 'index.js';
|
|
9914
10247
|
}
|
|
@@ -9919,9 +10252,16 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9919
10252
|
|
|
9920
10253
|
function extractRelativeSpecifiers(code) {
|
|
9921
10254
|
const out = new Set();
|
|
9922
|
-
const
|
|
9923
|
-
|
|
9924
|
-
|
|
10255
|
+
const patterns = [
|
|
10256
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
10257
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
10258
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
10259
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
10260
|
+
];
|
|
10261
|
+
for (const re of patterns) {
|
|
10262
|
+
let m;
|
|
10263
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
10264
|
+
}
|
|
9925
10265
|
return Array.from(out);
|
|
9926
10266
|
}
|
|
9927
10267
|
|
|
@@ -9986,20 +10326,49 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9986
10326
|
const entry = resolveEntryRelPath(meta);
|
|
9987
10327
|
const files = [];
|
|
9988
10328
|
const visited = new Set();
|
|
9989
|
-
|
|
9990
|
-
|
|
9991
|
-
|
|
9992
|
-
|
|
9993
|
-
|
|
9994
|
-
|
|
9995
|
-
|
|
9996
|
-
|
|
9997
|
-
|
|
9998
|
-
|
|
9999
|
-
|
|
10000
|
-
|
|
10001
|
-
|
|
10002
|
-
|
|
10329
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
10330
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
10331
|
+
const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
|
|
10332
|
+
const expMap = meta.exports;
|
|
10333
|
+
if (expMap && typeof expMap === 'object') {
|
|
10334
|
+
let subCount = 0;
|
|
10335
|
+
for (const key of Object.keys(expMap)) {
|
|
10336
|
+
if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
|
|
10337
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
10338
|
+
if (target) { seed.push(target); subCount++; }
|
|
10339
|
+
}
|
|
10340
|
+
}
|
|
10341
|
+
let frontier = seed;
|
|
10342
|
+
while (frontier.length > 0) {
|
|
10343
|
+
const batch = [];
|
|
10344
|
+
for (const raw of frontier) {
|
|
10345
|
+
const rel = stripRelPath(raw);
|
|
10346
|
+
if (!rel || visited.has(rel)) continue;
|
|
10347
|
+
visited.add(rel);
|
|
10348
|
+
batch.push(rel);
|
|
10349
|
+
}
|
|
10350
|
+
frontier = [];
|
|
10351
|
+
if (batch.length === 0) break;
|
|
10352
|
+
const texts = await Promise.all(
|
|
10353
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
10354
|
+
);
|
|
10355
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
10356
|
+
const rel = batch[idx];
|
|
10357
|
+
const text = texts[idx];
|
|
10358
|
+
if (text === null) continue;
|
|
10359
|
+
files.push({ rel, content: text });
|
|
10360
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
10361
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
10362
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
10363
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
10364
|
+
// candidates 404 harmlessly.
|
|
10365
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
10366
|
+
? [target]
|
|
10367
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
10368
|
+
for (const cand of cands) {
|
|
10369
|
+
const c = stripRelPath(cand);
|
|
10370
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
10371
|
+
}
|
|
10003
10372
|
}
|
|
10004
10373
|
}
|
|
10005
10374
|
}
|
|
@@ -10009,7 +10378,16 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10009
10378
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
10010
10379
|
}
|
|
10011
10380
|
|
|
10012
|
-
|
|
10381
|
+
// 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 || {});
|
|
10384
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
10385
|
+
for (const peer of Object.keys(meta.peerDependencies || {})) {
|
|
10386
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
10387
|
+
if (depNames.indexOf(peer) === -1) depNames.push(peer);
|
|
10388
|
+
}
|
|
10389
|
+
|
|
10390
|
+
return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
10013
10391
|
}
|
|
10014
10392
|
|
|
10015
10393
|
function installTargetDirs(ctx, name) {
|
|
@@ -10030,17 +10408,30 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10030
10408
|
}
|
|
10031
10409
|
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
10032
10410
|
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
10411
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
10412
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
10413
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
10414
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
10415
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
10416
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
10417
|
+
}
|
|
10418
|
+
modPkg.exports = normalized;
|
|
10419
|
+
}
|
|
10033
10420
|
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
10034
10421
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
10035
10422
|
}
|
|
10036
10423
|
}
|
|
10037
10424
|
|
|
10038
|
-
async function installPackage(pkgSpec, ctx) {
|
|
10425
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
10426
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
10427
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
10428
|
+
const isDev = Boolean(options.dev);
|
|
10039
10429
|
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
10040
10430
|
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
10041
10431
|
|
|
10042
10432
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
10043
|
-
|
|
10433
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
10434
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
10044
10435
|
|
|
10045
10436
|
const fetchImpl = packageCtxFetch(ctx);
|
|
10046
10437
|
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
@@ -10066,11 +10457,13 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10066
10457
|
});
|
|
10067
10458
|
if (!warning) warning = info.reason;
|
|
10068
10459
|
installed.push({ name: item.name, version: '0.0.0' });
|
|
10460
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
10069
10461
|
continue;
|
|
10070
10462
|
}
|
|
10071
10463
|
|
|
10072
10464
|
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
10073
10465
|
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
10466
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
10074
10467
|
if (item.direct) directVersion = info.version || null;
|
|
10075
10468
|
|
|
10076
10469
|
for (const dep of (info.deps || [])) {
|
|
@@ -10082,12 +10475,71 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10082
10475
|
}
|
|
10083
10476
|
}
|
|
10084
10477
|
|
|
10085
|
-
pkgData
|
|
10478
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
10086
10479
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
10087
10480
|
|
|
10088
10481
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
10089
10482
|
}
|
|
10090
10483
|
|
|
10484
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
10485
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
10486
|
+
function createInstallEmitter(ctx, sink) {
|
|
10487
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
10488
|
+
return function emit(text) {
|
|
10489
|
+
if (!text) return;
|
|
10490
|
+
sink.push(text);
|
|
10491
|
+
if (stream) stream(text);
|
|
10492
|
+
};
|
|
10493
|
+
}
|
|
10494
|
+
|
|
10495
|
+
function formatInstallLine(info) {
|
|
10496
|
+
if (!info || !info.name) return '';
|
|
10497
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
10498
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
10499
|
+
}
|
|
10500
|
+
|
|
10501
|
+
function countInstalledPackages(results) {
|
|
10502
|
+
const seen = new Set();
|
|
10503
|
+
for (const r of results) {
|
|
10504
|
+
if (!r) continue;
|
|
10505
|
+
if (r.name) seen.add(r.name);
|
|
10506
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
10507
|
+
}
|
|
10508
|
+
return seen.size;
|
|
10509
|
+
}
|
|
10510
|
+
|
|
10511
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
10512
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
10513
|
+
// "saved N package(s)".
|
|
10514
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
10515
|
+
const options = opts || {};
|
|
10516
|
+
const manager = options.manager || 'bun';
|
|
10517
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
10518
|
+
const out = [];
|
|
10519
|
+
const emit = createInstallEmitter(ctx, out);
|
|
10520
|
+
const started = Date.now();
|
|
10521
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
10522
|
+
const results = [];
|
|
10523
|
+
for (const p of pkgs) {
|
|
10524
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
10525
|
+
}
|
|
10526
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
10527
|
+
const count = countInstalledPackages(results);
|
|
10528
|
+
const ms = Date.now() - started;
|
|
10529
|
+
if (manager === 'npm') {
|
|
10530
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
10531
|
+
} else if (manager === 'pnpm') {
|
|
10532
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
10533
|
+
} else {
|
|
10534
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
10535
|
+
}
|
|
10536
|
+
return {
|
|
10537
|
+
code: 0,
|
|
10538
|
+
stdout: out.join(''),
|
|
10539
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
10540
|
+
};
|
|
10541
|
+
}
|
|
10542
|
+
|
|
10091
10543
|
function uninstallPackage(pkgName, ctx) {
|
|
10092
10544
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
10093
10545
|
let changed = false;
|
|
@@ -10139,9 +10591,261 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10139
10591
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
10140
10592
|
cmd += ' ' + scriptArgs.join(' ');
|
|
10141
10593
|
}
|
|
10594
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
10595
|
+
if (fallback) return fallback;
|
|
10142
10596
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
10143
10597
|
}
|
|
10144
10598
|
|
|
10599
|
+
// ---------------------------------------------------------------------------
|
|
10600
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
10601
|
+
//
|
|
10602
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
10603
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
10604
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
10605
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
10606
|
+
// ---------------------------------------------------------------------------
|
|
10607
|
+
|
|
10608
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
10609
|
+
|
|
10610
|
+
const PREVIEW_MIME = {
|
|
10611
|
+
'.html': 'text/html; charset=utf-8',
|
|
10612
|
+
'.htm': 'text/html; charset=utf-8',
|
|
10613
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
10614
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
10615
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
10616
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
10617
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
10618
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
10619
|
+
'.css': 'text/css; charset=utf-8',
|
|
10620
|
+
'.json': 'application/json; charset=utf-8',
|
|
10621
|
+
'.map': 'application/json; charset=utf-8',
|
|
10622
|
+
'.svg': 'image/svg+xml',
|
|
10623
|
+
'.png': 'image/png',
|
|
10624
|
+
'.jpg': 'image/jpeg',
|
|
10625
|
+
'.jpeg': 'image/jpeg',
|
|
10626
|
+
'.gif': 'image/gif',
|
|
10627
|
+
'.webp': 'image/webp',
|
|
10628
|
+
'.ico': 'image/x-icon',
|
|
10629
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
10630
|
+
};
|
|
10631
|
+
|
|
10632
|
+
function previewMimeFor(p) {
|
|
10633
|
+
const lower = String(p).toLowerCase();
|
|
10634
|
+
const dot = lower.lastIndexOf('.');
|
|
10635
|
+
if (dot === -1) return 'application/octet-stream';
|
|
10636
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
10637
|
+
}
|
|
10638
|
+
|
|
10639
|
+
function isPreviewScriptPath(p) {
|
|
10640
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
10641
|
+
}
|
|
10642
|
+
|
|
10643
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
10644
|
+
function extractBareSpecifiers(code) {
|
|
10645
|
+
const out = new Set();
|
|
10646
|
+
const patterns = [
|
|
10647
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
10648
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
10649
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
10650
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
10651
|
+
];
|
|
10652
|
+
for (const re of patterns) {
|
|
10653
|
+
let m;
|
|
10654
|
+
while ((m = re.exec(code)) !== null) {
|
|
10655
|
+
const spec = m[1];
|
|
10656
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
10657
|
+
out.add(spec);
|
|
10658
|
+
}
|
|
10659
|
+
}
|
|
10660
|
+
return Array.from(out);
|
|
10661
|
+
}
|
|
10662
|
+
|
|
10663
|
+
function normalizeVersionRange(range) {
|
|
10664
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
10665
|
+
const v = range.trim();
|
|
10666
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
10667
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
10668
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
10669
|
+
}
|
|
10670
|
+
|
|
10671
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
10672
|
+
try {
|
|
10673
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
10674
|
+
if (vfs.existsSync(modPkg)) {
|
|
10675
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
10676
|
+
if (parsed && parsed.version) return parsed.version;
|
|
10677
|
+
}
|
|
10678
|
+
} catch (_) {}
|
|
10679
|
+
try {
|
|
10680
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
10681
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
10682
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
10683
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
10684
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
10685
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
10686
|
+
}
|
|
10687
|
+
} catch (_) {}
|
|
10688
|
+
return 'latest';
|
|
10689
|
+
}
|
|
10690
|
+
|
|
10691
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
10692
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
10693
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
10694
|
+
return `${base}${sub}/+esm`;
|
|
10695
|
+
}
|
|
10696
|
+
|
|
10697
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
10698
|
+
const imports = {};
|
|
10699
|
+
for (const spec of specifiers) {
|
|
10700
|
+
const parts = String(spec).split('/');
|
|
10701
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
10702
|
+
if (!pkgName) continue;
|
|
10703
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
10704
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
10705
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
10706
|
+
}
|
|
10707
|
+
return imports;
|
|
10708
|
+
}
|
|
10709
|
+
|
|
10710
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
10711
|
+
const scripts = [];
|
|
10712
|
+
const walk = (dir, depth) => {
|
|
10713
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
10714
|
+
let entries = [];
|
|
10715
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
10716
|
+
for (const name of entries) {
|
|
10717
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
10718
|
+
const full = PosixPath.join(dir, name);
|
|
10719
|
+
let st;
|
|
10720
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
10721
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
10722
|
+
if (dirFlag) {
|
|
10723
|
+
walk(full, depth + 1);
|
|
10724
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
10725
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
10726
|
+
}
|
|
10727
|
+
}
|
|
10728
|
+
};
|
|
10729
|
+
walk(rootDir, 0);
|
|
10730
|
+
return scripts;
|
|
10731
|
+
}
|
|
10732
|
+
|
|
10733
|
+
function injectPreviewExtras(html, importMap) {
|
|
10734
|
+
let out = html;
|
|
10735
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
10736
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
10737
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
10738
|
+
} else {
|
|
10739
|
+
out = importMapTag + '\n' + out;
|
|
10740
|
+
}
|
|
10741
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
10742
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
10743
|
+
else out = out + '\n' + shim;
|
|
10744
|
+
return out;
|
|
10745
|
+
}
|
|
10746
|
+
|
|
10747
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
10748
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
10749
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
10750
|
+
|
|
10751
|
+
let port = Number(preferredPort) || 3000;
|
|
10752
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
10753
|
+
while (taken.has(port)) port++;
|
|
10754
|
+
|
|
10755
|
+
const specifiers = new Set();
|
|
10756
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
10757
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
10758
|
+
}
|
|
10759
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
10760
|
+
|
|
10761
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
10762
|
+
const isDir = (p) => {
|
|
10763
|
+
try {
|
|
10764
|
+
const st = ctx.vfs.statSync(p);
|
|
10765
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
10766
|
+
} catch (_) { return false; }
|
|
10767
|
+
};
|
|
10768
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
10769
|
+
|
|
10770
|
+
const handler = async (request) => {
|
|
10771
|
+
let pathname = '/';
|
|
10772
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
10773
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
10774
|
+
let target = PosixPath.join(rootDir, rel);
|
|
10775
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
10776
|
+
|
|
10777
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
10778
|
+
target = PosixPath.join(target, 'index.html');
|
|
10779
|
+
}
|
|
10780
|
+
if (!exists(target) && !hasExt) {
|
|
10781
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
10782
|
+
// the way a bundler / dev server would.
|
|
10783
|
+
const cands = [
|
|
10784
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
10785
|
+
target + '.mjs', target + '.cjs',
|
|
10786
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
10787
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
10788
|
+
];
|
|
10789
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
10790
|
+
}
|
|
10791
|
+
if (!exists(target) && !hasExt) {
|
|
10792
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
10793
|
+
}
|
|
10794
|
+
if (!exists(target)) {
|
|
10795
|
+
return new Response(
|
|
10796
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
10797
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
10798
|
+
);
|
|
10799
|
+
}
|
|
10800
|
+
|
|
10801
|
+
let body = readText(target);
|
|
10802
|
+
if (body === null) body = '';
|
|
10803
|
+
if (/\.html?$/i.test(target)) {
|
|
10804
|
+
body = injectPreviewExtras(body, importMap);
|
|
10805
|
+
} else if (isPreviewScriptPath(target)) {
|
|
10806
|
+
try {
|
|
10807
|
+
const rm = getRuntimeModule();
|
|
10808
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
10809
|
+
body = rm.transpileForBrowser(body, target);
|
|
10810
|
+
}
|
|
10811
|
+
} catch (_) {}
|
|
10812
|
+
}
|
|
10813
|
+
|
|
10814
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
10815
|
+
};
|
|
10816
|
+
|
|
10817
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
10818
|
+
return portTable.registerServer(port, {
|
|
10819
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
10820
|
+
fetch: handler,
|
|
10821
|
+
name: 'code-lab-serve',
|
|
10822
|
+
pid,
|
|
10823
|
+
root: rootDir
|
|
10824
|
+
});
|
|
10825
|
+
}
|
|
10826
|
+
|
|
10827
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
10828
|
+
// transparently redirected to the built-in preview server.
|
|
10829
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
10830
|
+
|
|
10831
|
+
function tryDevScriptFallback(scriptName, cmd, ctx) {
|
|
10832
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
10833
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
10834
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
10835
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
10836
|
+
if (ctx.vfs.existsSync(binPath)) return null;
|
|
10837
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
10838
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
10839
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
10840
|
+
const entry = registerPreviewServer(ctx, ctx.cwd, port);
|
|
10841
|
+
if (!entry) return null;
|
|
10842
|
+
return {
|
|
10843
|
+
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`,
|
|
10845
|
+
stderr: ''
|
|
10846
|
+
};
|
|
10847
|
+
}
|
|
10848
|
+
|
|
10145
10849
|
function evaluatePosixTest(args, ctx) {
|
|
10146
10850
|
const cleanArgs = [...args];
|
|
10147
10851
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -12640,7 +13344,8 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
12640
13344
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
12641
13345
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
12642
13346
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
12643
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
13347
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
13348
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
12644
13349
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
12645
13350
|
return { code: 0, stdout, stderr: '' };
|
|
12646
13351
|
},
|
|
@@ -12825,26 +13530,25 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
12825
13530
|
|
|
12826
13531
|
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
12827
13532
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
13533
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
12828
13534
|
if (pkgs.length === 0) {
|
|
12829
13535
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
12830
|
-
const deps = Object.keys(pkgData.dependencies || {});
|
|
12831
|
-
|
|
12832
|
-
|
|
12833
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
12834
|
-
return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
13536
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
13537
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
13538
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
12835
13539
|
}
|
|
12836
|
-
|
|
12837
|
-
for (const p of pkgs) results.push(await installPackage(p, ctx));
|
|
12838
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
12839
|
-
return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
13540
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
12840
13541
|
}
|
|
12841
13542
|
|
|
12842
13543
|
if (sub === 'add') {
|
|
12843
|
-
|
|
12844
|
-
const
|
|
12845
|
-
|
|
12846
|
-
|
|
12847
|
-
|
|
13544
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
13545
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
13546
|
+
if (pkgs.length === 0) {
|
|
13547
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
13548
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
13549
|
+
}
|
|
13550
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
13551
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
12848
13552
|
}
|
|
12849
13553
|
|
|
12850
13554
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -13004,22 +13708,14 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13004
13708
|
}
|
|
13005
13709
|
|
|
13006
13710
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
13007
|
-
|
|
13711
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
13712
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
13008
13713
|
if (pkgs.length === 0) {
|
|
13009
13714
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
13010
|
-
|
|
13011
|
-
|
|
13012
|
-
results.push(await installPackage(p, ctx));
|
|
13013
|
-
}
|
|
13014
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
13015
|
-
return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
13715
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
13716
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
13016
13717
|
}
|
|
13017
|
-
|
|
13018
|
-
for (const p of pkgs) {
|
|
13019
|
-
results.push(await installPackage(p, ctx));
|
|
13020
|
-
}
|
|
13021
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
13022
|
-
return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
13718
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
13023
13719
|
}
|
|
13024
13720
|
|
|
13025
13721
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -13071,6 +13767,123 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13071
13767
|
return await this.npx(args, ctx);
|
|
13072
13768
|
},
|
|
13073
13769
|
|
|
13770
|
+
async pnpm(args, ctx) {
|
|
13771
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
13772
|
+
return {
|
|
13773
|
+
code: 0,
|
|
13774
|
+
stdout: 'pnpm v9.0.0\nUsage: pnpm <command>\n\nCommands:\n install, i Install all dependencies\n add <pkg> Add a dependency (-D for dev)\n remove, rm Remove a dependency\n list, ls List dependencies\n run <script> Run a package script\n exec <cmd> Run a command from node_modules/.bin\n dlx <pkg> Fetch and run a package\n --version, -v Print the version\n',
|
|
13775
|
+
stderr: ''
|
|
13776
|
+
};
|
|
13777
|
+
}
|
|
13778
|
+
const sub = args[0];
|
|
13779
|
+
if (sub === '--version' || sub === '-v') {
|
|
13780
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
13781
|
+
}
|
|
13782
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
13783
|
+
|
|
13784
|
+
if (sub === 'init') {
|
|
13785
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
13786
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
13787
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
13788
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
13789
|
+
version: '1.0.0',
|
|
13790
|
+
main: 'index.js',
|
|
13791
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
13792
|
+
}, null, 2) + '\n');
|
|
13793
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
13794
|
+
}
|
|
13795
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
13796
|
+
}
|
|
13797
|
+
|
|
13798
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
13799
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
13800
|
+
if (pkgs.length === 0) {
|
|
13801
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
13802
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
13803
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
13804
|
+
}
|
|
13805
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
13806
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
13807
|
+
}
|
|
13808
|
+
|
|
13809
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
13810
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
13811
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
13812
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
13813
|
+
}
|
|
13814
|
+
|
|
13815
|
+
if (sub === 'list' || sub === 'ls') {
|
|
13816
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
13817
|
+
}
|
|
13818
|
+
|
|
13819
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
13820
|
+
const scriptName = args[1];
|
|
13821
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
13822
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
13823
|
+
}
|
|
13824
|
+
|
|
13825
|
+
if (sub === 'test') {
|
|
13826
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
13827
|
+
}
|
|
13828
|
+
|
|
13829
|
+
if (sub === 'exec') {
|
|
13830
|
+
const cmd = args[1];
|
|
13831
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
13832
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
13833
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
13834
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
13835
|
+
}
|
|
13836
|
+
|
|
13837
|
+
if (sub === 'dlx') {
|
|
13838
|
+
return await this.npx(args.slice(1), ctx);
|
|
13839
|
+
}
|
|
13840
|
+
|
|
13841
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
13842
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
13843
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
13844
|
+
}
|
|
13845
|
+
|
|
13846
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
13847
|
+
},
|
|
13848
|
+
|
|
13849
|
+
async serve(args, ctx) {
|
|
13850
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
13851
|
+
return {
|
|
13852
|
+
code: 0,
|
|
13853
|
+
stdout: 'Usage: serve [dir] [--port <n>]\n\n Starts the built-in CodeLab preview server on the virtual port table.\n HTML/CSS/JS are served statically, .ts/.tsx/.jsx are transpiled to\n browser-native ESM on the fly, and bare imports resolve to jsDelivr ESM.\n\n Open the Web Preview drawer (or http://127.0.0.1:<port>/) to view it.\n',
|
|
13854
|
+
stderr: ''
|
|
13855
|
+
};
|
|
13856
|
+
}
|
|
13857
|
+
const rootArg = (() => {
|
|
13858
|
+
const positionals = [];
|
|
13859
|
+
for (let i = 0; i < args.length; i++) {
|
|
13860
|
+
const a = args[i];
|
|
13861
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
13862
|
+
if (a.startsWith('-')) continue;
|
|
13863
|
+
positionals.push(a);
|
|
13864
|
+
}
|
|
13865
|
+
return positionals[0];
|
|
13866
|
+
})();
|
|
13867
|
+
let port = 3000;
|
|
13868
|
+
for (let i = 0; i < args.length; i++) {
|
|
13869
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
13870
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
13871
|
+
}
|
|
13872
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
13873
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
13874
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
13875
|
+
}
|
|
13876
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
13877
|
+
if (!entry) {
|
|
13878
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
13879
|
+
}
|
|
13880
|
+
return {
|
|
13881
|
+
code: 0,
|
|
13882
|
+
stdout: `\n ⚡ CodeLab preview server\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n ➜ Root: ${rootDir}\n ➜ Preview: open the Web Preview drawer for port ${entry.port}\n\n`,
|
|
13883
|
+
stderr: ''
|
|
13884
|
+
};
|
|
13885
|
+
},
|
|
13886
|
+
|
|
13074
13887
|
// -----------------------------------------------------------------------
|
|
13075
13888
|
// Port Table & HTTP Inspection: ports, curl
|
|
13076
13889
|
// -----------------------------------------------------------------------
|
|
@@ -17021,6 +17834,9 @@ declare module 'bun:sqlite' {
|
|
|
17021
17834
|
<span>${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Step' : 'Run Tests'}</span>
|
|
17022
17835
|
<span class="codelab-btn__kbd">⌘↵</span>
|
|
17023
17836
|
</button>
|
|
17837
|
+
<button type="button" class="codelab-btn codelab-btn--icon" id="cl-preview-app-btn" data-cl-action="preview-app" title="Run & Preview in Browser (built-in dev server)" aria-label="Run and Preview in Browser">
|
|
17838
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
|
|
17839
|
+
</button>
|
|
17024
17840
|
<span class="codelab-toolbar__sep" aria-hidden="true"></span>
|
|
17025
17841
|
${this.hasGuidedLab ? `
|
|
17026
17842
|
<button type="button" class="codelab-btn codelab-btn--icon ${isGuideCollapsed ? '' : 'active'}" id="cl-toggle-guide-btn" data-cl-action="toggle-guide" title="Toggle Guide Panel" aria-label="Toggle Guide Panel" aria-pressed="${isGuideCollapsed ? 'false' : 'true'}">
|
|
@@ -19353,6 +20169,55 @@ declare module 'bun:sqlite' {
|
|
|
19353
20169
|
return this._previewLoadPromise || Promise.resolve();
|
|
19354
20170
|
}
|
|
19355
20171
|
|
|
20172
|
+
// One-click "run the app in a browser": if nothing is listening yet, start the
|
|
20173
|
+
// built-in preview server (which transpiles TS/JSX to browser-native ESM and
|
|
20174
|
+
// resolves bare imports via jsDelivr) and then open the Web Preview.
|
|
20175
|
+
async previewApp() {
|
|
20176
|
+
const existing = this._firstListeningPort();
|
|
20177
|
+
if (existing) {
|
|
20178
|
+
this._openWebPreview(existing);
|
|
20179
|
+
return existing;
|
|
20180
|
+
}
|
|
20181
|
+
|
|
20182
|
+
const htmlCandidates = ['public/index.html', 'index.html', 'site/index.html', 'src/index.html'];
|
|
20183
|
+
if (!htmlCandidates.some((f) => this.files && this.files[f])) {
|
|
20184
|
+
this.drawerTab = 'terminal';
|
|
20185
|
+
this.terminalLogs.push({
|
|
20186
|
+
type: 'system',
|
|
20187
|
+
text: '\nNo index.html found. Add an `index.html` (or run `serve <dir>` in the terminal) to preview your app.'
|
|
20188
|
+
});
|
|
20189
|
+
this._renderDrawerBody();
|
|
20190
|
+
return null;
|
|
20191
|
+
}
|
|
20192
|
+
|
|
20193
|
+
const rootDir = (this.files['public/index.html']) ? '/workspace/public'
|
|
20194
|
+
: (this.files['site/index.html']) ? '/workspace/site'
|
|
20195
|
+
: '/workspace';
|
|
20196
|
+
|
|
20197
|
+
if (!this.shell || typeof this.shell.execute !== 'function') return null;
|
|
20198
|
+
this._syncFilesToShellVfs();
|
|
20199
|
+
this.shell.cwd = this.cwd || '/workspace';
|
|
20200
|
+
this.drawerTab = 'terminal';
|
|
20201
|
+
this.terminalLogs.push({ type: 'system', text: `\n$ serve ${rootDir}` });
|
|
20202
|
+
this._renderDrawerBody();
|
|
20203
|
+
|
|
20204
|
+
try {
|
|
20205
|
+
const res = await this.shell.execute(`serve ${rootDir}`, {});
|
|
20206
|
+
if (res && res.stdout) this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
|
|
20207
|
+
if (res && res.stderr) this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
|
|
20208
|
+
} catch (err) {
|
|
20209
|
+
this.terminalLogs.push({ type: 'stderr', text: String((err && err.message) || err) });
|
|
20210
|
+
}
|
|
20211
|
+
this._renderDrawerBody();
|
|
20212
|
+
|
|
20213
|
+
const port = this._firstListeningPort();
|
|
20214
|
+
if (port) {
|
|
20215
|
+
this._openWebPreview(port);
|
|
20216
|
+
return port;
|
|
20217
|
+
}
|
|
20218
|
+
return null;
|
|
20219
|
+
}
|
|
20220
|
+
|
|
19356
20221
|
_previewGo(urlOrPath) {
|
|
19357
20222
|
let url = String(urlOrPath || '').trim();
|
|
19358
20223
|
if (!url) return Promise.resolve();
|
|
@@ -19523,7 +20388,15 @@ declare module 'bun:sqlite' {
|
|
|
19523
20388
|
<div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
|
|
19524
20389
|
<iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
|
|
19525
20390
|
</div>
|
|
19526
|
-
|
|
20391
|
+
${servers.length
|
|
20392
|
+
? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
|
|
20393
|
+
: `<div class="codelab-preview-empty">
|
|
20394
|
+
<div class="codelab-preview-empty__icon">${CL_ICONS.globe || '🌐'}</div>
|
|
20395
|
+
<div class="codelab-preview-empty__title">No server running</div>
|
|
20396
|
+
<div class="codelab-preview-empty__text">Start the built-in preview server to render your <code>index.html</code>. TypeScript, TSX and JSX are transpiled for the browser automatically — no bundler required.</div>
|
|
20397
|
+
<button type="button" class="codelab-btn codelab-btn--primary codelab-btn--sm" data-cl-action="preview-app">${CL_ICONS.play || '▶'} <span>Run & Preview</span></button>
|
|
20398
|
+
<div class="codelab-preview-empty__hint">or run <code>serve</code> in the terminal</div>
|
|
20399
|
+
</div>`}
|
|
19527
20400
|
</div>
|
|
19528
20401
|
`;
|
|
19529
20402
|
this._loadPreviewFrame();
|
|
@@ -20526,6 +21399,8 @@ declare module 'bun:sqlite' {
|
|
|
20526
21399
|
} else if (action === 'open-web-preview') {
|
|
20527
21400
|
const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
|
|
20528
21401
|
if (port) this._openWebPreview(port);
|
|
21402
|
+
} else if (action === 'preview-app') {
|
|
21403
|
+
this.previewApp();
|
|
20529
21404
|
} else if (action === 'dismiss-toast') {
|
|
20530
21405
|
this._dismissPortToast(actionBtn.dataset.port);
|
|
20531
21406
|
} else if (action === 'preview-back') {
|
|
@@ -22472,6 +23347,7 @@ declare module 'bun:sqlite' {
|
|
|
22472
23347
|
cloneRepo(repoInput, opts) { return this._instance ? this._instance.cloneRepo(repoInput, opts) : Promise.reject(new Error('Workbench not mounted')); }
|
|
22473
23348
|
runDemo() { return this._instance ? this._instance.runDemo() : Promise.resolve(); }
|
|
22474
23349
|
runTests(filter) { return this._instance ? this._instance.runTests(filter) : Promise.resolve(); }
|
|
23350
|
+
previewApp() { return this._instance ? this._instance.previewApp() : Promise.resolve(null); }
|
|
22475
23351
|
stopExecution() { if (this._instance) this._instance.stopExecution(); }
|
|
22476
23352
|
reset() { if (this._instance) this._instance.reset(); }
|
|
22477
23353
|
exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
|