@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/dist/repl.js ADDED
@@ -0,0 +1,945 @@
1
+ import { join, dirname, basename, resolve as pathresolve } from 'node:path';
2
+ import { readFileSync, existsSync, readSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import readline from 'node:readline';
5
+ import { createRequire } from 'node:module';
6
+ import $ from './colors.js';
7
+ import swcrc from './swcrc.js';
8
+ import SWCTranspiler from './transpiler.js';
9
+ import repl from './module/repl.js';
10
+ import utl, { $Proxy } from './utl/index.js';
11
+ import bun, { serve, write, inspect as bunInspect, inspectorReady } from './shims/bun.js';
12
+ const { exit, cwd } = process;
13
+ // Node port: Bun's `import.meta.require` equivalent — a CJS loader anchored at this module.
14
+ const metaRequire = createRequire(import.meta.url);
15
+ const stdoutWrite = process.stdout.write.bind(process.stdout);
16
+ /**Safely get an object's property. If an error occurs, just treat it as non-existent. */ export function SafeGet(obj, key) {
17
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
18
+ try {
19
+ return obj?.[key];
20
+ } catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /** Safely inspect a value, falling down through implementations as they fail. If all inspectors fail, simply return undefined. */ export function SafeInspect(val, opts = {}) {
25
+ try {
26
+ try {
27
+ return utl.inspect(val, opts);
28
+ } catch {
29
+ // Bun's native inspect is expected to never fail. Unfortunately it doesn't inspect a lot of values properly,
30
+ // nor does it support the full options object, therefore it's the fallback for now.
31
+ if (opts.depth === null) opts.depth = Infinity;
32
+ if (typeof opts.sorted === 'function') opts.sorted = true;
33
+ return bunInspect(val, opts);
34
+ }
35
+ } catch {
36
+ try {
37
+ // In the greatly unexpected event of Bun's native inspect failing,
38
+ // panic back to the primitive method of string coercion.
39
+ console.warn($.yellow + $.dim + 'All value inspection methods failed, this should not happen!' + $.reset);
40
+ const str = val + '';
41
+ // If the coercion somehow fails to return a proper string, resort to an empty one.
42
+ return typeof str === 'string' ? str : '';
43
+ } catch {
44
+ // Here's a fun fact about javascript.
45
+ // You can't rely even on string concatenation as a fully reliable string coercion method.
46
+ // Introducing, null prototype objects: `Object.create(null) + ""` = throws TypeError
47
+ return ''; // If this line of code ever runs, something truly catastrophic happened...
48
+ }
49
+ }
50
+ }
51
+ const GLOBAL = globalThis;
52
+ // node port: one-shot global REPL setup guard — Bun exits the process after each
53
+ // single-shot run, but the Node port returns control, so start() may run again.
54
+ let REPL_GLOBALS_READY = false;
55
+ const { Buffer, WebSocket, Map, EvalError, TypeError, Error } = GLOBAL;
56
+ //const Promise: PromiseConstructor<any> = GLOBAL.Promise; // TS bug?
57
+ const { isBuffer } = Buffer;
58
+ const SymbolToStringTag = Symbol.toStringTag;
59
+ const JSONParse = JSON.parse;
60
+ const JSONStringify = JSON.stringify;
61
+ const ObjectAssign = Object.assign;
62
+ const ObjectDefineProperty = Object.defineProperty;
63
+ const ReflectGet = Reflect.get;
64
+ const ReflectSet = Reflect.set;
65
+ const ReflectDeleteProperty = Reflect.deleteProperty;
66
+ const RegExpTest = Function.prototype.call.bind(RegExp.prototype.test);
67
+ const RegExpPrototypeSymbolReplace = Function.prototype.call.bind(RegExp.prototype[Symbol.replace]);
68
+ const FunctionApply = Function.prototype.call.bind(Function.prototype.apply);
69
+ const BufferToString = Function.prototype.call.bind(Reflect.get(Buffer.prototype, 'toString'));
70
+ const StringTrim = Function.prototype.call.bind(String.prototype.trim);
71
+ const StringPadStart = Function.prototype.call.bind(String.prototype.padStart);
72
+ const StringPadEnd = Function.prototype.call.bind(String.prototype.padEnd);
73
+ const StringRepeat = Function.prototype.call.bind(String.prototype.repeat);
74
+ const StringMatchAll = Function.prototype.call.bind(String.prototype.matchAll);
75
+ const StringPrototypeSlice = Function.prototype.call.bind(String.prototype.slice);
76
+ const StringPrototypeSplit = Function.prototype.call.bind(String.prototype.split);
77
+ const StringPrototypeIncludes = Function.prototype.call.bind(String.prototype.includes);
78
+ const StringReplace = Function.prototype.call.bind(String.prototype.replace);
79
+ const StringPrototypeReplaceAll = Function.prototype.call.bind(String.prototype.replaceAll);
80
+ const ArrayPush = Function.prototype.call.bind(Array.prototype.push);
81
+ const ArrayPrototypePop = Function.prototype.call.bind(Array.prototype.pop);
82
+ const ArrayPrototypeJoin = Function.prototype.call.bind(Array.prototype.join);
83
+ const ArrayPrototypeFind = Function.prototype.call.bind(Array.prototype.find);
84
+ const ArrayPrototypeFilter = Function.prototype.call.bind(Array.prototype.filter);
85
+ const MapGet = Function.prototype.call.bind(Map.prototype.get);
86
+ const MapSet = Function.prototype.call.bind(Map.prototype.set);
87
+ const MapDelete = Function.prototype.call.bind(Map.prototype.delete);
88
+ const console = {
89
+ dir: GLOBAL.console.dir,
90
+ log: GLOBAL.console.log,
91
+ info: GLOBAL.console.info,
92
+ warn: GLOBAL.console.warn,
93
+ error: GLOBAL.console.error,
94
+ debug: GLOBAL.console.debug,
95
+ clear: GLOBAL.console.clear,
96
+ trace: GLOBAL.console.trace,
97
+ assert: GLOBAL.console.assert
98
+ };
99
+ // Uncomment below for extreme debugging
100
+ //for (const k in console) console[k as keyof typeof console] = GLOBAL.console.trace;
101
+ const IS_DEBUG = process.argv.includes('--debug');
102
+ const debuglog = IS_DEBUG ? (...args)=>console.debug($.dim + 'DEBUG:', ...args, $.reset) : ()=>void 0;
103
+ //const SLOPPY_MODE = process.argv.includes('--sloppy');
104
+ const NO_HISTORY = process.env.BUN_REPL_NO_HISTORY || process.argv.includes('--no-history');
105
+ // Node port: TS `enum` is not supported by Node's strip-only TS loader, so the
106
+ // modifier bitmask enum is expressed as a const object (same semantics).
107
+ const Modifier = {
108
+ NONE: 0b000,
109
+ CTRL: 0b001,
110
+ ALT: 0b010,
111
+ SHIFT: 0b100,
112
+ CTRL_ALT: 0b001 | 0b010,
113
+ CTRL_SHIFT: 0b001 | 0b100,
114
+ ALT_SHIFT: 0b010 | 0b100,
115
+ CTRL_ALT_SHIFT: 0b001 | 0b010 | 0b100
116
+ };
117
+ /** Convert a {@link WebSocket.onmessage} `event.data` value to a string. */ function wsDataToString(data) {
118
+ if (data instanceof ArrayBuffer) return new TextDecoder('utf-8').decode(data);
119
+ if (data instanceof Buffer || isBuffer(data)) return BufferToString(data, 'utf-8');
120
+ else return data;
121
+ }
122
+ // Note: This is a custom REPLServer, not the Node.js node:repl module one.
123
+ class REPLServer extends WebSocket {
124
+ constructor(){
125
+ const server = serve({
126
+ inspector: true,
127
+ development: true,
128
+ port: process.env.BUN_REPL_PORT ?? 0,
129
+ // @ts-expect-error stub
130
+ fetch () {}
131
+ });
132
+ super(`ws://${server.hostname}:${server.port}/bun:inspect`), /** Incrementing current request ID */ this.#reqID = 0, /** Queue of pending requests promises to resolve, mapped by request ID */ this.#pendingReqs = new Map(), /** Must be awaited before using the REPLServer */ this.ready = new Promise((resolve)=>{
133
+ // It's okay to not use primordials here since this only runs once before users can use the REPL
134
+ this.onopen = ()=>void this.request('Runtime.enable', {}).then(()=>this.rawEval('globalThis')).then(({ result })=>{
135
+ this.#globalObjectID = result.objectId;
136
+ // node port: skip repeated global setup (see REPL_GLOBALS_READY)
137
+ if (REPL_GLOBALS_READY) {
138
+ resolve();
139
+ return;
140
+ }
141
+ GLOBAL.Proxy = $Proxy;
142
+ Object.defineProperty(GLOBAL, '_', {
143
+ value: undefined,
144
+ writable: true,
145
+ configurable: true
146
+ }); // node port: configurable for repeated start()
147
+ Object.defineProperty(GLOBAL, '_error', {
148
+ value: undefined,
149
+ writable: true,
150
+ configurable: true
151
+ }); // node port: configurable for repeated start()
152
+ Object.defineProperty(GLOBAL, 'repl', {
153
+ value: repl,
154
+ writable: true,
155
+ configurable: true
156
+ }); // node port: configurable for repeated start()
157
+ // import.meta.resolveSync takes a *file* path for the parent.
158
+ // Bun.resolveSync takes a *directory* path for the parent.
159
+ const { resolveSync } = Bun;
160
+ const ArrayIncludes = Function.prototype.call.bind(Array.prototype.includes);
161
+ const nodePrefixedModules = repl.builtinModules.filter((x)=>x[0] !== '_' && !x.includes(':') && ![
162
+ 'undici',
163
+ 'ws',
164
+ 'detect-libc',
165
+ 'bun'
166
+ ].includes(x));
167
+ // eslint-disable-next-line unicorn/prefer-module
168
+ const originalRequire = metaRequire; // node port: ESM has no ambient `require` (Bun did)
169
+ Object.defineProperty(GLOBAL, 'require', {
170
+ value: function require(moduleID) {
171
+ if (ArrayIncludes(nodePrefixedModules, moduleID)) moduleID = `node:${moduleID}`;
172
+ if (moduleID === 'node:repl') return repl; // polyfill
173
+ if (moduleID === 'bun') return bun; // workaround
174
+ const here = cwd();
175
+ try {
176
+ moduleID = resolveSync(moduleID, here);
177
+ } catch {
178
+ // TODO: attempt to load the module from the global directory if it's not found in the local directory
179
+ throw {
180
+ name: 'ResolveError',
181
+ message: `Cannot find module "${moduleID}" from "${join(here, swcrc.filename)}"`,
182
+ specifier: moduleID
183
+ };
184
+ }
185
+ debuglog(`Importing: ${$.blueBright + moduleID + $.reset}`);
186
+ try {
187
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
188
+ return metaRequire(moduleID);
189
+ } catch (e) {
190
+ const err = e;
191
+ if (err instanceof TypeError && StringPrototypeIncludes(err.message, 'require() async module')) {
192
+ err.stack = '';
193
+ }
194
+ throw err;
195
+ }
196
+ },
197
+ writable: true,
198
+ configurable: true
199
+ }); // node port: Bun exited the process after one shot; the Node port returns, so allow redefinition
200
+ Object.defineProperties(GLOBAL.require, {
201
+ resolve: {
202
+ value: function resolve(moduleID, { paths = [
203
+ '.'
204
+ ] } = {}) {
205
+ if (paths.length === 0) paths.push('.');
206
+ const base = cwd();
207
+ for (const path of paths){
208
+ const from = pathresolve(base, path);
209
+ try {
210
+ return resolveSync(moduleID, from);
211
+ } catch {
212
+ continue;
213
+ }
214
+ }
215
+ throw {
216
+ name: 'ResolveError',
217
+ message: `Cannot find module "${moduleID}"`,
218
+ specifier: moduleID
219
+ };
220
+ }
221
+ },
222
+ main: {
223
+ value: Reflect.get(originalRequire, 'main')
224
+ },
225
+ extensions: {
226
+ value: Reflect.get(originalRequire, 'extensions')
227
+ },
228
+ cache: {
229
+ value: Reflect.get(originalRequire, 'cache')
230
+ }
231
+ });
232
+ GLOBAL.require.resolve.paths = function paths() {
233
+ return [];
234
+ }; // Bun's polyfill of this function is also like this for now
235
+ const REQUIRE = GLOBAL.require;
236
+ for (const module of nodePrefixedModules){
237
+ if (module.includes('/')) continue;
238
+ if ([
239
+ 'crypto',
240
+ 'repl',
241
+ 'process',
242
+ 'console'
243
+ ].includes(module)) continue;
244
+ const descriptor = {
245
+ cached: null
246
+ };
247
+ const getter = (function() {
248
+ if (this.cached) return this.cached;
249
+ return this.cached = REQUIRE(module);
250
+ }).bind(descriptor);
251
+ descriptor.get = getter;
252
+ Object.defineProperty(GLOBAL, module, descriptor);
253
+ }
254
+ for (const module of repl.builtinModules.filter((x)=>x.startsWith('bun:'))){
255
+ if (module.includes('/')) continue;
256
+ if ([
257
+ 'bun:main',
258
+ 'bun:wrap'
259
+ ].includes(module)) continue;
260
+ const descriptor = {
261
+ cached: null
262
+ };
263
+ const getter = (function() {
264
+ if (this.cached) return this.cached;
265
+ return this.cached = REQUIRE(module);
266
+ }).bind(descriptor);
267
+ descriptor.get = getter;
268
+ Object.defineProperty(GLOBAL, module.slice(4), descriptor);
269
+ }
270
+ // Yes, if someone types a 0xFFFF characters line, they will fill up the buffer.
271
+ // But that's very unlikely to happen, and if it does, it will just cutoff the line.
272
+ // Anyway this just a temporary workaround for https://github.com/oven-sh/bun/issues/5267
273
+ const promptReuseBuffer = Buffer.allocUnsafe(0xFFFF);
274
+ globalThis.prompt = function prompt(question = 'Prompt', defaultValue = null) {
275
+ stdoutWrite(question + ' ');
276
+ let i = -1;
277
+ // eslint-disable-next-line no-constant-condition
278
+ while(true){
279
+ // This currently relies on https://github.com/oven-sh/bun/issues/5305
280
+ // If that bug is fixed, this will break one way or another.
281
+ const read = readSync(0, promptReuseBuffer, {
282
+ length: 1,
283
+ offset: ++i
284
+ });
285
+ if (read !== 1) {
286
+ if (read === 0) {
287
+ stdoutWrite('\n');
288
+ return BufferToString(promptReuseBuffer, 'utf8', 0, i) || defaultValue;
289
+ } else throw new Error('Unexpected read length'); // This will tell us if the bug is fixed.
290
+ }
291
+ const char = promptReuseBuffer[i];
292
+ if (char === 3) {
293
+ stdoutWrite('^C\n');
294
+ exit(0);
295
+ }
296
+ if (char === 4) {
297
+ stdoutWrite('\n');
298
+ return defaultValue;
299
+ }
300
+ if (char === 27) {
301
+ stdoutWrite('^[');
302
+ continue;
303
+ }
304
+ if (char === 127) {
305
+ i--;
306
+ if (i < 0) continue;
307
+ stdoutWrite('\b \b');
308
+ if (promptReuseBuffer[i] === 27) stdoutWrite('\b \b');
309
+ i--;
310
+ continue;
311
+ }
312
+ stdoutWrite(BufferToString(promptReuseBuffer, 'utf8', i, i + 1));
313
+ if (char === 13 || char === 10) {
314
+ stdoutWrite('\n');
315
+ return BufferToString(promptReuseBuffer, 'utf8', 0, i) || defaultValue;
316
+ }
317
+ }
318
+ };
319
+ Object.defineProperty(GLOBAL, '@@bunReplRuntimeHelpers', {
320
+ value: Object.freeze({
321
+ join,
322
+ dirname,
323
+ basename,
324
+ resolve: pathresolve,
325
+ getcwd: process.cwd,
326
+ pathToFileURL: Bun.pathToFileURL,
327
+ fileURLToPath: Bun.fileURLToPath,
328
+ StringStartsWith: Function.prototype.call.bind(String.prototype.startsWith),
329
+ ObjectFreeze: Object.freeze
330
+ })
331
+ });
332
+ Object.defineProperty(GLOBAL, 'eval', {
333
+ value: eval,
334
+ configurable: false,
335
+ writable: false
336
+ }); // used by inlined import.meta trick
337
+ Object.defineProperty(GLOBAL, 'Object', {
338
+ value: Object,
339
+ configurable: false,
340
+ writable: false
341
+ }); // used by swc
342
+ Object.freeze(Object); // bun's node:events polyfill relies on this
343
+ Object.freeze(Promise); // must preserve .name property
344
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
345
+ Object.freeze(Promise.prototype); // too many possible pitfalls
346
+ //? Workarounds for bug: https://canary.discord.com/channels/876711213126520882/888839314056839309/1120394929164779570
347
+ const TypedArray = Object.getPrototypeOf(Uint8Array);
348
+ const wrapIterator = (iterable, key = Symbol.iterator, name = iterable.name + ' Iterator')=>{
349
+ const original = Reflect.get(iterable.prototype, key);
350
+ Reflect.set(iterable.prototype, key, function(...argz) {
351
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
352
+ const thiz = this;
353
+ function* wrappedIter() {
354
+ yield* FunctionApply(original, thiz, argz);
355
+ }
356
+ return ObjectDefineProperty(wrappedIter(), SymbolToStringTag, {
357
+ value: name,
358
+ configurable: true
359
+ });
360
+ });
361
+ };
362
+ wrapIterator(Array);
363
+ wrapIterator(Array, 'keys');
364
+ wrapIterator(Array, 'values');
365
+ wrapIterator(Array, 'entries');
366
+ wrapIterator(TypedArray, Symbol.iterator, 'Array Iterator');
367
+ wrapIterator(TypedArray, 'entries', 'Array Iterator');
368
+ wrapIterator(TypedArray, 'values', 'Array Iterator');
369
+ wrapIterator(TypedArray, 'keys', 'Array Iterator');
370
+ wrapIterator(String);
371
+ wrapIterator(Map);
372
+ wrapIterator(Map, 'keys');
373
+ wrapIterator(Map, 'values');
374
+ wrapIterator(Map, 'entries');
375
+ wrapIterator(Set);
376
+ wrapIterator(Set, 'keys');
377
+ wrapIterator(Set, 'values');
378
+ wrapIterator(Set, 'entries');
379
+ REPL_GLOBALS_READY = true;
380
+ resolve();
381
+ });
382
+ });
383
+ debuglog(`[ws/open] repl server listening on ${$.blueBright}ws://${server.hostname}:${server.port}/bun:inspect`);
384
+ this.onmessage = (event)=>{
385
+ try {
386
+ const data = JSONParse(wsDataToString(event.data));
387
+ const { id } = data;
388
+ const promiseRef = MapGet(this.#pendingReqs, id);
389
+ if (promiseRef) {
390
+ MapDelete(this.#pendingReqs, id);
391
+ if ('error' in data) promiseRef.reject(data.error);
392
+ else if ('result' in data) promiseRef.resolve(data.result);
393
+ else throw `Received response with no result or error: ${id}`;
394
+ } else throw `Received message for unknown request ID: ${id}`;
395
+ } catch (err) {
396
+ console.error(`[ws/message] An unexpected error occured:`, err, '\nReceived Data:', event.data);
397
+ }
398
+ };
399
+ this.onclose = ()=>console.info('[ws/close] disconnected');
400
+ this.onerror = (error)=>console.error('[ws/error]', error);
401
+ }
402
+ #reqID;
403
+ /** Object ID of the global object */ #globalObjectID;
404
+ #pendingReqs;
405
+ /** Check and assert typeof for a remote object */ typeof(v, expected) {
406
+ return v.type === expected;
407
+ }
408
+ /** Check and assert subtypeof for a remote object */ subtypeof(v, expected) {
409
+ return v.subtype === expected;
410
+ }
411
+ /** Send a direct request to the inspector */ request(method, params) {
412
+ const req = {
413
+ id: ++this.#reqID,
414
+ method,
415
+ params
416
+ };
417
+ const response = new Promise((resolve, reject)=>{
418
+ MapSet(this.#pendingReqs, this.#reqID, {
419
+ resolve: resolve,
420
+ reject
421
+ });
422
+ }).catch((err)=>{
423
+ throw ObjectAssign(new Error, err);
424
+ });
425
+ this.send(JSONStringify(req));
426
+ return response;
427
+ }
428
+ /** Direct shortcut for a `Runtime.evaluate` request */ async rawEval(code) {
429
+ return this.request('Runtime.evaluate', {
430
+ expression: code,
431
+ generatePreview: true
432
+ });
433
+ }
434
+ /** Run a snippet of code in the REPL */ async eval(code, topLevelAwaited = false, extraOut) {
435
+ debuglog(`transpiled code: ${StringTrim(code)}`);
436
+ const { result, wasThrown: thrown } = await this.rawEval(code);
437
+ let remoteObj = result;
438
+ remoteObj.wasThrown = thrown;
439
+ if (result.type === 'object') ObjectTypeHandler: {
440
+ if (result.subtype === 'null') break ObjectTypeHandler;
441
+ if (!result.objectId) throw new EvalError(`Received non-null object without objectId: ${JSONStringify(result)}`);
442
+ if (result.className === 'Promise') {
443
+ if (!result.preview) throw new EvalError(`Received Promise object without preview: ${JSONStringify(result)}}`);
444
+ if (topLevelAwaited) {
445
+ const awaited = await this.request('Runtime.awaitPromise', {
446
+ promiseObjectId: result.objectId,
447
+ generatePreview: false
448
+ });
449
+ remoteObj = awaited.result;
450
+ remoteObj.wasThrown = awaited.wasThrown;
451
+ if (remoteObj.type === 'undefined') {
452
+ console.warn($.yellow + $.dim + '[!] REPL top-level await is still very experimental and prone to failing on complex code snippets.\n' + ' You are seeing this because top-level await usage was detected with undefined as the result, if that was expected, you can ignore this.' + $.reset);
453
+ }
454
+ }
455
+ if (result.preview.properties && ArrayPrototypeFind(result.preview.properties, (p)=>p.name === 'status')?.value === 'rejected') {
456
+ remoteObj.wasRejectedPromise = true;
457
+ }
458
+ break ObjectTypeHandler;
459
+ }
460
+ }
461
+ //! bug workaround, bigints are being passed as undefined to Runtime.callFunctionOn (?)
462
+ if (remoteObj.type === 'bigint') {
463
+ if (!remoteObj.description) throw new EvalError(`Received BigInt value without description: ${JSONStringify(remoteObj)}`);
464
+ const value = BigInt(StringPrototypeSlice(remoteObj.description, 0, -1));
465
+ ReflectSet(GLOBAL, remoteObj.wasThrown ? '_error' : '_', value);
466
+ return (remoteObj.wasThrown ? $.red + 'Uncaught ' + $.reset : '') + SafeInspect(value, // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
467
+ ReflectGet(GLOBAL, 'repl')?.writer?.options ?? {
468
+ colors: Bun.enableANSIColors,
469
+ showProxy: true
470
+ });
471
+ }
472
+ //! bug workaround, Infinity and NaN are being passed as null to Runtime.callFunctionOn (?)
473
+ // also -0 is being passed as 0
474
+ if (remoteObj.type === 'number') {
475
+ if (!remoteObj.description) throw new EvalError(`Received Number value without description: ${JSONStringify(remoteObj)}`);
476
+ let value = remoteObj.value;
477
+ if (remoteObj.description === 'Infinity') value = Infinity;
478
+ else if (remoteObj.description === '-Infinity') value = -Infinity;
479
+ else if (remoteObj.description === 'NaN') value = NaN;
480
+ else if (remoteObj.description === '-0') value = -0;
481
+ ReflectSet(GLOBAL, remoteObj.wasThrown ? '_error' : '_', value);
482
+ return (remoteObj.wasThrown ? $.red + 'Uncaught ' + $.reset : '') + SafeInspect(value, // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
483
+ ReflectGet(GLOBAL, 'repl')?.writer?.options ?? {
484
+ colors: Bun.enableANSIColors,
485
+ showProxy: true
486
+ });
487
+ }
488
+ const { wasThrown } = remoteObj;
489
+ const REPL_INTERNALS = '@@bunReplInternals';
490
+ ObjectDefineProperty(GLOBAL, REPL_INTERNALS, {
491
+ value: {
492
+ SafeInspect,
493
+ SafeGet,
494
+ StringReplace,
495
+ bunInspect
496
+ },
497
+ configurable: true
498
+ });
499
+ const inspected = await this.request('Runtime.callFunctionOn', {
500
+ objectId: this.#globalObjectID,
501
+ functionDeclaration: `(v) => {
502
+ const { SafeInspect, SafeGet, StringReplace, bunInspect } = this['${REPL_INTERNALS}'];
503
+ if (!${wasThrown}) this._ = v;
504
+ else this._error = v;
505
+ if (v?.name === 'ResolveError')
506
+ return \`${$.red}ResolveError${$.reset}${$.dim}: ${$.reset}${$.whiteBright}\${StringReplace(
507
+ SafeGet(v, 'message') || \`Failed to resolve import "?" from "?"\`, / ".+" from ".+"$/,
508
+ \` ${$.blueBright}"\${SafeGet(v, 'specifier') ?? '<unresolved>'}"${$.whiteBright} from ${$.cyan + cwd()}/${swcrc.filename}\`
509
+ )}${$.reset}\`;
510
+ if (${remoteObj.subtype === 'error'}) return bunInspect(v, { colors: ${Bun.enableANSIColors} });
511
+ return SafeInspect(v, this.repl?.writer?.options ?? { colors: ${Bun.enableANSIColors}, showProxy: true });
512
+ }`,
513
+ arguments: [
514
+ remoteObj
515
+ ]
516
+ });
517
+ ReflectDeleteProperty(GLOBAL, REPL_INTERNALS);
518
+ if (inspected.wasThrown) throw new EvalError(`Failed to inspect object: ${JSONStringify(inspected)}`);
519
+ if (!this.typeof(inspected.result, 'string')) throw new EvalError(`Received non-string inspect result: ${JSONStringify(inspected)}`);
520
+ if (extraOut) {
521
+ if (wasThrown) extraOut.errored = true;
522
+ if (remoteObj.wasRejectedPromise) extraOut.noPrintError = true;
523
+ }
524
+ if (wasThrown && remoteObj.subtype !== 'error') return $.red + 'Uncaught ' + $.reset + inspected.result.value;
525
+ return inspected.result.value;
526
+ }
527
+ }
528
+ async function loadHistoryData() {
529
+ if (NO_HISTORY) return {
530
+ path: '',
531
+ lines: []
532
+ };
533
+ let out;
534
+ if (process.env.XDG_DATA_HOME && (out = await tryLoadHistory(process.env.XDG_DATA_HOME, 'bun'))) return out;
535
+ else if (process.env.BUN_INSTALL && (out = await tryLoadHistory(process.env.BUN_INSTALL))) return out;
536
+ else {
537
+ debuglog('Trying to load history from fallback location at home directory.');
538
+ const homedir = os.homedir();
539
+ return await tryLoadHistory(homedir) ?? {
540
+ path: join(homedir, '.bun_repl_history'),
541
+ lines: []
542
+ };
543
+ }
544
+ }
545
+ async function tryLoadHistory(...dir) {
546
+ const path = join(...dir, '.bun_repl_history');
547
+ try {
548
+ debuglog(`Trying to load REPL history from ${path}`);
549
+ if (!existsSync(path)) {
550
+ debuglog(`History file not found, creating new one at ${path}`);
551
+ await write(path, '\n');
552
+ // BUG: Bun.file doesn't update the file's status after writing to it
553
+ }
554
+ debuglog(`Loading history file from ${path}`);
555
+ return {
556
+ path,
557
+ lines: readFileSync(path, 'utf8').split('\n')
558
+ };
559
+ } catch (err) {
560
+ debuglog(`Failed to load history file from ${path}\nError will be printed below:`);
561
+ if (IS_DEBUG) console.error(err);
562
+ return null;
563
+ }
564
+ }
565
+ // This only supports the most basic var/let/const declarations
566
+ const JSVarDeclRegex = /(?<keyword>var|let|const)\s+(?<varname>(?:[$_\p{ID_Start}]|\\u[\da-fA-F]{4})(?:[$\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4})*)/gu;
567
+ // Wrap the code in an async function if it contains top level await
568
+ // Make sure to return the result of the last expression
569
+ function tryProcessTopLevelAwait(src) {
570
+ const lines = StringPrototypeSplit(src, '\n');
571
+ if (!StringTrim(lines[lines.length - 1])) ArrayPrototypePop(lines);
572
+ lines[lines.length - 1] = 'return ' + lines[lines.length - 1] + ';})();';
573
+ lines[0] = '(async()=>{' + lines[0];
574
+ let hoisted = '';
575
+ const transformed = StringPrototypeReplaceAll(ArrayPrototypeJoin(lines, '\n'), JSVarDeclRegex, (m, _1, _2, idx, str, groups)=>{
576
+ const { keyword, varname } = groups;
577
+ hoisted += `${keyword === 'const' ? 'let' : keyword} ${varname};`;
578
+ return varname;
579
+ });
580
+ return hoisted + transformed;
581
+ }
582
+ async function tryGetPackageVersion() {
583
+ try {
584
+ return 'v' + (await import('../package.json')).default.version;
585
+ } catch {
586
+ return $.dim + $.redBright + 'failed to retrieve version' + $.reset;
587
+ }
588
+ }
589
+ // Regex used for ANSI escape code splitting
590
+ // Adopted from https://github.com/chalk/ansi-regex/blob/HEAD/index.js
591
+ // License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore
592
+ // Matches all ansi escape code sequences in a string
593
+ const ansiPattern = "[\\u001B\\u009B][[\\]()#;?]*" + "(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*" + "|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)" + "|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))";
594
+ const ansi = new RegExp(ansiPattern, "g");
595
+ /** Remove all VT control characters. Use to estimate displayed string width. */ function stripVTControlCharacters(str) {
596
+ return RegExpPrototypeSymbolReplace(ansi, str, '');
597
+ }
598
+ function rlRefresh(rl) {
599
+ // @ts-expect-error "internal" function
600
+ rl._refreshLine(); // eslint-disable-line @typescript-eslint/no-unsafe-call
601
+ }
602
+ function rlLineInsert(rl, insert, cutoff = 0) {
603
+ const { line, cursor } = rl;
604
+ const middle = cursor - cutoff;
605
+ const lineStart = StringPrototypeSlice(line, 0, middle < 0 ? 0 : middle);
606
+ const lineEnd = StringPrototypeSlice(line, cursor);
607
+ ReflectSet(rl, 'line', lineStart + insert + lineEnd);
608
+ ReflectSet(rl, 'cursor', cursor + insert.length - (middle < 0 ? 0 : cutoff));
609
+ rlRefresh(rl);
610
+ }
611
+ const isMac = process.platform === 'darwin';
612
+ const metaKey = (key)=>(isMac ? 'Meta+' : 'Alt+') + key + (isMac ? '' : ' ');
613
+ export default {
614
+ async start (singleshotCode, printSingleshot = false) {
615
+ try {
616
+ debuglog('Debug mode enabled.');
617
+ if (IS_DEBUG) {
618
+ debuglog(`REPL version ${await tryGetPackageVersion()} running on Bun v${Bun.version}+${Bun.revision} (${process.platform} ${process.arch})`);
619
+ debuglog(`OS Info: ${os.type()} -- ${os.release()} -- ${os.version()}`);
620
+ }
621
+ // Node port: Bun.serve binds its inspector synchronously; the Node shim's
622
+ // HTTP server binds on the next tick, so wait for it before connecting.
623
+ await inspectorReady();
624
+ const repl = new REPLServer();
625
+ await repl.ready;
626
+ debuglog('REPL server initialized.');
627
+ // TODO: How to make Bun transpiler not dead-code-eliminate lone constants like "5"?
628
+ const transpiler = new SWCTranspiler();
629
+ debuglog('Transpiler initialized.');
630
+ /*new Bun.Transpiler({
631
+ target: 'bun',
632
+ loader: 'ts',
633
+ minifyWhitespace: false,
634
+ trimUnusedImports: false,
635
+ treeShaking: false,
636
+ inline: false,
637
+ jsxOptimizationInline: false,
638
+ });*/ if (singleshotCode) {
639
+ let code = singleshotCode;
640
+ try {
641
+ code = transpiler.preprocess(code);
642
+ code = transpiler.transpile(code);
643
+ code = transpiler.postprocess(code);
644
+ } catch (e) {
645
+ const err = e;
646
+ console.error((err?.message ?? 'Unknown transpiler error.').split('\nCaused by:\n')[0].trim());
647
+ return exit(1);
648
+ }
649
+ let hasTLA = false;
650
+ if (StringPrototypeIncludes(code, 'await')) {
651
+ hasTLA = true;
652
+ code = tryProcessTopLevelAwait(code);
653
+ }
654
+ const extraInfo = {
655
+ errored: false,
656
+ noPrintError: false
657
+ };
658
+ const evaled = await repl.eval(/* ts */ `${code}`, hasTLA, extraInfo);
659
+ if (!extraInfo.noPrintError) {
660
+ if (extraInfo.errored) console.error(evaled);
661
+ else if (printSingleshot) console.log(evaled);
662
+ } else if (!extraInfo.errored && printSingleshot) console.log(evaled);
663
+ // Node port: release the inspector WebSocket so the process can exit naturally
664
+ // (Bun exited the process here; the port returns control to the caller instead).
665
+ try {
666
+ repl.close();
667
+ } catch {}
668
+ return evaled;
669
+ }
670
+ const history = await loadHistoryData();
671
+ let historySize = Number(process.env.BUN_REPL_HISTORY_SIZE ?? 1000);
672
+ if (!Number.isSafeInteger(historySize) || historySize < 1) {
673
+ console.warn(`[!] Invalid BUN_REPL_HISTORY_SIZE value "${process.env.BUN_REPL_HISTORY_SIZE}", must be a safe positive integer!\n` + ` Using the default value of 1000.`);
674
+ historySize = 1000;
675
+ }
676
+ if (NO_HISTORY) debuglog('Skipped history file loading due to --no-history flag.');
677
+ else debuglog(`REPL history data loaded: (${history.lines.length} lines) ${history.path}`);
678
+ const sessionHistoryNoErrors = [];
679
+ if (!process.stdin.isTTY) {
680
+ console.error('[!] Failed to start REPL interface! Is the command running in an interactive terminal?');
681
+ return exit(1);
682
+ }
683
+ const rl = readline.createInterface({
684
+ input: process.stdin,
685
+ output: process.stdout,
686
+ terminal: true,
687
+ tabSize: 4,
688
+ prompt: process.env.BUN_REPL_PROMPT ?? '> ',
689
+ historySize: historySize,
690
+ history: history.lines
691
+ });
692
+ debuglog('readline interface created.');
693
+ process.on('exit', ()=>{
694
+ rl.close();
695
+ });
696
+ console.log(`Welcome to Bun v${Bun.version}\nType ".help" for more information.`);
697
+ console.warn(`${$.yellow + $.dim}[!] Please note that the REPL implementation is still experimental!\n` + ` Don't consider it to be representative of the stability or behavior of Bun overall.${$.reset}`);
698
+ //* Only primordials should be used beyond this point!
699
+ const multiline = {
700
+ enabled: false,
701
+ lines: []
702
+ };
703
+ const toggleMultiline = ()=>{
704
+ multiline.enabled = !multiline.enabled;
705
+ multiline.lines = [];
706
+ if (multiline.enabled) {
707
+ rl.setPrompt(`${$.purple}(m)${$.reset} ` + rl.getPrompt());
708
+ console.log(StringPadEnd(`\r${$.gray}Multi-line mode enabled. End a line with "${$.whiteBright}.${$.gray}" to send.${$.reset}`, rl.line.length + rl.getPrompt().length) + StringRepeat('\n', [
709
+ ...StringMatchAll(rl.line, '\n')
710
+ ].length));
711
+ } else {
712
+ rl.setPrompt(process.env.BUN_REPL_PROMPT ?? '> ');
713
+ console.log(StringPadEnd(`\r${$.gray}Multi-line mode disabled.${$.reset}`, rl.line.length + rl.getPrompt().length) + StringRepeat('\n', [
714
+ ...StringMatchAll(rl.line, '\n')
715
+ ].length));
716
+ }
717
+ rlRefresh(rl);
718
+ };
719
+ process.stdin.on('keypress', (char, key)=>{
720
+ let modifier = Modifier.NONE;
721
+ if (key.ctrl) modifier |= Modifier.CTRL;
722
+ if (key.meta) modifier |= Modifier.ALT;
723
+ if (key.shift) modifier |= Modifier.SHIFT;
724
+ if (modifier === Modifier.NONE) {
725
+ if (key.name === 'tab') {
726
+ // refuse to place the tab in preparation for autocompletion
727
+ return rlLineInsert(rl, '', 1);
728
+ }
729
+ } else if (modifier === Modifier.SHIFT) switch(key.name){
730
+ case 'tab':
731
+ {
732
+ rlLineInsert(rl, ' ');
733
+ }
734
+ break;
735
+ default:
736
+ return;
737
+ }
738
+ else if (modifier === Modifier.ALT) switch(key.name){
739
+ case 'n':
740
+ {
741
+ if (!multiline.enabled) rlLineInsert(rl, '\n');
742
+ else {
743
+ const { line, cursor } = rl;
744
+ ReflectSet(rl, 'line', StringPrototypeSlice(line, 0, cursor));
745
+ rlRefresh(rl);
746
+ rl.write('\n');
747
+ ReflectSet(rl, 'line', StringPrototypeSlice(line, cursor));
748
+ rlRefresh(rl);
749
+ }
750
+ }
751
+ break;
752
+ case 'm':
753
+ {
754
+ toggleMultiline();
755
+ }
756
+ break;
757
+ default:
758
+ return;
759
+ }
760
+ else if (modifier === Modifier.CTRL) switch(key.name){
761
+ default:
762
+ return;
763
+ }
764
+ else if (modifier === Modifier.ALT_SHIFT) switch(key.name){
765
+ // TODO: readline.moveCursor is broken ("TypeError: undefined is not a function")
766
+ case 'up':
767
+ {
768
+ //readline.moveCursor(process.stdin, 0, -1, () => void 0);
769
+ }
770
+ break;
771
+ case 'down':
772
+ {
773
+ //readline.moveCursor(process.stdin, 0, 1, () => void 0);
774
+ }
775
+ break;
776
+ default:
777
+ return;
778
+ }
779
+ });
780
+ rl.on('SIGINT', ()=>{
781
+ if (rl.line.length === 0) rl.close();
782
+ else {
783
+ console.log('');
784
+ ReflectSet(rl, 'line', '');
785
+ rl.prompt();
786
+ }
787
+ });
788
+ rl.on('close', ()=>{
789
+ if (!NO_HISTORY) write(history.path, ArrayPrototypeJoin(ArrayPrototypeFilter(history.lines, (l)=>l !== '.exit'), '\n')).catch(()=>console.warn(`[!] Failed to save REPL history to ${history.path}!`));
790
+ console.log(''); // ensure newline
791
+ exit(0);
792
+ });
793
+ rl.on('history', (newHistory)=>{
794
+ history.lines = newHistory;
795
+ });
796
+ rl.on('line', async (line, { loadingFile = false } = {})=>{
797
+ line = StringTrim(line);
798
+ if (!line) return rl.prompt();
799
+ if (!loadingFile && line[0] === '.' && multiline.lines.length === 0 && !RegExpTest(/\d/, line[1])) {
800
+ const replCmd = StringPrototypeSplit(line, /\s+/g);
801
+ switch(replCmd[0]){
802
+ case '.help':
803
+ {
804
+ console.log(`Commands & keybinds:\n` + ` .help Show this help message.\n` + ` .info Print extra REPL information.\n` + ` .multiline Toggle multi-line mode. ${$.gray}(${metaKey('M').trim()})${$.reset}\n` + ` .save Save all successful commands evaluated in this REPL session to a file.\n` + ` .load Load a file into the REPL session. ${$.yellow}(Experimental)${$.reset}\n` + ` .clear Clear the screen. ${$.gray}(Ctrl+L)${$.reset}\n` + ` .exit Exit the REPL. ${$.gray}(Ctrl+C / Ctrl+D)${$.reset}\n` + `\n` + ` ${metaKey('N')} Insert a raw newline at cursor position, works even in single-line mode.\n` + ` ${$.dim}* In multi-line mode, ${$.noDim + $.gray}Enter${$.reset + $.dim} can only append newline to the end of the input.${$.reset}\n` + ` ${metaKey('M')} Toggle multi-line mode.\n` + ` Shift+Tab Insert an indent instead of triggering autocompletions (autocomplete not yet implemented).` + (!isMac ? '' : `\n\n${$.dim}[?] MacOS users: The ${$.noDim + $.gray}Meta${$.reset + $.dim} key defaults to ${$.noDim + $.gray}Esc${$.reset + $.dim}, ` + `but may also be mapped to ${$.noDim + $.gray}Option${$.reset + $.dim} based on your terminal settings.${$.reset}`));
805
+ }
806
+ break;
807
+ case '.info':
808
+ {
809
+ console.log(`Running on Bun v${Bun.version} ${$.gray}(${Bun.revision})${$.reset}\n` + ` REPL version: ${await tryGetPackageVersion()}\n` + ` Color mode: ${Bun.enableANSIColors ? `${$.greenBright}Enabled` : 'Disabled'}${$.reset}\n` + ` Debug mode: ${IS_DEBUG ? `${$.greenBright}Enabled` : $.dim + 'Disabled'}${$.reset}`);
810
+ }
811
+ break;
812
+ case '.multiline':
813
+ {
814
+ toggleMultiline();
815
+ }
816
+ break;
817
+ case '.load':
818
+ {
819
+ const filepath = replCmd[1];
820
+ if (!filepath) {
821
+ console.log(`${$.red}Missing argument, usage: ${$.whiteBright}.load <filepath>${$.reset}`);
822
+ break;
823
+ }
824
+ const resolved = pathresolve(filepath);
825
+ try {
826
+ const contents = readFileSync(resolved, 'utf8');
827
+ console.warn(`${$.yellow + $.dim}[!] Loading files into the REPL is experimental and may not work as expected.${$.reset}`);
828
+ rl.emit('line', contents, {
829
+ loadingFile: true
830
+ });
831
+ } catch (e) {
832
+ const err = e;
833
+ console.error(`Failed to load file ${$.cyan}${resolved}${$.red}: ${err.message ?? 'Unknown error'}${$.reset}`);
834
+ if (IS_DEBUG) console.error(err);
835
+ break;
836
+ }
837
+ }
838
+ break;
839
+ case '.save':
840
+ {
841
+ const filepath = replCmd[1];
842
+ if (!filepath) {
843
+ console.log(`${$.red}Missing argument, usage: ${$.whiteBright}.save <filepath>${$.reset}`);
844
+ break;
845
+ }
846
+ const resolved = pathresolve(filepath);
847
+ const contents = ArrayPrototypeJoin(sessionHistoryNoErrors, '\n');
848
+ try {
849
+ await write(resolved, contents);
850
+ } catch (e) {
851
+ const err = e;
852
+ console.error(`Failed to save REPL session to ${$.cyan}${resolved}${$.red}: ${err.message ?? 'Unknown error'}${$.reset}`);
853
+ if (IS_DEBUG) console.error(err);
854
+ break;
855
+ }
856
+ console.log(`Saved REPL session to: ${$.cyan}${resolved}${$.reset + $.dim} (${contents.length} chars)${$.reset}`);
857
+ }
858
+ break;
859
+ case '.clear':
860
+ {
861
+ console.clear();
862
+ }
863
+ break;
864
+ case '.exit':
865
+ {
866
+ rl.close();
867
+ }
868
+ break;
869
+ default:
870
+ {
871
+ console.log(`${$.red}Unknown REPL command "${$.whiteBright}${line}${$.red}", ` + `type "${$.whiteBright}.help${$.red}" for more information.${$.reset}`);
872
+ }
873
+ break;
874
+ }
875
+ } else {
876
+ if (multiline.enabled && !loadingFile) {
877
+ if (line[line.length - 1] === '.') {
878
+ ArrayPush(multiline.lines, StringPrototypeSlice(line, 0, -1));
879
+ line = ArrayPrototypeJoin(multiline.lines, '\n');
880
+ multiline.lines = [];
881
+ rl.setPrompt(`${$.purple}(m)${$.reset} ` + (process.env.BUN_REPL_PROMPT ?? '> '));
882
+ //rlRefresh(rl);
883
+ } else {
884
+ ArrayPush(multiline.lines, line);
885
+ const promptLineNo = `${$.dim}${multiline.lines.length + 1} | ${$.reset}`;
886
+ const stripped = stripVTControlCharacters(promptLineNo);
887
+ const padded = StringPadStart(stripped, stripVTControlCharacters(rl.getPrompt()).length);
888
+ rl.setPrompt(StringRepeat(' ', padded.length - stripped.length) + promptLineNo);
889
+ rlRefresh(rl);
890
+ return;
891
+ }
892
+ }
893
+ const backupPrompt = rl.getPrompt();
894
+ if (loadingFile) rl.setPrompt('');
895
+ let code = line;
896
+ try {
897
+ if (RegExpTest(/^\s*{/, code) && !RegExpTest(/;\s*$/, code)) code = `(${code})`;
898
+ code = transpiler.preprocess(code);
899
+ code = transpiler.transpile(code);
900
+ code = transpiler.postprocess(code);
901
+ } catch (e) {
902
+ const err = e;
903
+ if (err.stack?.includes('@swc/core') || err.stack?.includes('@ohos-ports/swc-core')) {
904
+ console.error('Internal failure due to global builtins tampering, this is likely not a bug but a temporary limitation of the REPL.\n' + 'Please do not report this and avoid tampering with the global builtins in the REPL.\n' + 'If you didn\'t tamper with the global builtins, please report this as a bug.');
905
+ if (IS_DEBUG) console.error(e);
906
+ exit(0);
907
+ }
908
+ console.error(StringTrim(StringPrototypeSplit(err?.message ?? 'Unknown transpiler error.', '\nCaused by:\n')[0]));
909
+ if (IS_DEBUG) console.error(e);
910
+ rl.prompt();
911
+ return;
912
+ }
913
+ let hasTLA = false;
914
+ if (StringPrototypeIncludes(code, 'await')) {
915
+ hasTLA = true;
916
+ code = tryProcessTopLevelAwait(code);
917
+ }
918
+ const extraInfo = {
919
+ errored: false,
920
+ noPrintError: false
921
+ };
922
+ const evaled = await repl.eval(/* ts */ `${code}`, hasTLA, extraInfo);
923
+ if (!extraInfo.noPrintError) {
924
+ if (extraInfo.errored) console.error(evaled);
925
+ else {
926
+ console.log(evaled);
927
+ ArrayPush(sessionHistoryNoErrors, line);
928
+ }
929
+ } else if (!extraInfo.errored) {
930
+ console.log(evaled);
931
+ ArrayPush(sessionHistoryNoErrors, line);
932
+ }
933
+ if (loadingFile) rl.setPrompt(backupPrompt);
934
+ }
935
+ rl.prompt();
936
+ });
937
+ debuglog('readline interface event handlers registered.');
938
+ rl.prompt();
939
+ } catch (err) {
940
+ console.error('Internal REPL Error:');
941
+ console.error(err, '\nThis should not happen! Search GitHub issues https://bun.sh/issues or ask for #help in https://bun.sh/discord');
942
+ exit(1);
943
+ }
944
+ }
945
+ };