All files / json-pack/src/ejson EjsonDecoder.ts

88.47% Statements 284/321
85.48% Branches 159/186
100% Functions 16/16
91.18% Lines 269/295

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 5155x                             5x 5x             5x 5x 5x               108x 108x       2979x 2979x 2979x 2979x 2979x   1025x   194x   73x   83x   69x   763x   772x 1x         1443x 1443x 1443x 1443x 1443x 1443x 4041x 4041x 4041x 2598x 1009x 2598x 2598x 2598x         763x 763x 763x 763x 763x 763x 5168x 5168x 5168x 762x   762x   4406x 732x 4406x 4406x 4406x 4405x 4405x 4405x 4405x 4405x     4405x 4405x         7820x 7820x 7820x 7820x 7820x   2314x   1249x   223x   223x   384x   1422x   2005x           1422x 1422x 1422x 1422x 1422x 1422x 4837x 4837x 4837x 1422x 1422x   3415x 1314x 3415x 3415x 3415x 3415x 3415x 3415x 3415x 3415x 3415x 3415x         2685x     2685x 97x 95x       9048x   2685x   181x 11x 1x   10x 10x 7x   3x       170x 17x 2x   15x 15x 14x 14x 11x     4x       153x 4x     4x 4x 3x 3x 2x     2x       149x 14x     14x 14x 13x 10x 7x 4x 4x 3x     2x       135x 1x     1x 1x 1x           134x 8x     8x 8x 6x 6x 5x 5x 5x 5x 5x 5x       3x       126x 2x     2x 2x 1x 1x   1x       124x 5x     5x 5x 5x           119x 1x     1x 1x 1x 1x                 118x 1x     1x 1x 1x           117x 7x     7x 7x 7x 7x 5x 5x 5x 3x       4x       110x 3x     3x 3x 3x 3x 3x 3x 3x 3x               107x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 106x 17x     17x 17x   8x 8x 7x   9x   9x 9x 9x 9x 9x 8x       2x       89x 1x     1x 1x           88x 1x     1x 1x           87x 3x     3x 3x             2588x 1x 1x 1x   1x 1x       1x 3x         1x       2587x 2587x 8944x 1476x 7468x 1748x 2558x         5720x     2587x           7x 7x 7x 7x         5x 5x 5x 18x   5x         2x 2x         1x 1x 1x 16x   1x      
import {
  BsonBinary,
  BsonDbPointer,
  BsonDecimal128,
  BsonFloat,
  BsonInt32,
  BsonInt64,
  BsonJavascriptCode,
  BsonJavascriptCodeWithScope,
  BsonMaxKey,
  BsonMinKey,
  BsonObjectId,
  BsonSymbol,
  BsonTimestamp,
} from '../bson/values';
import {JsonDecoder} from '../json/JsonDecoder';
import {readKey} from '../json/JsonDecoder';
 
export interface EjsonDecoderOptions {
  /** Whether to parse legacy Extended JSON formats */
  legacy?: boolean;
}
 
export class EjsonDecoder extends JsonDecoder {
  constructor(private options: EjsonDecoderOptions = {}) {
    super();
  }
 
  /**
   * Decode from string (for backward compatibility).
   * This method maintains the previous API but uses the binary decoder internally.
   */
  public decodeFromString(json: string): unknown {
    const bytes = new TextEncoder().encode(json);
    return this.decode(bytes);
  }
 
  public readAny(): unknown {
    this.skipWhitespace();
    const reader = this.reader;
    const uint8 = reader.uint8;
    const char = uint8[reader.x];
    switch (char) {
      case 34 /* " */:
        return this.readStr();
      case 91 /* [ */:
        return this.readArr();
      case 102 /* f */:
        return this.readFalse();
      case 110 /* n */:
        return this.readNull();
      case 116 /* t */:
        return this.readTrue();
      case 123 /* { */:
        return this.readObjWithEjsonSupport();
      default:
        if ((char >= 48 /* 0 */ && char <= 57) /* 9 */ || char === 45 /* - */) return this.readNum();
        throw new Error('Invalid JSON');
    }
  }
 
