From a879ba01c1a67b3d53b1dc56da61cbae453be8cb Mon Sep 17 00:00:00 2001 From: alok-108 <166419621+alok-108@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:32:20 +0530 Subject: [PATCH] fix: preserve numeric BSON types in Document View --- src/documentdb/ClustersClient.ts | 6 +- .../documentView/documentEjson.test.ts | 101 ++++++++++++++++++ .../documentdb/documentView/documentEjson.ts | 73 +++++++++++++ .../documentView/documentsViewRouter.ts | 9 +- 4 files changed, 182 insertions(+), 7 deletions(-) create mode 100644 src/webviews/documentdb/documentView/documentEjson.test.ts create mode 100644 src/webviews/documentdb/documentView/documentEjson.ts diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index e95dc632a..97f47f7aa 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -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); + const documentContent = await collection.findOne({ _id: parsedDocumentId } as Filter, { + promoteValues: false, + }); return documentContent; } @@ -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 }; } diff --git a/src/webviews/documentdb/documentView/documentEjson.test.ts b/src/webviews/documentdb/documentView/documentEjson.test.ts new file mode 100644 index 000000000..39d7323c3 --- /dev/null +++ b/src/webviews/documentdb/documentView/documentEjson.test.ts @@ -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); + }); +}); diff --git a/src/webviews/documentdb/documentView/documentEjson.ts b/src/webviews/documentdb/documentView/documentEjson.ts new file mode 100644 index 000000000..c316df4a3 --- /dev/null +++ b/src/webviews/documentdb/documentView/documentEjson.ts @@ -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 = {}; + 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; +} diff --git a/src/webviews/documentdb/documentView/documentsViewRouter.ts b/src/webviews/documentdb/documentView/documentsViewRouter.ts index 4676f23ab..7498fb0fb 100644 --- a/src/webviews/documentdb/documentView/documentsViewRouter.ts +++ b/src/webviews/documentdb/documentView/documentsViewRouter.ts @@ -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 & { /** @@ -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); @@ -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; @@ -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}`);