@ohos-ports/bun-repl 0.0.0-stage → 2.1.1-beta.1
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/.eslintignore +2 -0
- package/.eslintrc.json +89 -0
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/dist/cli.js +62 -0
- package/dist/colors.js +68 -0
- package/dist/module/repl.js +83 -0
- package/dist/repl.js +945 -0
- package/dist/shims/bun.js +126 -0
- package/dist/shims/inspector-server.js +518 -0
- package/dist/swcrc.js +66 -0
- package/dist/transpiler.js +86 -0
- package/dist/utl/index.d.ts +30 -0
- package/dist/utl/index.js +2760 -0
- package/dist/utl/primordials.js +216 -0
- package/dist/utl/proxy.js +30 -0
- package/package.json +50 -4
- package/scripts/build.mjs +98 -0
- package/src/cli.ts +54 -0
- package/src/colors.ts +73 -0
- package/src/module/repl.ts +77 -0
- package/src/repl.ts +947 -0
- package/src/shims/bun.js +126 -0
- package/src/shims/inspector-server.js +518 -0
- package/src/swcrc.ts +70 -0
- package/src/transpiler.ts +96 -0
- package/src/utl/index.d.ts +117 -0
- package/src/utl/index.js +2760 -0
- package/src/utl/primordials.js +216 -0
- package/src/utl/proxy.js +30 -0
- package/tsconfig.json +99 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bun-repl Node port — 'bun' module shim + globalThis.Bun (src/shims/bun.js)
|
|
3
|
+
*
|
|
4
|
+
* Only the APIs actually referenced by the package are implemented, each with
|
|
5
|
+
* a real Node-based implementation (no no-op stubs):
|
|
6
|
+
*
|
|
7
|
+
* named exports (src/repl.ts `import ... from 'bun'`):
|
|
8
|
+
* - serve(...) -> node:http server hosting the local inspector backend
|
|
9
|
+
* - write(...) -> node:fs/promises writeFile
|
|
10
|
+
* - inspect(..) -> node:util inspect (with Bun-style option normalization)
|
|
11
|
+
*
|
|
12
|
+
* globalThis.Bun (Bun.* touchpoints in src/repl.ts, src/colors.ts,
|
|
13
|
+
* src/module/repl.ts, src/utl/index.js):
|
|
14
|
+
* - enableANSIColors -> real TTY/NO_COLOR/TERM computation
|
|
15
|
+
* - inspect, pathToFileURL, fileURLToPath -> node builtins
|
|
16
|
+
* - resolveSync -> createRequire(...).resolve
|
|
17
|
+
* - version/revision -> honest port markers (this is not a real Bun)
|
|
18
|
+
* - peek / peek.status -> real promise-state tracking (see inspector-server)
|
|
19
|
+
*
|
|
20
|
+
* Importing this module also installs `globalThis.Bun` (idempotently), so that
|
|
21
|
+
* modules which only read the global (src/colors.ts, src/utl/index.js) work.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { inspect as nodeUtilInspect } from 'node:util';
|
|
25
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
26
|
+
import { createRequire } from 'node:module';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
import { writeFile } from 'node:fs/promises';
|
|
29
|
+
import { getInspector, startInspector, peekStatus, peekValue } from './inspector-server.js';
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// 'bun' module named exports
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Bun.serve replacement for the REPL's inspector server.
|
|
37
|
+
* `options.port` may request a specific port (0 / undefined = ephemeral).
|
|
38
|
+
* Returns { hostname, port } like Bun's serve(); the port is bound by the
|
|
39
|
+
* time `inspectorReady()` resolves.
|
|
40
|
+
*/
|
|
41
|
+
export function serve(options = {}) {
|
|
42
|
+
const requestedPort = Number(options?.port) || 0;
|
|
43
|
+
const inspector = requestedPort > 0 ? startInspector(requestedPort) : getInspector();
|
|
44
|
+
return {
|
|
45
|
+
hostname: inspector.hostname,
|
|
46
|
+
// getter: the port is bound asynchronously on Node (Bun binds synchronously)
|
|
47
|
+
get port() { return inspector.port; },
|
|
48
|
+
get url() { return `http://${inspector.hostname}:${inspector.port}/`; },
|
|
49
|
+
get id() { return `bun-repl-node-port-${inspector.port}`; },
|
|
50
|
+
fetch() {
|
|
51
|
+
return Promise.resolve(new Response('bun-repl (node port): inspector endpoint only', { status: 404 }));
|
|
52
|
+
},
|
|
53
|
+
stop() { return inspector.close(); },
|
|
54
|
+
upgrade() { return inspector; },
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Resolves once the (default) inspector server is listening. */
|
|
59
|
+
export function inspectorReady() {
|
|
60
|
+
return getInspector().ready;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Bun.write(destination, data): promise-based file write (node:fs/promises). */
|
|
64
|
+
export function write(destination, data) {
|
|
65
|
+
return writeFile(destination, data);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Bun.inspect(value, options?): node:util inspect with Bun-style option fixes. */
|
|
69
|
+
export function inspect(value, options) {
|
|
70
|
+
const opts = { ...options };
|
|
71
|
+
if (opts.depth === null) opts.depth = Infinity;
|
|
72
|
+
if (typeof opts.sorted === 'function') opts.sorted = true;
|
|
73
|
+
return nodeUtilInspect(value, opts);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
// Bun global object
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Real ANSI-colour capability detection, mirroring Bun.enableANSIColors
|
|
82
|
+
* semantics: colour support requires a TTY, NO_COLOR must be unset and TERM
|
|
83
|
+
* must not be "dumb".
|
|
84
|
+
*/
|
|
85
|
+
const enableANSIColors =
|
|
86
|
+
process.stdout?.isTTY === true &&
|
|
87
|
+
process.env.NO_COLOR === undefined &&
|
|
88
|
+
process.env.TERM !== 'dumb';
|
|
89
|
+
|
|
90
|
+
/** Bun.resolveSync(specifier, parentDirectory) -> absolute file path. */
|
|
91
|
+
function resolveSync(specifier, parentDirectory) {
|
|
92
|
+
const anchor = typeof parentDirectory === 'string' && parentDirectory.length > 0
|
|
93
|
+
? join(parentDirectory, 'index.js')
|
|
94
|
+
: join(process.cwd(), 'index.js');
|
|
95
|
+
return createRequire(anchor).resolve(specifier);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const BunGlobal = {
|
|
99
|
+
// Identity is reported honestly: this is a Node port of a Bun-only package,
|
|
100
|
+
// not an actual Bun runtime.
|
|
101
|
+
version: '0.0.0-node-port',
|
|
102
|
+
revision: `bun-repl node port (no Bun runtime; host node v${process.versions.node})`,
|
|
103
|
+
enableANSIColors,
|
|
104
|
+
inspect,
|
|
105
|
+
pathToFileURL,
|
|
106
|
+
fileURLToPath,
|
|
107
|
+
resolveSync,
|
|
108
|
+
peek: Object.assign(
|
|
109
|
+
function peek(value) { return peekValue(value); },
|
|
110
|
+
{
|
|
111
|
+
/** Bun.peek.status(promise) — actual tracked state ('pending' on first observation). */
|
|
112
|
+
status(promise) { return peekStatus(promise); },
|
|
113
|
+
},
|
|
114
|
+
),
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
if (typeof globalThis.Bun === 'undefined') {
|
|
118
|
+
Object.defineProperty(globalThis, 'Bun', {
|
|
119
|
+
value: BunGlobal,
|
|
120
|
+
writable: true,
|
|
121
|
+
configurable: true,
|
|
122
|
+
enumerable: true,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export default BunGlobal;
|
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bun-repl Node port — local inspector backend (src/shims/inspector-server.js)
|
|
3
|
+
*
|
|
4
|
+
* The upstream REPL is architected around Bun's built-in JavaScriptCore
|
|
5
|
+
* inspector: `Bun.serve({ inspector: true })` exposes a WebSocket endpoint at
|
|
6
|
+
* ws://127.0.0.1:<port>/bun:inspect and `src/repl.ts` drives evaluation by
|
|
7
|
+
* sending JSC inspector protocol requests (`Runtime.evaluate`,
|
|
8
|
+
* `Runtime.callFunctionOn`, `Runtime.awaitPromise`, ...) over that socket.
|
|
9
|
+
*
|
|
10
|
+
* Node has no such server, so this shim provides a real, minimal
|
|
11
|
+
* implementation of the same protocol subset on top of `node:http`:
|
|
12
|
+
* - an HTTP server (with WebSocket upgrade handling, RFC 6455 frames)
|
|
13
|
+
* - `Runtime.evaluate` -> indirect `eval` in the main realm
|
|
14
|
+
* - `Runtime.callFunctionOn` -> real `Function.prototype.apply` with the
|
|
15
|
+
* registered object as receiver
|
|
16
|
+
* - `Runtime.awaitPromise` -> settles with the actual promise outcome
|
|
17
|
+
*
|
|
18
|
+
* Expressions are evaluated in the same realm the REPL runs in, which mirrors
|
|
19
|
+
* Bun's behaviour (the inspector evaluates against the process global object).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import http from 'node:http';
|
|
23
|
+
import { createHash } from 'node:crypto';
|
|
24
|
+
|
|
25
|
+
const INSPECT_PATH = '/bun:inspect';
|
|
26
|
+
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Promise internals peeking (Node replacement for Bun.peek)
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
// Bun.peek can synchronously read a promise's state and settled result.
|
|
32
|
+
// Node exposes no such API, so we track it for real: the first time a promise
|
|
33
|
+
// is observed it reports `pending`, and from then on the recorded state is
|
|
34
|
+
// the promise's actual settled state (updated via .then handlers).
|
|
35
|
+
const promiseStates = new WeakMap();
|
|
36
|
+
const promiseValues = new WeakMap();
|
|
37
|
+
|
|
38
|
+
function isThenable(value) {
|
|
39
|
+
try {
|
|
40
|
+
return value != null &&
|
|
41
|
+
(typeof value === 'object' || typeof value === 'function') &&
|
|
42
|
+
typeof value.then === 'function';
|
|
43
|
+
} catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function trackPromise(promise) {
|
|
49
|
+
if (promiseStates.has(promise)) return;
|
|
50
|
+
promiseStates.set(promise, 'pending');
|
|
51
|
+
try {
|
|
52
|
+
promise.then(
|
|
53
|
+
value => { promiseStates.set(promise, 'fulfilled'); promiseValues.set(promise, value); },
|
|
54
|
+
error => { promiseStates.set(promise, 'rejected'); promiseValues.set(promise, error); },
|
|
55
|
+
);
|
|
56
|
+
} catch {
|
|
57
|
+
// Not actually thenable; nothing to track.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Bun.peek.status(promise): 'pending' | 'fulfilled' | 'rejected' (best effort). */
|
|
62
|
+
export function peekStatus(promise) {
|
|
63
|
+
if (!isThenable(promise)) return undefined;
|
|
64
|
+
trackPromise(promise);
|
|
65
|
+
return promiseStates.get(promise);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Bun.peek(value): settled result of a promise if already observed, else the value itself. */
|
|
69
|
+
export function peekValue(value) {
|
|
70
|
+
if (!isThenable(value)) return value;
|
|
71
|
+
trackPromise(value);
|
|
72
|
+
return promiseValues.get(value);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
// Remote object registry (objectId <-> live value)
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
const objectRegistry = new Map();
|
|
79
|
+
let nextObjectID = 0;
|
|
80
|
+
|
|
81
|
+
function registerObject(value) {
|
|
82
|
+
const id = `inspector-object-${++nextObjectID}`;
|
|
83
|
+
objectRegistry.set(id, value);
|
|
84
|
+
return id;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function describeSafe(value, fallback) {
|
|
88
|
+
try {
|
|
89
|
+
const s = String(value);
|
|
90
|
+
return typeof s === 'string' ? s : fallback;
|
|
91
|
+
} catch {
|
|
92
|
+
return fallback;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Build a JSC-style `Runtime.RemoteObject` for a real value.
|
|
98
|
+
* Shapes consumed by src/repl.ts: type/subtype/className/value/description/
|
|
99
|
+
* objectId, plus `preview.properties[name='status']` for promises.
|
|
100
|
+
*/
|
|
101
|
+
function remoteObject(value) {
|
|
102
|
+
if (value === null) return { type: 'object', subtype: 'null', value: null, description: 'null' };
|
|
103
|
+
const type = typeof value;
|
|
104
|
+
switch (type) {
|
|
105
|
+
case 'undefined':
|
|
106
|
+
return { type };
|
|
107
|
+
case 'string':
|
|
108
|
+
case 'boolean':
|
|
109
|
+
return { type, value };
|
|
110
|
+
case 'number': {
|
|
111
|
+
// JSON cannot carry Infinity/NaN; JSC reports them via description.
|
|
112
|
+
const description = Object.is(value, -0) ? '-0' : String(value);
|
|
113
|
+
return { type, value: Number.isFinite(value) ? value : null, description };
|
|
114
|
+
}
|
|
115
|
+
case 'bigint':
|
|
116
|
+
// JSC reports bigint descriptions with the literal "n" suffix;
|
|
117
|
+
// src/repl.ts strips it back off before BigInt() reconstruction.
|
|
118
|
+
return { type, description: `${String(value)}n`, objectId: registerObject(value) };
|
|
119
|
+
case 'symbol':
|
|
120
|
+
return { type, description: describeSafe(value, 'Symbol()'), objectId: registerObject(value) };
|
|
121
|
+
case 'function': {
|
|
122
|
+
const className = value.name || 'Function';
|
|
123
|
+
return { type, className, description: describeSafe(value, className), objectId: registerObject(value) };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// typeof value === 'object'
|
|
127
|
+
if (isThenable(value)) {
|
|
128
|
+
return {
|
|
129
|
+
type,
|
|
130
|
+
subtype: 'promise',
|
|
131
|
+
className: 'Promise',
|
|
132
|
+
description: 'Promise',
|
|
133
|
+
preview: {
|
|
134
|
+
properties: [{ name: 'status', type: 'string', value: peekStatus(value) ?? 'pending' }],
|
|
135
|
+
},
|
|
136
|
+
objectId: registerObject(value),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
if (value instanceof Error) {
|
|
140
|
+
const className = value?.name ?? 'Error';
|
|
141
|
+
return { type, subtype: 'error', className, description: describeSafe(value, className), objectId: registerObject(value) };
|
|
142
|
+
}
|
|
143
|
+
let className = 'Object';
|
|
144
|
+
try { className = value?.constructor?.name ?? 'Object'; } catch { /* hostile prototype chain */ }
|
|
145
|
+
if (Array.isArray(value)) {
|
|
146
|
+
return { type, subtype: 'array', className, description: `Array(${value.length})`, objectId: registerObject(value) };
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
type,
|
|
150
|
+
className,
|
|
151
|
+
description: describeSafe(value, className).slice(0, 200),
|
|
152
|
+
objectId: registerObject(value),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Revive a RemoteObject back into the live value it was produced from. */
|
|
157
|
+
function reviveRemoteObject(ro) {
|
|
158
|
+
if (ro === null || typeof ro !== 'object') return ro;
|
|
159
|
+
if (ro.objectId) return objectRegistry.get(ro.objectId);
|
|
160
|
+
switch (ro.type) {
|
|
161
|
+
case 'object': return ro.subtype === 'null' ? null : undefined;
|
|
162
|
+
case 'undefined': return undefined;
|
|
163
|
+
case 'string': return ro.value;
|
|
164
|
+
case 'boolean': return ro.value;
|
|
165
|
+
case 'number': {
|
|
166
|
+
if (typeof ro.value === 'number') return ro.value;
|
|
167
|
+
switch (ro.description) {
|
|
168
|
+
case 'Infinity': return Infinity;
|
|
169
|
+
case '-Infinity': return -Infinity;
|
|
170
|
+
case 'NaN': return NaN;
|
|
171
|
+
default: return Number(ro.description);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
case 'bigint': return BigInt(String(ro.description ?? '0').replace(/n$/, ''));
|
|
175
|
+
default: return undefined;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Inspector protocol handlers
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* JSC-style completion values (Safari/Bun console semantics):
|
|
185
|
+
* JavaScriptCore reports the initializer of a trailing `var`/`let`/`const`
|
|
186
|
+
* declaration as a program's completion value, while V8 reports `undefined`
|
|
187
|
+
* (LexicalDeclaration evaluates to an empty completion per spec). Since this
|
|
188
|
+
* backend replaces Bun's JSC inspector, mirror JSC's behaviour by statically
|
|
189
|
+
* detecting a trailing declaration and appending a same-scope reference to it.
|
|
190
|
+
*
|
|
191
|
+
* Returns the declarator identifier, or null when the final statement is not
|
|
192
|
+
* a simple (non-destructuring) declaration.
|
|
193
|
+
*/
|
|
194
|
+
function trailingDeclarationName(code) {
|
|
195
|
+
// Drop trailing whitespace/semicolons so the final statement itself is
|
|
196
|
+
// captured (its own closing ';' must not be treated as its boundary).
|
|
197
|
+
const src = code.replace(/[\s;]+$/, '');
|
|
198
|
+
// Forward scan for the final statement, skipping string/template contents
|
|
199
|
+
// and comments, and tracking nesting so ';' inside braces is not a boundary.
|
|
200
|
+
let statementStart = 0;
|
|
201
|
+
let depth = 0;
|
|
202
|
+
let quote = null;
|
|
203
|
+
for (let i = 0; i < src.length; i++) {
|
|
204
|
+
const c = src[i];
|
|
205
|
+
const next = src[i + 1];
|
|
206
|
+
if (quote) {
|
|
207
|
+
if (c === '\\') { i++; continue; }
|
|
208
|
+
if (c === quote) quote = null;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (c === '\'' || c === '"' || c === '`') { quote = c; continue; }
|
|
212
|
+
if (c === '/' && next === '/') { while (i < src.length && src[i] !== '\n') i++; continue; }
|
|
213
|
+
if (c === '/' && next === '*') {
|
|
214
|
+
const end = src.indexOf('*/', i + 2);
|
|
215
|
+
i = end === -1 ? src.length : end + 1;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (c === '{' || c === '(' || c === '[') { depth++; continue; }
|
|
219
|
+
if (c === '}' || c === ')' || c === ']') { if (depth > 0) depth--; continue; }
|
|
220
|
+
if (depth === 0 && (c === ';' || c === '}')) statementStart = i + 1;
|
|
221
|
+
}
|
|
222
|
+
const statement = src.slice(statementStart).trim();
|
|
223
|
+
const decl = /^(?:var|let|const)\s+/.exec(statement);
|
|
224
|
+
if (!decl) return null;
|
|
225
|
+
// Split the declarator list on top-level commas and inspect the last one.
|
|
226
|
+
const list = statement.slice(decl[0].length);
|
|
227
|
+
const chunks = [];
|
|
228
|
+
{
|
|
229
|
+
let start = 0, d = 0, q = null;
|
|
230
|
+
for (let i = 0; i < list.length; i++) {
|
|
231
|
+
const c = list[i];
|
|
232
|
+
if (q) {
|
|
233
|
+
if (c === '\\') { i++; continue; }
|
|
234
|
+
if (c === q) q = null;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (c === '\'' || c === '"' || c === '`') { q = c; continue; }
|
|
238
|
+
if (c === '{' || c === '(' || c === '[') { d++; continue; }
|
|
239
|
+
if (c === '}' || c === ')' || c === ']') { if (d > 0) d--; continue; }
|
|
240
|
+
if (c === ',' && d === 0) { chunks.push(list.slice(start, i)); start = i + 1; }
|
|
241
|
+
}
|
|
242
|
+
chunks.push(list.slice(start));
|
|
243
|
+
}
|
|
244
|
+
const last = chunks[chunks.length - 1];
|
|
245
|
+
const name = /^\s*([A-Za-z_$][\w$]*)\s*=/.exec(last);
|
|
246
|
+
return name ? name[1] : null;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function runtimeEvaluate({ expression }) {
|
|
250
|
+
let source = expression;
|
|
251
|
+
if ((0, eval)('true') !== true) throw new Error('eval is unavailable'); // sanity guard
|
|
252
|
+
// Pre-compute the JSC-style completion only when the plain completion is
|
|
253
|
+
// empty; detect the trailing declaration statically first (no double eval).
|
|
254
|
+
const trailingName = trailingDeclarationName(expression);
|
|
255
|
+
if (trailingName !== null) {
|
|
256
|
+
source = `${expression}\n;(typeof ${trailingName} === 'undefined' || ${trailingName} === undefined) ? undefined : ${trailingName};`;
|
|
257
|
+
}
|
|
258
|
+
let value;
|
|
259
|
+
try {
|
|
260
|
+
value = (0, eval)(source); // indirect eval: main-realm global scope
|
|
261
|
+
} catch (error) {
|
|
262
|
+
return { result: remoteObject(error), wasThrown: true };
|
|
263
|
+
}
|
|
264
|
+
return { result: remoteObject(value), wasThrown: false };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function runtimeAwaitPromise({ promiseObjectId }) {
|
|
268
|
+
const promise = objectRegistry.get(promiseObjectId);
|
|
269
|
+
if (!isThenable(promise)) throw new Error('Runtime.awaitPromise: object is not a promise');
|
|
270
|
+
return new Promise(resolve => {
|
|
271
|
+
promise.then(
|
|
272
|
+
value => resolve({ result: remoteObject(value), wasThrown: false }),
|
|
273
|
+
error => resolve({ result: remoteObject(error), wasThrown: true }),
|
|
274
|
+
);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function runtimeCallFunctionOn({ objectId, functionDeclaration, arguments: args = [] }) {
|
|
279
|
+
let fn;
|
|
280
|
+
try {
|
|
281
|
+
fn = (0, eval)(`(${functionDeclaration})`);
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return { result: remoteObject(error), wasThrown: true };
|
|
284
|
+
}
|
|
285
|
+
if (typeof fn !== 'function') {
|
|
286
|
+
const error = new TypeError('Runtime.callFunctionOn: functionDeclaration did not evaluate to a function');
|
|
287
|
+
return { result: remoteObject(error), wasThrown: true };
|
|
288
|
+
}
|
|
289
|
+
const thisArg = objectId ? objectRegistry.get(objectId) : undefined;
|
|
290
|
+
const revived = args.map(reviveRemoteObject);
|
|
291
|
+
let value;
|
|
292
|
+
try {
|
|
293
|
+
value = fn.apply(thisArg, revived);
|
|
294
|
+
} catch (error) {
|
|
295
|
+
return { result: remoteObject(error), wasThrown: true };
|
|
296
|
+
}
|
|
297
|
+
return { result: remoteObject(value), wasThrown: false };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function dispatch(method, params) {
|
|
301
|
+
switch (method) {
|
|
302
|
+
case 'Runtime.enable':
|
|
303
|
+
case 'Runtime.runIfWaitingForDebugger':
|
|
304
|
+
return {};
|
|
305
|
+
case 'Runtime.evaluate':
|
|
306
|
+
return runtimeEvaluate(params);
|
|
307
|
+
case 'Runtime.awaitPromise':
|
|
308
|
+
return runtimeAwaitPromise(params);
|
|
309
|
+
case 'Runtime.callFunctionOn':
|
|
310
|
+
return runtimeCallFunctionOn(params);
|
|
311
|
+
default:
|
|
312
|
+
// Unknown inspector domains are acknowledged, like a real inspector
|
|
313
|
+
// frontend/backend pair would tolerate.
|
|
314
|
+
return {};
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function handleInspectorMessage(connection, text) {
|
|
319
|
+
let message;
|
|
320
|
+
try {
|
|
321
|
+
message = JSON.parse(text);
|
|
322
|
+
} catch {
|
|
323
|
+
return; // not a protocol message
|
|
324
|
+
}
|
|
325
|
+
const { id, method, params = {} } = message;
|
|
326
|
+
try {
|
|
327
|
+
const result = await dispatch(method, params);
|
|
328
|
+
connection.send(JSON.stringify({ id, result }));
|
|
329
|
+
} catch (error) {
|
|
330
|
+
connection.send(JSON.stringify({ id, error: { code: -32000, message: describeSafe(error, 'inspector error') } }));
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---------------------------------------------------------------------------
|
|
335
|
+
// Minimal RFC 6455 WebSocket server-side connection
|
|
336
|
+
// ---------------------------------------------------------------------------
|
|
337
|
+
class WebSocketConnection {
|
|
338
|
+
constructor(socket) {
|
|
339
|
+
this.socket = socket;
|
|
340
|
+
this.buffer = Buffer.alloc(0);
|
|
341
|
+
this.fragments = null;
|
|
342
|
+
this.closed = false;
|
|
343
|
+
this.onmessage = null;
|
|
344
|
+
this.onclose = null;
|
|
345
|
+
socket.on('data', chunk => this.#onData(chunk));
|
|
346
|
+
socket.on('error', () => this.#destroy());
|
|
347
|
+
socket.on('close', () => {
|
|
348
|
+
if (!this.closed) {
|
|
349
|
+
this.closed = true;
|
|
350
|
+
this.onclose?.();
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
#onData(chunk) {
|
|
356
|
+
this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]);
|
|
357
|
+
for (let frame = this.#readFrame(); frame !== null; frame = this.#readFrame()) {
|
|
358
|
+
const { opcode, fin, payload } = frame;
|
|
359
|
+
if (opcode === 0x0) { // continuation frame
|
|
360
|
+
if (this.fragments) {
|
|
361
|
+
this.fragments.push(payload);
|
|
362
|
+
if (fin) {
|
|
363
|
+
const full = Buffer.concat(this.fragments);
|
|
364
|
+
this.fragments = null;
|
|
365
|
+
this.onmessage?.(full.toString('utf8'));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
} else if (opcode === 0x1 || opcode === 0x2) { // text / binary
|
|
369
|
+
if (!fin) this.fragments = [payload];
|
|
370
|
+
else this.onmessage?.(payload.toString('utf8'));
|
|
371
|
+
} else if (opcode === 0x8) { // close
|
|
372
|
+
this.sendFrame(0x8, payload.subarray(0, 2));
|
|
373
|
+
this.#destroy();
|
|
374
|
+
} else if (opcode === 0x9) { // ping
|
|
375
|
+
this.sendFrame(0xA, payload);
|
|
376
|
+
}
|
|
377
|
+
// pong (0xA): nothing to do
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
#readFrame() {
|
|
382
|
+
const buf = this.buffer;
|
|
383
|
+
if (buf.length < 2) return null;
|
|
384
|
+
const fin = (buf[0] & 0x80) !== 0;
|
|
385
|
+
const opcode = buf[0] & 0x0f;
|
|
386
|
+
const masked = (buf[1] & 0x80) !== 0;
|
|
387
|
+
let length = buf[1] & 0x7f;
|
|
388
|
+
let offset = 2;
|
|
389
|
+
if (length === 126) {
|
|
390
|
+
if (buf.length < offset + 2) return null;
|
|
391
|
+
length = buf.readUInt16BE(offset);
|
|
392
|
+
offset += 2;
|
|
393
|
+
} else if (length === 127) {
|
|
394
|
+
if (buf.length < offset + 8) return null;
|
|
395
|
+
length = Number(buf.readBigUInt64BE(offset));
|
|
396
|
+
offset += 8;
|
|
397
|
+
}
|
|
398
|
+
let mask = null;
|
|
399
|
+
if (masked) {
|
|
400
|
+
if (buf.length < offset + 4) return null;
|
|
401
|
+
mask = buf.subarray(offset, offset + 4);
|
|
402
|
+
offset += 4;
|
|
403
|
+
}
|
|
404
|
+
if (buf.length < offset + length) return null;
|
|
405
|
+
let payload = Buffer.from(buf.subarray(offset, offset + length));
|
|
406
|
+
if (mask) {
|
|
407
|
+
for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
|
|
408
|
+
}
|
|
409
|
+
this.buffer = buf.subarray(offset + length);
|
|
410
|
+
return { fin, opcode, payload };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
sendFrame(opcode, payload) {
|
|
414
|
+
if (this.closed || this.socket.destroyed) return;
|
|
415
|
+
const length = payload.length;
|
|
416
|
+
let header;
|
|
417
|
+
if (length < 126) {
|
|
418
|
+
header = Buffer.from([0x80 | opcode, length]);
|
|
419
|
+
} else if (length < 65536) {
|
|
420
|
+
header = Buffer.alloc(4);
|
|
421
|
+
header[0] = 0x80 | opcode;
|
|
422
|
+
header[1] = 126;
|
|
423
|
+
header.writeUInt16BE(length, 2);
|
|
424
|
+
} else {
|
|
425
|
+
header = Buffer.alloc(10);
|
|
426
|
+
header[0] = 0x80 | opcode;
|
|
427
|
+
header[1] = 127;
|
|
428
|
+
header.writeBigUInt64BE(BigInt(length), 2);
|
|
429
|
+
}
|
|
430
|
+
this.socket.write(Buffer.concat([header, payload]));
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
send(text) {
|
|
434
|
+
this.sendFrame(0x1, Buffer.from(text, 'utf8'));
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
#destroy() {
|
|
438
|
+
if (this.closed) return;
|
|
439
|
+
this.closed = true;
|
|
440
|
+
try { this.socket.destroy(); } catch { /* already destroyed */ }
|
|
441
|
+
this.onclose?.();
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function acceptWebSocket(req, socket) {
|
|
446
|
+
const key = req.headers['sec-websocket-key'];
|
|
447
|
+
if (!key) {
|
|
448
|
+
socket.destroy();
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const accept = createHash('sha1').update(key + WS_GUID).digest('base64');
|
|
452
|
+
socket.write(
|
|
453
|
+
'HTTP/1.1 101 Switching Protocols\r\n' +
|
|
454
|
+
'Upgrade: websocket\r\n' +
|
|
455
|
+
'Connection: Upgrade\r\n' +
|
|
456
|
+
`Sec-WebSocket-Accept: ${accept}\r\n` +
|
|
457
|
+
'\r\n',
|
|
458
|
+
);
|
|
459
|
+
socket.setNoDelay(true);
|
|
460
|
+
// The inspector must never keep the process alive on its own.
|
|
461
|
+
socket.unref();
|
|
462
|
+
const connection = new WebSocketConnection(socket);
|
|
463
|
+
connection.onmessage = text => { void handleInspectorMessage(connection, text); };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// ---------------------------------------------------------------------------
|
|
467
|
+
// Server lifecycle
|
|
468
|
+
// ---------------------------------------------------------------------------
|
|
469
|
+
export function startInspector(port = 0) {
|
|
470
|
+
const server = http.createServer((req, res) => {
|
|
471
|
+
res.statusCode = 404;
|
|
472
|
+
res.setHeader('content-type', 'text/plain');
|
|
473
|
+
res.end('bun-repl (node port): only the inspector endpoint is served here.');
|
|
474
|
+
});
|
|
475
|
+
server.on('upgrade', (req, socket) => {
|
|
476
|
+
let pathname;
|
|
477
|
+
try {
|
|
478
|
+
pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
|
|
479
|
+
} catch {
|
|
480
|
+
pathname = req.url ?? '/';
|
|
481
|
+
}
|
|
482
|
+
if (pathname !== INSPECT_PATH) {
|
|
483
|
+
socket.destroy();
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
acceptWebSocket(req, socket);
|
|
487
|
+
});
|
|
488
|
+
let resolveReady;
|
|
489
|
+
let rejectReady;
|
|
490
|
+
const ready = new Promise((resolve, reject) => {
|
|
491
|
+
resolveReady = resolve;
|
|
492
|
+
rejectReady = reject;
|
|
493
|
+
});
|
|
494
|
+
let boundPort = null;
|
|
495
|
+
server.on('listening', () => {
|
|
496
|
+
boundPort = server.address().port;
|
|
497
|
+
resolveReady();
|
|
498
|
+
});
|
|
499
|
+
server.on('error', rejectReady);
|
|
500
|
+
server.listen(port, '127.0.0.1');
|
|
501
|
+
// A REPL inspector should not hold the event loop open by itself
|
|
502
|
+
// (Bun kills the process via process.exit; Node relies on handle counts).
|
|
503
|
+
server.unref();
|
|
504
|
+
return {
|
|
505
|
+
get hostname() { return '127.0.0.1'; },
|
|
506
|
+
get port() { return boundPort; },
|
|
507
|
+
ready,
|
|
508
|
+
close: () => new Promise(resolve => server.close(() => resolve())),
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
let singleton = null;
|
|
513
|
+
|
|
514
|
+
/** The default inspector (ephemeral port), created on first use. */
|
|
515
|
+
export function getInspector() {
|
|
516
|
+
singleton ??= startInspector(0);
|
|
517
|
+
return singleton;
|
|
518
|
+
}
|