  public readArr(): unknown[] {
    const reader = this.reader;
    Iif (reader.u8() !== 0x5b /* [ */) throw new Error('Invalid JSON');
    const arr: unknown[] = [];
    const uint8 = reader.uint8;
    let first = true;
    while (true) {
      this.skipWhitespace();
      const char = uint8[reader.x];
      if (char === 0x5d /* ] */) return reader.x++, arr;
      if (char === 0x2c /* , */) reader.x++;
      else Iif (!first) throw new Error('Invalid JSON');
      this.skipWhitespace();
      arr.push(this.readAny()); // Arrays should process EJSON objects recursively
      first = false;
    }
  }
 
  public readObjWithEjsonSupport(): unknown {
    const reader = this.reader;
    Iif (reader.u8() !== 0x7b /* { */) throw new Error('Invalid JSON');
    const obj: Record<string, unknown> = {};
    const uint8 = reader.uint8;
    let first = true;
    while (true) {
      this.skipWhitespace();
      let char = uint8[reader.x];
      if (char === 0x7d /* } */) {
        reader.x++;
        // Check if this is an EJSON type wrapper
        return this.transformEjsonObject(obj);
      }
      if (char === 0x2c /* , */) reader.x++;
      else Iif (!first) throw new Error('Invalid JSON');
      this.skipWhitespace();
      char = uint8[reader.x++];
      if (char !== 0x22 /* " */) throw new Error('Invalid JSON');
      const key = readKey(reader);
      Iif (key === '__proto__') throw new Error('Invalid JSON');
      this.skipWhitespace();
      Iif (reader.u8() !== 0x3a /* : */) throw new Error('Invalid JSON');
      this.skipWhitespace();
 
      // For EJSON type wrapper detection, we need to read nested objects as raw first
      obj[key] = this.readValue();
      first = false;
    }
  }
 
  private readValue(): unknown {
    this.skipWhitespace();
    const reader = this.reader;
    const uint8 = reader.uint8;
    const char = uint8[reader.x];
    switch (char) {
      case 34 /* " */:
        return this.readStr();
      case 91 /* [ */:
        return this.readArr();
      case 102 /* f */:
        return this.readFalse();
      case 110 /* n */:
        return this.readNull();
      case 116 /* t */:
        return this.readTrue();
      case 123 /* { */:
        return this.readRawObj(); // Read as raw object first
      default:
        if ((char >= 48 /* 0 */ && char <= 57) /* 9 */ || char === 45 /* - */) return this.readNum();
        throw new Error('Invalid JSON');
    }
  }
 
  private readRawObj(): Record<string, unknown> {
    const reader = this.reader;
    Iif (reader.u8() !== 0x7b /* { */) throw new Error('Invalid JSON');
    const obj: Record<string, unknown> = {};
    const uint8 = reader.uint8;
    let first = true;
    while (true) {
      this.skipWhitespace();
      let char = uint8[reader.x];
      if (char === 0x7d /* } */) {
        reader.x++;
        return obj; // Return raw object without transformation
      }
      if (char === 0x2c /* , */) reader.x++;
      else Iif (!first) throw new Error('Invalid JSON');
      this.skipWhitespace();
      char = uint8[reader.x++];
      Iif (char !== 0x22 /* " */) throw new Error('Invalid JSON');
      const key = readKey(reader);
      Iif (key === '__proto__') throw new Error('Invalid JSON');
      this.skipWhitespace();
      Iif (reader.u8() !== 0x3a /* : */) throw new Error('Invalid JSON');
      this.skipWhitespace();
      obj[key] = this.readValue();
      first = false;
    }
  }
 
