Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 4 additions & 2 deletions src/documentdb/ClustersClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1205,7 +1205,9 @@ export class ClustersClient {
// connect and execute
const collection = this._mongoClient.db(databaseName).collection(collectionName);

const documentContent = await collection.findOne({ _id: parsedDocumentId } as Filter<Document>);
const documentContent = await collection.findOne({ _id: parsedDocumentId } as Filter<Document>, {
promoteValues: false,
});

return documentContent;
}
Expand Down Expand Up @@ -1245,7 +1247,7 @@ export class ClustersClient {
const newDocumentId = (replaceResult.upsertedId as any) ?? parsedId;

// eslint-disable-next-line
const newDocument = await collection.findOne({ _id: newDocumentId });
const newDocument = await collection.findOne({ _id: newDocumentId }, { promoteValues: false });

return { documentId: newDocumentId, document: newDocument };
}
Expand Down
101 changes: 101 additions & 0 deletions src/webviews/documentdb/documentView/documentEjson.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { BSON, Decimal128, Double, Int32, Long, ObjectId } from 'bson';
import { describe, expect, it } from 'vitest';
import { parseDocumentFromEditor, stringifyDocumentForEditor } from './documentEjson';

describe('documentEjson', () => {
it('preserves Long, integral Double, and Int32 across read -> editor -> save round-trips', () => {
const id = new ObjectId('65f1a2b3c4d5e6f708192a3b');
const original = {
_id: id,
smallLong: Long.fromNumber(5),
bigLong: Long.fromString('9007199254740993'),
integralDouble: new Double(1),
largeIntegralDouble: new Double(3000000000),
negativeZeroDouble: new Double(-0),
fractionalDouble: new Double(1.5),
int32: new Int32(7),
decimal: Decimal128.fromString('12.34'),
nested: {
arr: [Long.fromNumber(42), new Double(2), new Double(2.5), new Int32(3)],
},
};

// Simulate reading from MongoDB with promoteValues: false
const readFromDb = BSON.deserialize(BSON.serialize(original), { promoteValues: false });
const editorText = stringifyDocumentForEditor(readFromDb);

// Ordinary Int32 and fractional Double stay readable as plain JSON numbers
expect(editorText).toContain('"int32": 7');
expect(editorText).toContain('"fractionalDouble": 1.5');

// Long and integral Double keep explicit wrappers so precision and BSON types survive
expect(editorText).toContain('"$numberLong": "5"');
expect(editorText).toContain('"$numberLong": "9007199254740993"');
expect(editorText).toContain('"$numberDouble": "1.0"');
expect(editorText).toContain('"$numberDouble": "3000000000.0"');
expect(editorText).toContain('"$numberDouble": "-0.0"');

// Simulate parsing on save and persisting back to BSON
const parsedForSave = parseDocumentFromEditor(editorText);
const savedInDb = BSON.deserialize(BSON.serialize(parsedForSave), { promoteValues: false });

expect(savedInDb._id).toBeInstanceOf(ObjectId);
expect((savedInDb._id as ObjectId).toHexString()).toBe(id.toHexString());

expect(savedInDb.smallLong).toBeInstanceOf(Long);
expect((savedInDb.smallLong as Long).toString()).toBe('5');

expect(savedInDb.bigLong).toBeInstanceOf(Long);
expect((savedInDb.bigLong as Long).toString()).toBe('9007199254740993');

expect(savedInDb.integralDouble).toBeInstanceOf(Double);
expect((savedInDb.integralDouble as Double).valueOf()).toBe(1);

expect(savedInDb.largeIntegralDouble).toBeInstanceOf(Double);
expect((savedInDb.largeIntegralDouble as Double).valueOf()).toBe(3000000000);

expect(savedInDb.negativeZeroDouble).toBeInstanceOf(Double);
expect(Object.is((savedInDb.negativeZeroDouble as Double).valueOf(), -0)).toBe(true);

expect(savedInDb.fractionalDouble).toBeInstanceOf(Double);
expect((savedInDb.fractionalDouble as Double).valueOf()).toBe(1.5);

expect(savedInDb.int32).toBeInstanceOf(Int32);
expect((savedInDb.int32 as Int32).valueOf()).toBe(7);

expect(savedInDb.decimal).toBeInstanceOf(Decimal128);
expect((savedInDb.decimal as Decimal128).toString()).toBe('12.34');

const nestedArr = (savedInDb.nested as { arr: unknown[] }).arr;
expect(nestedArr[0]).toBeInstanceOf(Long);
expect((nestedArr[0] as Long).toString()).toBe('42');
expect(nestedArr[1]).toBeInstanceOf(Double);
expect((nestedArr[1] as Double).valueOf()).toBe(2);
expect(nestedArr[2]).toBeInstanceOf(Double);
expect((nestedArr[2] as Double).valueOf()).toBe(2.5);
expect(nestedArr[3]).toBeInstanceOf(Int32);
expect((nestedArr[3] as Int32).valueOf()).toBe(3);
});

it('handles null documents and non-finite doubles', () => {
expect(stringifyDocumentForEditor(null)).toBe('null');

const doc = BSON.deserialize(BSON.serialize({ nanVal: new Double(NaN), infVal: new Double(Infinity) }), {
promoteValues: false,
});
const editorText = stringifyDocumentForEditor(doc);
const saved = BSON.deserialize(BSON.serialize(parseDocumentFromEditor(editorText)), {
promoteValues: false,
});

expect(saved.nanVal).toBeInstanceOf(Double);
expect(Number.isNaN((saved.nanVal as Double).valueOf())).toBe(true);
expect(saved.infVal).toBeInstanceOf(Double);
expect((saved.infVal as Double).valueOf()).toBe(Infinity);
});
});
73 changes: 73 additions & 0 deletions src/webviews/documentdb/documentView/documentEjson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { Double, EJSON, Long, type Document } from 'bson';

