Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(NODE-5040): add color to BSON inspect #635

Merged
merged 17 commits into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 3 additions & 16 deletions src/binary.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
type InspectParameterFn,
defaultInspect,
isAnyArrayBuffer,
isUint8Array
} from './parser/utils';
import { type InspectFn, defaultInspect, isAnyArrayBuffer, isUint8Array } from './parser/utils';
import type { EJSONOptions } from './extended_json';
import { BSONError } from './error';
import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants';
Expand Down Expand Up @@ -268,15 +263,11 @@ export class Binary extends BSONValue {
return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = !inspect;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
const base64Arg = inspect(base64, options);
const subTypeArg = inspect(this.sub_type, options);
if (addQuotes) {
return `Binary.createFromBase64('${base64Arg}', ${subTypeArg})`;
}
return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
}
}
Expand Down Expand Up @@ -472,12 +463,8 @@ export class UUID extends Binary {
* @returns return the 36 character hex string representation.
*
*/
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = !inspect;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
if (addQuotes) {
return `new UUID('${inspect(this.toHexString(), options)}')`;
}
return `new UUID(${inspect(this.toHexString(), options)})`;
}
}
12 changes: 8 additions & 4 deletions src/bson_value.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BSON_MAJOR_VERSION } from './constants';
import { type InspectParameterFn } from './parser/utils';
import { type InspectFn } from './parser/utils';

