@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.
@@ -0,0 +1,216 @@
1
+ const createSafeIterator = (factory, next) => {
2
+ class SafeIterator {
3
+ constructor(iterable) {
4
+ this._iterator = factory(iterable);
5
+ }
6
+ next() {
7
+ return next(this._iterator);
8
+ }
9
+ [Symbol.iterator]() {
10
+ return this;
11
+ }
12
+ }
13
+ Object.setPrototypeOf(SafeIterator.prototype, null);
14
+ Object.freeze(SafeIterator.prototype);
15
+ Object.freeze(SafeIterator);
16
+ return SafeIterator;
17
+ };
18
+
19
+ function getGetter(cls, getter) {
20
+ // TODO: __lookupGetter__ is deprecated, but Object.getOwnPropertyDescriptor doesn't work on built-ins like Typed Arrays.
21
+ return Function.prototype.call.bind(cls.prototype.__lookupGetter__(getter));
22
+ }
23
+
24
+ function getterCaller(getter) {
25
+ return val => {
26
+ return val.constructor.prototype.__lookupGetter__(getter).call(val);
27
+ };
28
+ }
29
+
30
+ function uncurryThis(func) {
31
+ return Function.prototype.call.bind(func);
32
+ }
33
+
34
+ const copyProps = (src, dest) => {
35
+ Array.prototype.forEach.call(Reflect.ownKeys(src), key => {
36
+ if (!Reflect.getOwnPropertyDescriptor(dest, key)) {
37
+ Reflect.defineProperty(dest, key, /** @type {*} */(Reflect.getOwnPropertyDescriptor(src, key)));
38
+ }
39
+ });
40
+ };
41
+
42
+ const makeSafe = (unsafe, safe) => {
43
+ if (Symbol.iterator in unsafe.prototype) {
44
+ const dummy = new unsafe();
45
+ let next; // We can reuse the same `next` method.
46
+
47
+ Array.prototype.forEach.call(Reflect.ownKeys(unsafe.prototype), key => {
48
+ if (!Reflect.getOwnPropertyDescriptor(safe.prototype, key)) {
49
+ const desc = /** @type {*} */(Reflect.getOwnPropertyDescriptor(unsafe.prototype, key));
50
+ if (
51
+ typeof desc.value === "function" &&
52
+ desc.value.length === 0 &&
53
+ Symbol.iterator in (Function.prototype.call.call(desc.value, dummy) || {})
54
+ ) {
55
+ const createIterator = uncurryThis(desc.value);
56
+ next ??= uncurryThis(createIterator(dummy).next);
57
+ const SafeIterator = createSafeIterator(createIterator, next);
58
+ desc.value = function () {
59
+ return new SafeIterator(this);
60
+ };
61
+ }
62
+ Reflect.defineProperty(safe.prototype, key, desc);
63
+ }
64
+ });
65
+ } else copyProps(unsafe.prototype, safe.prototype);
66
+ copyProps(unsafe, safe);
67
+
68
+ Object.setPrototypeOf(safe.prototype, null);
69
+ Object.freeze(safe.prototype);
70
+ Object.freeze(safe);
71
+ return safe;
72
+ };
73
+
74
+ const StringIterator = Function.prototype.call.bind(String.prototype[Symbol.iterator]);
75
+ const StringIteratorPrototype = /** @type {*} */(Reflect.getPrototypeOf(StringIterator("")));
76
+
77
+ const StringPrototypeReplace = Function.prototype.call.bind(String.prototype.replace);
78
+ const Error = globalThis.Error;
79
+ function ErrorCaptureStackTrace(targetObject) {
80
+ const stack = new Error().stack ?? '';
81
+ // Remove the second line, which is this function
82
+ targetObject.stack = StringPrototypeReplace(stack, /.*\n.*/, "$1");
83
+ }
84
+
85
+ export default {
86
+ makeSafe, // exported for testing
87
+ Array,
88
+ ArrayFrom: Array.from,
89
+ ArrayIsArray: Array.isArray,
90
+ ArrayPrototypeFlat: Function.prototype.call.bind(Array.prototype.flat),
91
+ ArrayPrototypeFilter: Function.prototype.call.bind(Array.prototype.filter),
92
+ ArrayPrototypeForEach: Function.prototype.call.bind(Array.prototype.forEach),
93
+ ArrayPrototypeIncludes: Function.prototype.call.bind(Array.prototype.includes),
94
+ ArrayPrototypeIndexOf: Function.prototype.call.bind(Array.prototype.indexOf),
95
+ ArrayPrototypeJoin: Function.prototype.call.bind(Array.prototype.join),
96
+ ArrayPrototypeMap: Function.prototype.call.bind(Array.prototype.map),
97
+ ArrayPrototypePop: Function.prototype.call.bind(Array.prototype.pop),
98
+ ArrayPrototypePush: Function.prototype.call.bind(Array.prototype.push),
99
+ ArrayPrototypePushApply: Function.apply.bind(Array.prototype.push),
100
+ ArrayPrototypeSlice: Function.prototype.call.bind(Array.prototype.slice),
101
+ ArrayPrototypeSort: Function.prototype.call.bind(Array.prototype.sort),
102
+ ArrayPrototypeSplice: Function.prototype.call.bind(Array.prototype.splice),
103
+ ArrayPrototypeUnshift: Function.prototype.call.bind(Array.prototype.unshift),
104
+ BigIntPrototypeValueOf: Function.prototype.call.bind(BigInt.prototype.valueOf),
105
+ BooleanPrototypeValueOf: Function.prototype.call.bind(Boolean.prototype.valueOf),
106
+ DatePrototypeGetTime: Function.prototype.call.bind(Date.prototype.getTime),
107
+ DatePrototypeToISOString: Function.prototype.call.bind(Date.prototype.toISOString),
108
+ DatePrototypeToString: Function.prototype.call.bind(Date.prototype.toString),
109
+ ErrorCaptureStackTrace,
110
+ ErrorPrototypeToString: Function.prototype.call.bind(Error.prototype.toString),
111
+ FunctionPrototypeBind: Function.prototype.call.bind(Function.prototype.bind),
112
+ FunctionPrototypeCall: Function.prototype.call.bind(Function.prototype.call),
113
+ FunctionPrototypeToString: Function.prototype.call.bind(Function.prototype.toString),
114
+ JSONStringify: JSON.stringify,
115
+ MapPrototypeGetSize: getGetter(Map, "size"),
116
+ MapPrototypeEntries: Function.prototype.call.bind(Map.prototype.entries),
117
+ MapPrototypeValues: Function.prototype.call.bind(Map.prototype.values),
118
+ MapPrototypeKeys: Function.prototype.call.bind(Map.prototype.keys),
119
+ MathFloor: Math.floor,
120
+ MathMax: Math.max,
121
+ MathMin: Math.min,
122
+ MathRound: Math.round,
123
+ MathSqrt: Math.sqrt,
124
+ MathTrunc: Math.trunc,
125
+ Number,
126
+ NumberIsFinite: Number.isFinite,
127
+ NumberIsNaN: Number.isNaN,
128
+ NumberParseFloat: Number.parseFloat,
129
+ NumberParseInt: Number.parseInt,
130
+ NumberPrototypeToString: Function.prototype.call.bind(Number.prototype.toString),
131
+ NumberPrototypeValueOf: Function.prototype.call.bind(Number.prototype.valueOf),
132
+ Object,
133
+ ObjectAssign: Object.assign,
134
+ ObjectCreate: Object.create,
135
+ ObjectDefineProperty: Object.defineProperty,
136
+ ObjectEntries: Object.entries,
137
+ ObjectGetOwnPropertyDescriptor: Object.getOwnPropertyDescriptor,
138
+ ObjectGetOwnPropertyDescriptors: Object.getOwnPropertyDescriptors,
139
+ ObjectGetOwnPropertyNames: Object.getOwnPropertyNames,
140
+ ObjectGetOwnPropertySymbols: Object.getOwnPropertySymbols,
141
+ ObjectGetPrototypeOf: Object.getPrototypeOf,
142
+ ObjectIs: Object.is,
143
+ ObjectKeys: Object.keys,
144
+ ObjectPrototypeHasOwnProperty: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
145
+ ObjectPrototypePropertyIsEnumerable: Function.prototype.call.bind(Object.prototype.propertyIsEnumerable),
146
+ ObjectPrototypeToString: Function.prototype.call.bind(Object.prototype.toString),
147
+ ObjectSeal: Object.seal,
148
+ ObjectSetPrototypeOf: Object.setPrototypeOf,
149
+ ReflectApply: Reflect.apply,
150
+ ReflectOwnKeys: Reflect.ownKeys,
151
+ RegExp,
152
+ RegExpPrototypeExec: Function.prototype.call.bind(RegExp.prototype.exec),
153
+ RegExpPrototypeSymbolReplace: Function.prototype.call.bind(RegExp.prototype[Symbol.replace]),
154
+ RegExpPrototypeSymbolSplit: Function.prototype.call.bind(RegExp.prototype[Symbol.split]),
155
+ RegExpPrototypeTest: Function.prototype.call.bind(RegExp.prototype.test),
156
+ RegExpPrototypeToString: Function.prototype.call.bind(RegExp.prototype.toString),
157
+ SafeStringIterator: createSafeIterator(StringIterator, Function.prototype.call.bind(StringIteratorPrototype.next)),
158
+ SafeMap: makeSafe(
159
+ Map,
160
+ class SafeMap extends Map {
161
+ constructor(i) {
162
+ super(i);
163
+ }
164
+ },
165
+ ),
166
+ SafeSet: makeSafe(
167
+ Set,
168
+ class SafeSet extends Set {
169
+ constructor(i) {
170
+ super(i);
171
+ }
172
+ },
173
+ ),
174
+ SetPrototypeGetSize: getGetter(Set, "size"),
175
+ SetPrototypeEntries: Function.prototype.call.bind(Set.prototype.entries),
176
+ SetPrototypeValues: Function.prototype.call.bind(Set.prototype.values),
177
+ String,
178
+ StringPrototypeCharCodeAt: Function.prototype.call.bind(String.prototype.charCodeAt),
179
+ StringPrototypeCodePointAt: Function.prototype.call.bind(String.prototype.codePointAt),
180
+ StringPrototypeEndsWith: Function.prototype.call.bind(String.prototype.endsWith),
181
+ StringPrototypeIncludes: Function.prototype.call.bind(String.prototype.includes),
182
+ StringPrototypeIndexOf: Function.prototype.call.bind(String.prototype.indexOf),
183
+ StringPrototypeLastIndexOf: Function.prototype.call.bind(String.prototype.lastIndexOf),
184
+ StringPrototypeMatch: Function.prototype.call.bind(String.prototype.match),
185
+ StringPrototypeNormalize: Function.prototype.call.bind(String.prototype.normalize),
186
+ StringPrototypePadEnd: Function.prototype.call.bind(String.prototype.padEnd),
187
+ StringPrototypePadStart: Function.prototype.call.bind(String.prototype.padStart),
188
+ StringPrototypeRepeat: Function.prototype.call.bind(String.prototype.repeat),
189
+ StringPrototypeReplace,
190
+ StringPrototypeReplaceAll: Function.prototype.call.bind(String.prototype.replaceAll),
191
+ StringPrototypeSlice: Function.prototype.call.bind(String.prototype.slice),
192
+ StringPrototypeSplit: Function.prototype.call.bind(String.prototype.split),
193
+ StringPrototypeStartsWith: Function.prototype.call.bind(String.prototype.startsWith),
194
+ StringPrototypeToLowerCase: Function.prototype.call.bind(String.prototype.toLowerCase),
195
+ StringPrototypeTrim: Function.prototype.call.bind(String.prototype.trim),
196
+ StringPrototypeValueOf: Function.prototype.call.bind(String.prototype.valueOf),
197
+ SymbolPrototypeToString: Function.prototype.call.bind(Symbol.prototype.toString),
198
+ SymbolPrototypeValueOf: Function.prototype.call.bind(Symbol.prototype.valueOf),
199
+ SymbolIterator: Symbol.iterator,
200
+ SymbolFor: Symbol.for,
201
+ SymbolToStringTag: Symbol.toStringTag,
202
+ TypedArrayPrototypeGetLength: getGetter(Uint8Array, "length"),
203
+ TypedArrayPrototypeGetSymbolToStringTag: getGetter(Uint8Array, Symbol.toStringTag),
204
+ Uint8ClampedArray,
205
+ Uint8Array,
206
+ Uint16Array,
207
+ Uint32Array,
208
+ Int8Array,
209
+ Int16Array,
210
+ Int32Array,
211
+ Float32Array,
212
+ Float64Array,
213
+ BigUint64Array,
214
+ BigInt64Array,
215
+ uncurryThis,
216
+ };
@@ -0,0 +1,30 @@
1
+
2
+ const Proxies = new WeakMap();
3
+
4
+ class Proxy {
5
+ static #Native = globalThis.Proxy;
6
+ constructor(target, handler) {
7
+ const p = new Proxy.#Native(target, handler);
8
+ Proxies.set(p, [target, handler]);
9
+ return p;
10
+ }
11
+ static revocable(target, handler) {
12
+ const p = Proxy.#Native.revocable(target, handler);
13
+ Proxies.set(p.proxy, [target, handler]);
14
+ const revoke = p.revoke;
15
+ p.revoke = () => {
16
+ Proxies.set(p.proxy, [null, null]);
17
+ revoke();
18
+ };
19
+ return p;
20
+ }
21
+ }
22
+
23
+ function getProxyDetails(obj, withHandler = true) {
24
+ const details = Proxies.get(obj);
25
+ if (!details) return;
26
+ if (withHandler) return details;
27
+ return details[0]; // target only
28
+ }
29
+
30
+ export default { Proxy, getProxyDetails };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
+ "type": "module",
2
3
  "name": "@ohos-ports/bun-repl",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "2.1.1-beta.1",
