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 10 commits
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
38 changes: 23 additions & 15 deletions src/binary.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { isAnyArrayBuffer, isUint8Array } from './parser/utils';
import {
type InspectParameterFn,
basicInspectParameterFn,
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 @@ -263,14 +268,16 @@ export class Binary extends BSONValue {
return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = inspect ? false : true;
inspect ??= basicInspectParameterFn;
const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
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 @@ -463,13 +470,14 @@ export class UUID extends Binary {
* Converts to a string representation of this Id.
*
* @returns return the 36 character hex string representation.
* @internal
*
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new UUID("${this.toHexString()}")`;
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = inspect ? false : true;
inspect ??= basicInspectParameterFn;
if (addQuotes) {
return `new UUID('${inspect(this.toHexString(), options)}')`;
}
return `new UUID(${inspect(this.toHexString(), options)})`;
}
}
11 changes: 10 additions & 1 deletion src/bson_value.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BSON_MAJOR_VERSION } from './constants';
import { type InspectParameterFn } from './parser/utils';

/** @public */
export abstract class BSONValue {
Expand All @@ -10,8 +11,16 @@ export abstract class BSONValue {
return BSON_MAJOR_VERSION;
}

[Symbol.for('nodejs.util.inspect.custom')](
W-A-James marked this conversation as resolved.
Show resolved Hide resolved
depth?: number,
options?: unknown,
inspect?: InspectParameterFn
): string {
return this.inspect(depth, options, inspect);
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
}

/** @public */
public abstract inspect(): string;
public abstract inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string;
baileympearson marked this conversation as resolved.
Show resolved Hide resolved

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

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

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
const codeJson = this.toJSON();
return `new Code(${JSON.stringify(String(codeJson.code))}${
codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''
})`;
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect ??= basicInspectParameterFn;
let parametersString = inspect(this.code, options);
const multiLineFn = parametersString.includes('\n');
if (this.scope != null) {
parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
}
const endingNewline = multiLineFn && this.scope === null;
return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
}
}
32 changes: 21 additions & 11 deletions src/db_ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +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, basicInspectParameterFn } from './parser/utils';

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

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = inspect ? false : true;
baileympearson marked this conversation as resolved.
Show resolved Hide resolved
inspect ??= basicInspectParameterFn;

const namespaceArg = addQuotes
? `'${inspect(this.namespace, options)}'`
: inspect(this.namespace, options);
const objectIDArg = addQuotes
? `new ObjectId('${inspect(this.oid, options)}')`
: inspect(this.oid, options);
const args = [namespaceArg, objectIDArg];

if (this.db) {
args.push(addQuotes ? `'${inspect(this.db, options)}'` : inspect(this.db, options));
}

if (Object.keys(this.fields).length > 0) {
args.push(inspect(this.fields, options));
}

baileympearson marked this conversation as resolved.
Show resolved Hide resolved
inspect(): string {
// NOTE: if OID is an ObjectId class it will just print the oid string.
const oid =
this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
addaleax marked this conversation as resolved.
Show resolved Hide resolved
return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${
this.db ? `, "${this.db}"` : ''
})`;
return `new DBRef(${args.join(', ')})`;
}
}
17 changes: 9 additions & 8 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 { isUint8Array } from './parser/utils';
import { type InspectParameterFn, basicInspectParameterFn, 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,12 +847,13 @@ export class Decimal128 extends BSONValue {
return Decimal128.fromString(doc.$numberDecimal);
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

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

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

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
const eJSON = this.toExtendedJSON() as DoubleExtended;
return `new Double(${eJSON.$numberDouble})`;
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect ??= basicInspectParameterFn;
return `new Double(${inspect(this.valueOf(), options)})`;
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
}
}
11 changes: 4 additions & 7 deletions src/int_32.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BSONValue } from './bson_value';
import type { EJSONOptions } from './extended_json';
import { type InspectParameterFn, basicInspectParameterFn } from './parser/utils';

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

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

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

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

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`;
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
inspect ??= basicInspectParameterFn;
const longVal = inspect(this.toString(), options);
const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
return `new Long(${longVal}${unsignedVal})`;
}
}
5 changes: 0 additions & 5 deletions src/max_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ export class MaxKey extends BSONValue {
return new MaxKey();
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return 'new MaxKey()';
}
Expand Down
5 changes: 0 additions & 5 deletions src/min_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ export class MinKey extends BSONValue {
return new MinKey();
}

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return 'new MinKey()';
}
Expand Down
15 changes: 8 additions & 7 deletions src/objectid.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BSONValue } from './bson_value';
import { BSONError } from './error';
import { type InspectParameterFn, basicInspectParameterFn } from './parser/utils';
import { BSONDataView, ByteUtils } from './utils/byte_utils';

// Regular expression that checks for hex value
Expand Down Expand Up @@ -294,13 +295,13 @@ export class ObjectId extends BSONValue {
* Converts to a string representation of this Id.
*
* @returns return the 24 character hex string representation.
* @internal
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new ObjectId("${this.toHexString()}")`;
inspect(depth?: number, options?: unknown, inspect?: InspectParameterFn): string {
const addQuotes = inspect ? false : true;
inspect ??= basicInspectParameterFn;
if (addQuotes) {
return `new ObjectId('${inspect(this.toHexString(), options)}')`;
}
return `new ObjectId(${inspect(this.toHexString(), options)})`;
}
}
20 changes: 20 additions & 0 deletions src/parser/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,23 @@ export function isMap(d: unknown): d is Map<unknown, unknown> {
export function isDate(d: unknown): d is Date {
return Object.prototype.toString.call(d) === '[object Date]';
}

/** @internal */
export type StylizeFunction = (x: string, style: string) => string;
export type InspectParameterFn = (x: unknown, options: unknown) => string;
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
export const basicInspectParameterFn: InspectParameterFn = v => `${v}`;
baileympearson marked this conversation as resolved.
Show resolved Hide resolved

export function getStylizeFunction(options?: unknown): StylizeFunction {
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
const stylizeExists =
options != null &&
typeof options === 'object' &&
'stylize' in options &&
typeof options.stylize === 'function';

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

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

/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
/** @internal */
[Symbol.for('nodejs.util.inspect.custom')](depth?: number, options?: unknown): string {
W-A-James marked this conversation as resolved.
Show resolved Hide resolved
return this.inspect(depth, options);
}

inspect(): string {
return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`;
inspect(depth?: number, options?: unknown): string {
const stylize = getStylizeFunction(options);
const pattern = stylize(`'${this.pattern}'`, 'regexp');
const flags = stylize(`'${this.options}'`, 'regexp');
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
return `new BSONRegExp(${pattern}, ${flags})`;
}
}
Loading