/** @public */
export abstract class BSONValue {
Expand All @@ -14,13 +14,17 @@ export abstract class BSONValue {
[Symbol.for('nodejs.util.inspect.custom')](
W-A-James marked this conversation as resolved.
Show resolved Hide resolved
depth?: number,
options?: unknown,
inspect?: InspectParameterFn
inspect?: InspectFn
): string {
return this.inspect(depth, options, inspect);
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
}

/** @public */
public abstract inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string;
/**
* @public
* Prints a human-readable string of BSON value information
* If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
*/
public abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;

/** @internal */
abstract toExtendedJSON(): unknown;
Expand Down
4 changes: 2 additions & 2 deletions src/code.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Document } from './bson';
import { BSONValue } from './bson_value';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface CodeExtended {
Expand Down Expand Up @@ -56,7 +56,7 @@ export class Code extends BSONValue {
return new Code(doc.$code, doc.$scope);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
let parametersString = inspect(this.code, options);
const multiLineFn = parametersString.includes('\n');
Expand Down
9 changes: 4 additions & 5 deletions src/db_ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Document } from './bson';
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import type { ObjectId } from './objectid';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface DBRefLike {
Expand Down Expand Up @@ -112,18 +112,17 @@ export class DBRef extends BSONValue {
return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = !inspect;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;

const args = [
inspect(this.namespace, options),
inspect(this.oid, options),
...(this.db ? [inspect(this.db, options)] : []),
...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
].map(arg => (addQuotes ? `'${arg}'` : arg));
];

args[1] = addQuotes ? `new ObjectId(${args[1]})` : args[1];
args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];

return `new DBRef(${args.join(', ')})`;
}
Expand Down
8 changes: 2 additions & 6 deletions src/decimal128.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import { Long } from './long';
import { type InspectParameterFn, defaultInspect, isUint8Array } from './parser/utils';
import { type InspectFn, defaultInspect, isUint8Array } from './parser/utils';
import { ByteUtils } from './utils/byte_utils';

const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
Expand Down Expand Up @@ -847,13 +847,9 @@ export class Decimal128 extends BSONValue {
return Decimal128.fromString(doc.$numberDecimal);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = !inspect;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const d128string = inspect(this.toString(), options);
if (addQuotes) {
return `new Decimal128('${d128string}')`;
}
return `new Decimal128(${d128string})`;
}
}
6 changes: 3 additions & 3 deletions src/double.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface DoubleExtended {
Expand Down Expand Up @@ -72,8 +72,8 @@ export class Double extends BSONValue {
return options && options.relaxed ? doubleValue : new Double(doubleValue);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new Double(${inspect(this.valueOf(), options)})`;
return `new Double(${inspect(this.value, options)})`;
}
}
4 changes: 2 additions & 2 deletions src/int_32.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface Int32Extended {
Expand Down Expand Up @@ -60,7 +60,7 @@ export class Int32 extends BSONValue {
return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
return `new Int32(${inspect(this.value, options)})`;
}
Expand Down
4 changes: 2 additions & 2 deletions src/long.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import type { EJSONOptions } from './extended_json';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';
import type { Timestamp } from './timestamp';

interface LongWASMHelpers {
Expand Down Expand Up @@ -1057,7 +1057,7 @@ export class Long extends BSONValue {
return longResult;
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const longVal = inspect(this.toString(), options);
const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
Expand Down
8 changes: 2 additions & 6 deletions src/objectid.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';
import { BSONDataView, ByteUtils } from './utils/byte_utils';

// Regular expression that checks for hex value
Expand Down Expand Up @@ -296,12 +296,8 @@ export class ObjectId extends BSONValue {
*
* @returns return the 24 character hex string representation.
*/
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = !inspect;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
if (addQuotes) {
return `new ObjectId('${inspect(this.toHexString(), options)}')`;
}
return `new ObjectId(${inspect(this.toHexString(), options)})`;
}
}
29 changes: 26 additions & 3 deletions src/parser/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,29 @@ export function isDate(d: unknown): d is Date {
return Object.prototype.toString.call(d) === '[object Date]';
}

export type InspectParameterFn = (x: unknown, options: unknown) => string;
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
export const defaultInspect: InspectParameterFn = v => `${v}`;
export type InspectFn = (x: unknown, options?: unknown) => string;
export function defaultInspect(x: unknown, _options?: unknown): string {
return JSON.stringify(x, (k: string, v: unknown) => {
if (typeof v === 'bigint') {
return { $numberLong: `${v}` };
} else if (isMap(v)) {
return Object.fromEntries(v);
}
return v;
});
}

/** @internal */
type StylizeFunction = (x: string, style: string) => string;
/** @internal */
export function getStylizeFunction(options?: unknown): StylizeFunction | undefined {
const stylizeExists =
options != null &&
typeof options === 'object' &&
'stylize' in options &&
typeof options.stylize === 'function';

if (stylizeExists) {
return options.stylize as StylizeFunction;
}
}
28 changes: 6 additions & 22 deletions src/regexp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import type { EJSONOptions } from './extended_json';
import { defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect, getStylizeFunction } from './parser/utils';

function alphabetize(str: string): string {
return str.split('').sort().join('');
Expand Down Expand Up @@ -104,27 +104,11 @@ export class BSONRegExp extends BSONValue {
throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
}

inspect(depth?: number, options?: unknown): string {
const stylize = getStylizeFunction(options);
const pattern = stylize(`'${this.pattern}'`, 'regexp');
const flags = stylize(`'${this.options}'`, 'regexp');
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
const stylize = getStylizeFunction(options) ?? (v => v);
inspect ??= defaultInspect;
const pattern = stylize(inspect(this.pattern), 'regexp');
const flags = stylize(inspect(this.options), 'regexp');
return `new BSONRegExp(${pattern}, ${flags})`;
}
}

/** @internal */
type StylizeFunction = (x: string, style: string) => string;
/** @internal */
function getStylizeFunction(options?: unknown): StylizeFunction {
const stylizeExists =
options != null &&
typeof options === 'object' &&
'stylize' in options &&
typeof options.stylize === 'function';

if (stylizeExists) {
return options.stylize as StylizeFunction;
} else {
return defaultInspect;
}
}
8 changes: 2 additions & 6 deletions src/symbol.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BSONValue } from './bson_value';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export interface BSONSymbolExtended {
Expand Down Expand Up @@ -48,12 +48,8 @@ export class BSONSymbol extends BSONValue {
return new BSONSymbol(doc.$symbol);
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = !inspect;
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
if (addQuotes) {
return `new BSONSymbol('${inspect(this.value, options)}')`;
}
return `new BSONSymbol(${inspect(this.value, options)})`;
}
}
8 changes: 4 additions & 4 deletions src/timestamp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BSONError } from './error';
import type { Int32 } from './int_32';
import { Long } from './long';
import { type InspectParameterFn, defaultInspect } from './parser/utils';
import { type InspectFn, defaultInspect } from './parser/utils';

/** @public */
export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect';
Expand Down Expand Up @@ -142,10 +142,10 @@ export class Timestamp extends LongWithoutOverridesClass {
return new Timestamp({ t, i });
}

inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
inspect ??= defaultInspect;
const t = inspect(this.getHighBits(), options);
const i = inspect(this.getLowBits(), options);
const t = inspect(this.high >>> 0, options);
const i = inspect(this.low >>> 0, options);
return `new Timestamp({ t: ${t}, i: ${i} })`;
}
}
60 changes: 60 additions & 0 deletions test/colors.mjs
W-A-James marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/** Used to generate screenshots for introducing color to BSON inspect function */

'use strict';
W-A-James marked this conversation as resolved.
Show resolved Hide resolved

import {
Binary,
UUID,
Code,
DBRef,
Decimal128,
Double,
Int32,
Long,
ObjectId,
BSONRegExp,
BSONSymbol,
Timestamp,
MaxKey,
MinKey
} from '../lib/bson.mjs';

console.log({
binary: new Binary(Buffer.from('abcdef', 'utf8'), 0x06),
uuid: new UUID(),
code: new Code(function iLoveJavaScript() {
do {
console.log('hello!');
} while (Math.random() > 0.5);
}),
c: new Code(
function iLoveJavaScript() {
do {
console.log('hello!');
} while (Math.random() > 0.5);
},
{ context: 'random looping!', reference: Long.fromString('2345'), my_map: {a:1}}
),
c2: new Code (
function iLoveJavaScript() { return `js`; },
{ context: 'random looping!', reference: Long.fromString('2345'), my_map: {a:1}}
),
dbref: new DBRef('collection', new ObjectId('00'.repeat(12))),
dbref_db: new DBRef('collection', new ObjectId('00'.repeat(12)), 'db'),
dbref_db_fields: new DBRef('collection', new ObjectId('00'.repeat(12)), 'db', { a: 1 }),
decimal128: new Decimal128('1.353e34'),
double: new Double(2.354),
double2: new Double(2),
double3: new Double(-0),
int32: new Int32('4577'),
long: new Long(-12442),
objectid: new ObjectId('00'.repeat(12)),
bsonregexp: new BSONRegExp('abc', 'imx'),
bsonsymbol: new BSONSymbol('my symbol'),
timestamp: new Timestamp({ i: 2345, t: 23453 }),
maxkey: new MaxKey(),
minkey: new MinKey()
});

const oid = new ObjectId('00'.repeat(12));
console.log(oid);
Loading