5
+ "description": "Experimental REPL for Bun",
6
+ "main": "./dist/module/repl.js",
7
+ "scripts": {
8
+ "start": "bun run src/cli.ts",
9
+ "test": "bun run --silent check && bun run --silent start",
10
+ "deeptest": "bun run --silent lint && bun run --silent test",
11
+ "check": "bun tsc",
12
+ "lint": "bun eslint src/**/*.ts",
13
+ "lint-fix": "bun run --silent lint -- --fix",
14
+ "build": "node scripts/build.mjs"
15
+ },
16
+ "author": "jhmaster",
17
+ "license": "MIT",
18
+ "homepage": "https://github.com/ohos-ports/ohos-ports/tree/main/ports/bun-repl/2.1.1",
19
+ "bugs": {
20
+ "url": "https://github.com/ohos-ports/ohos-ports/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
25
+ "directory": "ports/bun-repl/2.1.1"
26
+ },
27
+ "keywords": [
28
+ "bun",
29
+ "repl",
30
+ "cli",
31
+ "ts",
32
+ "js"
33
+ ],
34
+ "dependencies": {
35
+ "@ohos-ports/swc-core": "^1.16.22-beta.0"
36
+ },
37
+ "devDependencies": {
38
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
39
+ "@typescript-eslint/parser": "^6.0.0",
40
+ "bun-devtools": "^0.0.2",
41
+ "bun-types": "^1.0.1",
42
+ "eslint": "^8.44.0",
43
+ "eslint-plugin-unicorn": "^48.0.1",
44
+ "typescript": "^5.1.6"
45
+ },
46
+ "bin": {
47
+ "bun-repl": "./dist/cli.js"
48
+ },
49
+ "engines": {
50
+ "node": ">=22.0.0"
51
+ }
52
+ }
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bun-repl Node port — build script (scripts/build.mjs)
4
+ *
5
+ * Transpiles the TypeScript sources under src/ to dist/ using
6
+ * @ohos-ports/swc-core (the HarmonyOS
7
+ * openharmony-arm64 port of @swc/core, already the package's runtime
8
+ * dependency for the REPL's own transpiler):
9
+ * - TS enums are lowered to real JS (Node's strip-only loader cannot)
10
+ * - relative `.ts` import specifiers are rewritten to `.js`
11
+ * - plain `.js` files (shims, utl) are copied verbatim
12
+ * - the CLI entry keeps an executable `#!/usr/bin/env node` shebang
13
+ *
14
+ * The original src/ tree is left untouched by the build; all source-level
15
+ * changes are recorded as patches (see patches/).
16
+ */
17
+
18
+ import { chmodSync, copyFileSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
19
+ import { dirname, join, relative, resolve } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+ import swc from '@ohos-ports/swc-core';
22
+
23
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
24
+ const srcDir = join(packageRoot, 'src');
25
+ const outDir = join(packageRoot, 'dist');
26
+
27
+ function walk(dir, files = []) {
28
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
29
+ const full = join(dir, entry.name);
30
+ if (entry.isDirectory()) walk(full, files);
31
+ else files.push(full);
32
+ }
33
+ return files;
34
+ }
35
+
36
+ function rewriteTsSpecifiers(code) {
37
+ // Only relative import/export specifiers are rewritten, so unrelated string
38
+ // literals (e.g. swcrc.ts's '$bun$repl.ts') stay untouched.
39
+ return code
40
+ .replace(/(\bfrom\s*)(['"])(\.\.?\/[^'"]*)\.ts\2/g, '$1$2$3.js$2')
41
+ .replace(/(\bimport\s*\(\s*)(['"])(\.\.?\/[^'"]*)\.ts\2/g, '$1$2$3.js$2');
42
+ }
43
+
44
+ const files = walk(srcDir).sort();
45
+ let transpiled = 0;
46
+ let copied = 0;
47
+
48
+ for (const file of files) {
49
+ const rel = relative(srcDir, file);
50
+ // .d.ts declaration files keep their name; only real modules are renamed.
51
+ const outPath = join(outDir, /\.d\.ts$/.test(rel) ? rel : rel.replace(/\.ts$/, '.js'));
52
+ mkdirSync(dirname(outPath), { recursive: true });
53
+
54
+ if (file.endsWith('.js')) {
55
+ copyFileSync(file, outPath);
56
+ copied++;
57
+ continue;
58
+ }
59
+ if (!file.endsWith('.ts')) {
60
+ copyFileSync(file, outPath);
61
+ copied++;
62
+ continue;
63
+ }
64
+
65
+ let source = readFileSync(file, 'utf8');
66
+ let shebang = null;
67
+ if (source.startsWith('#!')) {
68
+ const newline = source.indexOf('\n');
69
+ shebang = source.slice(0, newline);
70
+ source = source.slice(newline + 1);
71
+ }
72
+
73
+ const { code } = swc.transformSync(source, {
74
+ filename: rel,
75
+ isModule: true,
76
+ swcrc: false,
77
+ sourceMaps: false,
78
+ inlineSourcesContent: false,
79
+ module: { type: 'es6' },
80
+ jsc: {
81
+ target: 'esnext',
82
+ parser: { syntax: 'typescript', dynamicImport: true, decorators: true },
83
+ transform: { useDefineForClassFields: false },
84
+ },
85
+ });
86
+
87
+ let out = rewriteTsSpecifiers(code);
88
+ if (shebang) {
89
+ out = `${shebang}\n${out}`;
90
+ writeFileSync(outPath, out);
91
+ chmodSync(outPath, 0o755);
92
+ } else {
93
+ writeFileSync(outPath, out);
94
+ }
95
+ transpiled++;
96
+ }
97
+
98
+ console.log(`build: transpiled ${transpiled} TypeScript file(s), copied ${copied} file(s) -> ${relative(packageRoot, outDir)}/`);
package/src/cli.ts ADDED
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ // node port: shebang retargeted from bun to node (bin entry now runs the dist build)
3
+ import $ from './colors.ts';
4
+
5
+ const helpFlag = process.argv.includes('-h') || process.argv.includes('--help');
6
+ if (helpFlag) {
7
+ printCLIHelp();
8
+ process.exit(0);
9
+ }
10
+
11
+ let evalFlag = process.argv.indexOf('-e');
12
+ if (evalFlag === -1) evalFlag = process.argv.indexOf('--eval');
13
+ let printFlag = process.argv.indexOf('-p');
14
+ if (printFlag === -1) printFlag = process.argv.indexOf('--print');
15
+ if (evalFlag !== -1 && printFlag !== -1) {
16
+ console.error(`bun repl: Incompatible options "${$.whiteBright}--eval${$.red}" and "${$.whiteBright}--print${$.red}"`);
17
+ console.error(`For more information try ${$.whiteBright}--help${$.reset}`);
18
+ process.exit(0);
19
+ }
20
+ const singleshot = evalFlag !== -1 || printFlag !== -1;
21
+ const singleshotCode = process.argv.slice((evalFlag !== -1 ? evalFlag : printFlag) + 1).join(' ');
22
+
23
+ const validFlags = [
24
+ '-h', '--help', '-e', '--eval', '-p', '--print', '--debug', '--sloppy', '--no-history',
25
+ ] as const;
26
+ if (process.argv.length > 2) {
27
+ for (const arg of process.argv.slice(2)) {
28
+ if (['-e', '--eval', '-p', '--print'].includes(arg)) break;
29
+ if (validFlags.includes(arg as typeof validFlags[0])) continue;
30
+ console.error(`bun repl: Unknown option "${$.whiteBright+arg+$.red}"`);
31
+ console.error(`For more information try ${$.whiteBright}--help${$.reset}`);
32
+ process.exit(0);
33
+ }
34
+ }
35
+
36
+ const { default: repl } = await import('./repl.ts');
37
+ await repl.start(singleshot ? singleshotCode : undefined, printFlag !== -1);
38
+
39
+ function printCLIHelp(): void {
40
+ console.log(`Usage: bun repl [options]
41
+
42
+ Options:
43
+ -h, --help Display this message.
44
+ -p, --print <...> Evaluates given code, prints result and exits.
45
+ -e, --eval <...> Evaluates given code and silently exits.
46
+ --sloppy Runs the REPL in sloppy mode.
47
+
48
+ * Options with <...> as argument must be passed last.
49
+
50
+ Environment variables:
51
+ BUN_REPL_HISTORY_SIZE The maximum number of lines to store in the history. (Default: 1000)
52
+ BUN_REPL_PROMPT A string to override the default REPL prompt with. (Default: "> ")
53
+ BUN_REPL_PORT The port for the REPL's local server to use. (Default: random free port)`);
54
+ }
package/src/colors.ts ADDED
@@ -0,0 +1,73 @@
1
+ // Node port: src/colors.ts dereferences `Bun.enableANSIColors` at module top level;
2
+ // importing the shim installs globalThis.Bun first (idempotent).
3
+ import './shims/bun.js';
4
+
5
+ const colors = {
6
+ bold: '\x1B[1m',
7
+ dim: '\x1B[2m',
8
+ underline: '\x1B[4m',
9
+ /** Not widely supported! */
10
+ blink: '\x1B[5m',
11
+ invert: '\x1B[7m',
12
+ invisible: '\x1B[8m',
13
+
14
+ reset: '\x1B[0m',
15
+ //noBold: '\x1B[21m', (broken)
16
+ noDim: '\x1B[22m',
17
+ noUnderline: '\x1B[24m',
18
+ noBlink: '\x1B[25m',
19
+ noInvert: '\x1B[27m',
20
+ visible: '\x1B[28m',
21
+
22
+ black: '\x1B[30m',
23
+ red: '\x1B[31m',
24
+ green: '\x1B[32m',
25
+ yellow: '\x1B[33m',
26
+ blue: '\x1B[34m',
27
+ purple: '\x1B[35m',
28
+ cyan: '\x1B[36m',
29
+ white: '\x1B[37m',
30
+ gray: '\x1B[90m',
31
+ redBright: '\x1B[91m',
32
+ greenBright: '\x1B[92m',
33
+ yellowBright: '\x1B[93m',
34
+ blueBright: '\x1B[94m',
35
+ purpleBright: '\x1B[95m',
36
+ cyanBright: '\x1B[96m',
37
+ whiteBright: '\x1B[97m',
38
+ } as const;
39
+
40
+ const bgColors = {
41
+ black: '\x1B[40m',
42
+ red: '\x1B[41m',
43
+ green: '\x1B[42m',
44
+ yellow: '\x1B[43m',
45
+ blue: '\x1B[44m',
46
+ purple: '\x1B[45m',
47
+ cyan: '\x1B[46m',
48
+ white: '\x1B[47m',
49
+ gray: '\x1B[100m',
50
+ redBright: '\x1B[101m',
51
+ greenBright: '\x1B[102m',
52
+ yellowBright: '\x1B[103m',
53
+ blueBright: '\x1B[104m',
54
+ purpleBright: '\x1B[105m',
55
+ cyanBright: '\x1B[106m',
56
+ whiteBright: '\x1B[107m',
57
+ } as const;
58
+
59
+ if (!Bun.enableANSIColors) {
60
+ for (const color in colors) Reflect.set(colors, color, '');
61
+ for (const color in bgColors) Reflect.set(bgColors, color, '');
62
+ }
63
+
64
+ // For testing all colors
65
+ //for (const color in colors) console.log(colors[color as keyof typeof colors], color, colors.reset);
66
+ //for (const color in bgColors) console.log(bgColors[color as keyof typeof bgColors], color, colors.reset);
67
+
68
+ function bool(bool: boolean, important: boolean = false) {
69
+ if (bool) return `${colors.greenBright}true${colors.reset}`;
70
+ else return `${important ? colors.redBright : colors.gray}false${colors.reset}`;
71
+ }
72
+
73
+ export default { ...colors, bg: bgColors, bool };
@@ -0,0 +1,77 @@
1
+ /* eslint-disable unicorn/custom-error-definition */
2
+ // Polyfill of the Node.js "repl" module (WIP)
3
+
4
+ // Node port: install globalThis.Bun (used by `writer` below) before anything else.
5
+ import '../shims/bun.js';
6
+ import utl from '../utl/index.js'; // node port: Bun-style directory import made explicit
7
+ import { builtinModules } from 'node:module';
8
+
9
+ class NotImplementedError extends Error {
10
+ constructor(method: string, fullmsg: boolean = false) {
11
+ super(fullmsg ? method : method + ' is not implemented');
12
+ this.name = 'NotImplementedError';
13
+ }
14
+ }
15
+
16
+ export class REPLServer {
17
+ constructor() {
18
+ throw new NotImplementedError('repl.REPLServer');
19
+ }
20
+ }
21
+
22
+ export class Recoverable extends SyntaxError {
23
+ readonly err: Error;
24
+ constructor(err: Error) {
25
+ super();
26
+ this.err = err;
27
+ throw new NotImplementedError('repl.Recoverable');
28
+ }
29
+ }
30
+
31
+ export const REPL_MODE_SLOPPY = Symbol('repl-sloppy');
32
+ export const REPL_MODE_STRICT = Symbol('repl-strict');
33
+
34
+ export function start(prompt: string, source: any, eval_: any, useGlobal: boolean, ignoreUndefined: boolean, replMode: symbol) {
35
+ //return new REPLServer(prompt, source, eval_, useGlobal, ignoreUndefined, replMode);
36
+ throw new NotImplementedError('repl.start');
37
+ }
38
+
39
+ interface REPLWriterFunction {
40
+ (val: any): string;
41
+ options: utl.InspectOptions;
42
+ }
43
+
44
+ export const writer = function writer(val: any): string {
45
+ if (val instanceof Error) return Bun.inspect(val, { colors: Bun.enableANSIColors });
46
+ // @ts-expect-error not exactly 1:1 or safe but meh
47
+ // eslint-disable-next-line
48
+ return utl.inspect(val, globalThis.repl?.writer?.options ?? { colors: Bun.enableANSIColors, showProxy: true });
49
+ } as REPLWriterFunction;
50
+ Object.defineProperty(writer, 'options', {
51
+ value: { ...utl.inspect.replDefaults }, enumerable: true
52
+ });
53
+
54
+ const repl = Object.defineProperties({}, {
55
+ start: { value: start, enumerable: true },
56
+ writer: { value: writer, enumerable: true },
57
+ repl: {
58
+ get() { throw new NotImplementedError('bun repl does not run on a REPLServer', true); },
59
+ enumerable: true
60
+ },
61
+ builtinModules: { value: builtinModules, enumerable: true },
62
+ REPL_MODE_SLOPPY: { value: REPL_MODE_SLOPPY, enumerable: true },
63
+ REPL_MODE_STRICT: { value: REPL_MODE_STRICT, enumerable: true },
64
+ REPLServer: { value: REPLServer, enumerable: true },
65
+ Recoverable: { value: Recoverable, enumerable: true }
66
+ }) as {
67
+ start: typeof start,
68
+ writer: typeof writer,
69
+ repl: REPLServer,
70
+ builtinModules: typeof builtinModules,
71
+ REPL_MODE_SLOPPY: typeof REPL_MODE_SLOPPY,
72
+ REPL_MODE_STRICT: typeof REPL_MODE_STRICT,
73
+ REPLServer: typeof REPLServer,
74
+ Recoverable: typeof Recoverable
75
+ };
76
+
77
+ export default repl;