function isBsonLong(value: unknown): value is Long {
return (
value instanceof Long ||
(typeof value === 'object' && value !== null && '_bsontype' in value && value._bsontype === 'Long')
);
}

function isBsonDouble(value: unknown): value is Double {
return (
value instanceof Double ||
(typeof value === 'object' && value !== null && '_bsontype' in value && value._bsontype === 'Double')
);
}

function preserveNumericTypesForEjson(value: unknown): unknown {
if (isBsonLong(value)) {
return EJSON.serialize(value, { relaxed: false });
}

if (isBsonDouble(value)) {
const numericValue = value.valueOf();
// Integral doubles (including -0) would serialize as plain integers in relaxed EJSON
// and be parsed back as Int32 or Long instead of Double.
if (Number.isInteger(numericValue)) {
return EJSON.serialize(value, { relaxed: false });
}
return value;
}

if (Array.isArray(value)) {
return value.map(preserveNumericTypesForEjson);
}

if (
value !== null &&
typeof value === 'object' &&
!('_bsontype' in value) &&
!(value instanceof Date) &&
!(value instanceof RegExp)
) {
const result: Record<string, unknown> = {};
for (const [key, entryValue] of Object.entries(value)) {
result[key] = preserveNumericTypesForEjson(entryValue);
}
return result;
}

return value;
}

/**
* Serializes a BSON document to pretty-printed Extended JSON for the Document View editor.
* Keeps relaxed formatting for readability while preserving explicit `$numberLong` and
* integral `$numberDouble` wrappers where relaxed EJSON would lose precision or BSON types.
*/
export function stringifyDocumentForEditor(document: Document | null): string {
return EJSON.stringify(preserveNumericTypesForEjson(document), undefined, 4);
}

/**
* Parses Extended JSON from the Document View editor back into a BSON document
* without relaxing explicit `$numberLong`, `$numberDouble`, or `$numberInt` wrappers.
*/
export function parseDocumentFromEditor(documentContent: string): Document {
return EJSON.parse(documentContent, { relaxed: false }) as Document;
}
9 changes: 4 additions & 5 deletions src/webviews/documentdb/documentView/documentsViewRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { recordSurveyActivity } from '../../../services/survey/SurveyService';
import { showConfirmationAsInSettings } from '../../../utils/dialogs/showConfirmation';
import { type BaseRouterContext } from '../../_integration/appRouter';
import { publicProcedureWithTelemetry, router, type WithTelemetry } from '../../_integration/trpc';
import { parseDocumentFromEditor, stringifyDocumentForEditor } from './documentEjson';

export type RouterContext = BaseRouterContext & {
/**
Expand Down Expand Up @@ -64,7 +65,7 @@ export const documentsViewRouter = router({
* Not all BSON objects can be serialized to JSON. Therefore, we're using
* EJSON to serialize the document to an object that can be serialized to JSON.
*/
const extendedJson = EJSON.stringify(documentContent, undefined, 4);
const extendedJson = stringifyDocumentForEditor(documentContent);

//const documentContetntAsString = JSON.stringify(extendedJson, null, 4);

Expand All @@ -77,8 +78,7 @@ export const documentsViewRouter = router({
.mutation(async ({ input, ctx }) => {
const myCtx = ctx as RouterContext;

// eslint-disable-next-line
const documentBson: Document = EJSON.parse(input.documentContent);
const documentBson: Document = parseDocumentFromEditor(input.documentContent);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
let documentId: any;
Expand Down Expand Up @@ -112,8 +112,7 @@ export const documentsViewRouter = router({
* Not all BSON objects can be serialized to JSON. Therefore, we're using
* EJSON to serialize the document to an object that can be serialized to JSON.
*/
const extendedJson = EJSON.serialize(upsertResult.document);
const newDocumentStringified = JSON.stringify(extendedJson, null, 4);
const newDocumentStringified = stringifyDocumentForEditor(upsertResult.document);

myCtx.viewPanelTitleSetter(`${myCtx.databaseName}/${myCtx.collectionName}/${newDocumentId}`);

Expand Down