  private transformEjsonObject(obj: Record<string, unknown>): unknown {
    const keys = Object.keys(obj);
 
    // Helper function to validate exact key match
    const hasExactKeys = (expectedKeys: string[]): boolean => {
      if (keys.length !== expectedKeys.length) return false;
      return expectedKeys.every((key) => keys.includes(key));
    };
 
    // Check if object has any special $ keys that indicate a type wrapper
    const specialKeys = keys.filter((key) => key.startsWith('$'));
 
    if (specialKeys.length > 0) {
      // ObjectId
      if (specialKeys.includes('$oid')) {
        if (!hasExactKeys(['$oid'])) {
          throw new Error('Invalid ObjectId format: extra keys not allowed');
        }
        const oidStr = obj.$oid as string;
        if (typeof oidStr === 'string' && /^[0-9a-fA-F]{24}$/.test(oidStr)) {
          return this.parseObjectId(oidStr);
        }
        throw new Error('Invalid ObjectId format');
      }
 
      // Int32
      if (specialKeys.includes('$numberInt')) {
        if (!hasExactKeys(['$numberInt'])) {
          throw new Error('Invalid Int32 format: extra keys not allowed');
        }
        const intStr = obj.$numberInt as string;
        if (typeof intStr === 'string') {
          const value = parseInt(intStr, 10);
          if (!Number.isNaN(value) && value >= -2147483648 && value <= 2147483647) {
            return new BsonInt32(value);
          }
        }
        throw new Error('Invalid Int32 format');
      }
 
      // Int64
      if (specialKeys.includes('$numberLong')) {
        Iif (!hasExactKeys(['$numberLong'])) {
          throw new Error('Invalid Int64 format: extra keys not allowed');
        }
        const longStr = obj.$numberLong as string;
        if (typeof longStr === 'string') {
          const value = parseFloat(longStr); // Use parseFloat to handle large numbers better
          if (!Number.isNaN(value)) {
            return new BsonInt64(value);
          }
        }
        throw new Error('Invalid Int64 format');
      }
 
      // Double
      if (specialKeys.includes('$numberDouble')) {
        Iif (!hasExactKeys(['$numberDouble'])) {
          throw new Error('Invalid Double format: extra keys not allowed');
        }
        const doubleStr = obj.$numberDouble as string;
        if (typeof doubleStr === 'string') {
          if (doubleStr === 'Infinity') return new BsonFloat(Infinity);
          if (doubleStr === '-Infinity') return new BsonFloat(-Infinity);
          if (doubleStr === 'NaN') return new BsonFloat(NaN);
          const value = parseFloat(doubleStr);
          if (!Number.isNaN(value)) {
            return new BsonFloat(value);
          }
        }
        throw new Error('Invalid Double format');
      }
 
      // Decimal128
      if (specialKeys.includes('$numberDecimal')) {
        Iif (!hasExactKeys(['$numberDecimal'])) {
          throw new Error('Invalid Decimal128 format: extra keys not allowed');
        }
        const decimalStr = obj.$numberDecimal as string;
        if (typeof decimalStr === 'string') {
          return new BsonDecimal128(new Uint8Array(16));
        }
        throw new Error('Invalid Decimal128 format');
      }
 
      // Binary
      if (specialKeys.includes('$binary')) {
        Iif (!hasExactKeys(['$binary'])) {
          throw new Error('Invalid Binary format: extra keys not allowed');
        }
        const binaryObj = obj.$binary as Record<string, unknown>;
        if (typeof binaryObj === 'object' && binaryObj !== null) {
          const binaryKeys = Object.keys(binaryObj);
          if (binaryKeys.length === 2 && binaryKeys.includes('base64') && binaryKeys.includes('subType')) {
            const base64 = binaryObj.base64 as string;
            const subType = binaryObj.subType as string;
            if (typeof base64 === 'string' && typeof subType === 'string') {
              const data = this.base64ToUint8Array(base64);
              const subtype = parseInt(subType, 16);
              return new BsonBinary(subtype, data);
            }
          }
        }
        throw new Error('Invalid Binary format');
      }
 
      // UUID (special case of Binary)
      if (specialKeys.includes('$uuid')) {
        Iif (!hasExactKeys(['$uuid'])) {
          throw new Error('Invalid UUID format: extra keys not allowed');
        }
        const uuidStr = obj.$uuid as string;
        if (typeof uuidStr === 'string' && this.isValidUuid(uuidStr)) {
          const data = this.uuidToBytes(uuidStr);
          return new BsonBinary(4, data); // Subtype 4 for UUID
        }
        throw new Error('Invalid UUID format');
      }
 
      // Code
      if (specialKeys.includes('$code') && !specialKeys.includes('$scope')) {
        Iif (!hasExactKeys(['$code'])) {
          throw new Error('Invalid Code format: extra keys not allowed');
        }
        const code = obj.$code as string;
        if (typeof code === 'string') {
          return new BsonJavascriptCode(code);
        }
        throw new Error('Invalid Code format');
      }
 
      // CodeWScope
      if (specialKeys.includes('$code') && specialKeys.includes('$scope')) {
        Iif (!hasExactKeys(['$code', '$scope'])) {
          throw new Error('Invalid CodeWScope format: extra keys not allowed');
        }
        const code = obj.$code as string;
        const scope = obj.$scope;
        if (typeof code === 'string' && typeof scope === 'object' && scope !== null) {
          return new BsonJavascriptCodeWithScope(
            code,
            this.transformEjsonObject(scope as Record<string, unknown>) as Record<string, unknown>,
          );
        }
        throw new Error('Invalid CodeWScope format');
      }
 
      // Symbol
      if (specialKeys.includes('$symbol')) {
        Iif (!hasExactKeys(['$symbol'])) {
          throw new Error('Invalid Symbol format: extra keys not allowed');
        }
        const symbol = obj.$symbol as string;
        if (typeof symbol === 'string') {
          return new BsonSymbol(symbol);
        }
        throw new Error('Invalid Symbol format');
      }
 
      // Timestamp
      if (specialKeys.includes('$timestamp')) {
        Iif (!hasExactKeys(['$timestamp'])) {
          throw new Error('Invalid Timestamp format: extra keys not allowed');
        }
        const timestampObj = obj.$timestamp as Record<string, unknown>;
        if (typeof timestampObj === 'object' && timestampObj !== null) {
          const timestampKeys = Object.keys(timestampObj);
          if (timestampKeys.length === 2 && timestampKeys.includes('t') && timestampKeys.includes('i')) {
            const t = timestampObj.t as number;
            const i = timestampObj.i as number;
            if (typeof t === 'number' && typeof i === 'number' && t >= 0 && i >= 0) {
              return new BsonTimestamp(i, t);
            }
          }
        }
        throw new Error('Invalid Timestamp format');
      }
 
      // Regular Expression
      if (specialKeys.includes('$regularExpression')) {
        Iif (!hasExactKeys(['$regularExpression'])) {
          throw new Error('Invalid RegularExpression format: extra keys not allowed');
        }
        const regexObj = obj.$regularExpression as Record<string, unknown>;
        if (typeof regexObj === 'object' && regexObj !== null) {
          const regexKeys = Object.keys(regexObj);
          if (regexKeys.length === 2 && regexKeys.includes('pattern') && regexKeys.includes('options')) {
            const pattern = regexObj.pattern as string;
            const options = regexObj.options as string;
            if (typeof pattern === 'string' && typeof options === 'string') {
              return new RegExp(pattern, options);
            }
          }
        }
        throw new Error('Invalid RegularExpression format');
      }
 
      // DBPointer
      if (specialKeys.includes('$dbPointer')) {
        Iif (!hasExactKeys(['$dbPointer'])) {
          throw new Error('Invalid DBPointer format: extra keys not allowed');
        }
        const dbPointerObj = obj.$dbPointer as Record<string, unknown>;
        if (typeof dbPointerObj === 'object' && dbPointerObj !== null) {
          const dbPointerKeys = Object.keys(dbPointerObj);
          if (dbPointerKeys.length === 2 && dbPointerKeys.includes('$ref') && dbPointerKeys.includes('$id')) {
            const ref = dbPointerObj.$ref as string;
            const id = dbPointerObj.$id;
            if (typeof ref === 'string' && id !== undefined) {
              const transformedId = this.transformEjsonObject(id as Record<string, unknown>) as BsonObjectId;
              if (transformedId instanceof BsonObjectId) {
                return new BsonDbPointer(ref, transformedId);
              }
            }
          }
        }
        throw new Error('Invalid DBPointer format');
      }
 
      // Date
      if (specialKeys.includes('$date')) {
        Iif (!hasExactKeys(['$date'])) {
          throw new Error('Invalid Date format: extra keys not allowed');
        }
        const dateValue = obj.$date;
        if (typeof dateValue === 'string') {
          // ISO-8601 format (relaxed)
          const date = new Date(dateValue);
          if (!Number.isNaN(date.getTime())) {
            return date;
          }
        } else if (typeof dateValue === 'object' && dateValue !== null) {
          // Canonical format with $numberLong
          const longObj = dateValue as Record<string, unknown>;
          const longKeys = Object.keys(longObj);
          if (longKeys.length === 1 && longKeys[0] === '$numberLong' && typeof longObj.$numberLong === 'string') {
            const timestamp = parseFloat(longObj.$numberLong);
            if (!Number.isNaN(timestamp)) {
              return new Date(timestamp);
            }
          }
        }
        throw new Error('Invalid Date format');
      }
 
      // MinKey
      if (specialKeys.includes('$minKey')) {
        Iif (!hasExactKeys(['$minKey'])) {
          throw new Error('Invalid MinKey format: extra keys not allowed');
        }
        if (obj.$minKey === 1) {
          return new BsonMinKey();
        }
        throw new Error('Invalid MinKey format');
      }
 
      // MaxKey
      if (specialKeys.includes('$maxKey')) {
        Iif (!hasExactKeys(['$maxKey'])) {
          throw new Error('Invalid MaxKey format: extra keys not allowed');
        }
        if (obj.$maxKey === 1) {
          return new BsonMaxKey();
        }
        throw new Error('Invalid MaxKey format');
      }
 
      // Undefined
      if (specialKeys.includes('$undefined')) {
        Iif (!hasExactKeys(['$undefined'])) {
          throw new Error('Invalid Undefined format: extra keys not allowed');
        }
        if (obj.$undefined === true) {
          return undefined;
        }
        throw new Error('Invalid Undefined format');
      }
    }
 
    // DBRef (not a BSON type, but a convention) - special case, can have additional fields
    if (keys.includes('$ref') && keys.includes('$id')) {
      const ref = obj.$ref as string;
      const id = this.transformEjsonObject(obj.$id as Record<string, unknown>);
      const result: Record<string, unknown> = {$ref: ref, $id: id};
 
      if (keys.includes('$db')) {
        result.$db = obj.$db;
      }
 
      // Add any other fields
      for (const key of keys) {
        Iif (key !== '$ref' && key !== '$id' && key !== '$db') {
          result[key] = this.transformEjsonObject(obj[key] as Record<string, unknown>);
        }
      }
 
      return result;
    }
 
    // Regular object - transform all properties
    const result: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(obj)) {
      if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
        result[key] = this.transformEjsonObject(val as Record<string, unknown>);
      } else if (Array.isArray(val)) {
        result[key] = val.map((item) =>
          typeof item === 'object' && item !== null && !Array.isArray(item)
            ? this.transformEjsonObject(item as Record<string, unknown>)
            : item,
        );
      } else {
        result[key] = val;
      }
    }
    return result;
  }
 
  // Utility methods
  private parseObjectId(hex: string): BsonObjectId {
    // Parse 24-character hex string into ObjectId components
    const timestamp = parseInt(hex.slice(0, 8), 16);
    const process = parseInt(hex.slice(8, 18), 16);
    const counter = parseInt(hex.slice(18, 24), 16);
    return new BsonObjectId(timestamp, process, counter);
  }
 
  private base64ToUint8Array(base64: string): Uint8Array {
    // Convert base64 string to Uint8Array
    const binary = atob(base64);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i);
    }
    return bytes;
  }
 
  private isValidUuid(uuid: string): boolean {
    // UUID pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    const uuidPattern = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
    return uuidPattern.test(uuid);
  }
 
  private uuidToBytes(uuid: string): Uint8Array {
    // Convert UUID string to 16-byte array
    const hex = uuid.replace(/-/g, '');
    const bytes = new Uint8Array(16);
    for (let i = 0; i < 16; i++) {
      bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
    }
    return bytes;
  }
}