UNPKG

23.2 kBTypeScriptView Raw
1// Type definitions for bson 4.0
2// Project: https://github.com/mongodb/js-bson
3// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>
4// Federico Caselli <https://github.com/CaselIT>
5// Justin Grant <https://github.com/justingrant>
6// Mikael Lirbank <https://github.com/lirbank>
7// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
8
9/// <reference types="node"/>
10
11interface CommonSerializeOptions {
12 /** {default:false}, the serializer will check if keys are valid. */
13 checkKeys?: boolean | undefined;
14 /** {default:false}, serialize the javascript functions. */
15 serializeFunctions?: boolean | undefined;
16 /** {default:true}, ignore undefined fields. */
17 ignoreUndefined?: boolean | undefined;
18}
19
20export interface SerializeOptions extends CommonSerializeOptions {
21 /** {default:1024*1024*17}, minimum size of the internal temporary serialization buffer. */
22 minInternalBufferSize?: number | undefined;
23}
24
25export interface SerializeWithBufferAndIndexOptions extends CommonSerializeOptions {
26 /** {default:0}, the index in the buffer where we wish to start serializing into. */
27 index?: number | undefined;
28}
29
30export interface DeserializeOptions {
31 /** {default:false}, evaluate functions in the BSON document scoped to the object deserialized. */
32 evalFunctions?: boolean | undefined;
33 /** {default:false}, cache evaluated functions for reuse. */
34 cacheFunctions?: boolean | undefined;
35 /** {default:false}, use a crc32 code for caching, otherwise use the string of the function. */
36 cacheFunctionsCrc32?: boolean | undefined;
37 /** {default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits. */
38 promoteLongs?: boolean | undefined;
39 /** {default:false}, deserialize Binary data directly into node.js Buffer object. */
40 promoteBuffers?: boolean | undefined;
41 /** {default:false}, when deserializing will promote BSON values to their Node.js closest equivalent types. */
42 promoteValues?: boolean | undefined;
43 /** {default:null}, allow to specify if there what fields we wish to return as unserialized raw buffer. */
44 fieldsAsRaw?: { readonly [fieldName: string]: boolean } | undefined;
45 /** {default:false}, return BSON regular expressions as BSONRegExp instances. */
46 bsonRegExp?: boolean | undefined;
47 /** {default:false}, allows the buffer to be larger than the parsed BSON object. */
48 allowObjectSmallerThanBufferSize?: boolean | undefined;
49}
50
51export interface CalculateObjectSizeOptions {
52 /** {default:false}, serialize the javascript functions */
53 serializeFunctions?: boolean | undefined;
54 /** {default:true}, ignore undefined fields. */
55 ignoreUndefined?: boolean | undefined;
56}
57
58
59/**
60 * Serialize a Javascript object.
61 *
62 * @param object The Javascript object to serialize.
63 * @param options Serialize options.
64 * @return The Buffer object containing the serialized object.
65 */
66export function serialize(object: any, options?: SerializeOptions): Buffer;
67
68/**
69 * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
70 *
71 * @param object The Javascript object to serialize.
72 * @param buffer The Buffer you pre-allocated to store the serialized BSON object.
73 * @param options Serialize options.
74 * @returns The index pointing to the last written byte in the buffer
75 */
76export function serializeWithBufferAndIndex(object: any, buffer: Buffer, options?: SerializeWithBufferAndIndexOptions): number;
77
78/**
79 * Deserialize data as BSON.
80 *
81 * @param buffer The buffer containing the serialized set of BSON documents.
82 * @param options Deserialize options.
83 * @returns The deserialized Javascript Object.
84 */
85export function deserialize(buffer: Buffer, options?: DeserializeOptions): any;
86
87/**
88 * Calculate the bson size for a passed in Javascript object.
89 *
90 * @param {Object} object the Javascript object to calculate the BSON byte size for.
91 * @param {CalculateObjectSizeOptions} Options
92 * @return {Number} returns the number of bytes the BSON object will take up.
93 */
94export function calculateObjectSize(object: any, options?: CalculateObjectSizeOptions): number;
95
96/**
97 * Deserialize stream data as BSON documents.
98 *
99 * @param data The buffer containing the serialized set of BSON documents.
100 * @param startIndex The start index in the data Buffer where the deserialization is to start.
101 * @param numberOfDocuments Number of documents to deserialize
102 * @param documents An array where to store the deserialized documents
103 * @param docStartIndex The index in the documents array from where to start inserting documents
104 * @param options Additional options used for the deserialization
105 * @returns The next index in the buffer after deserialization of the `numberOfDocuments`
106 */
107export function deserializeStream(
108 data: Buffer,
109 startIndex: number,
110 numberOfDocuments: number,
111 documents: Array<any>,
112 docStartIndex: number,
113 options?: DeserializeOptions
114): number;
115
116/** A class representation of the BSON Binary type. */
117export class Binary {
118
119 static readonly SUBTYPE_DEFAULT: number;
120 static readonly SUBTYPE_FUNCTION: number;
121 static readonly SUBTYPE_BYTE_ARRAY: number;
122 static readonly SUBTYPE_UUID_OLD: number;
123 static readonly SUBTYPE_UUID: number;
124 static readonly SUBTYPE_MD5: number;
125 static readonly SUBTYPE_USER_DEFINED: number;
126
127 /**
128 * @param buffer A buffer object containing the binary data
129 * @param subType Binary data subtype
130 */
131 constructor(buffer: Buffer, subType?: number);
132
133 /** The underlying Buffer which stores the binary data. */
134 readonly buffer: Buffer;
135 /** Binary data subtype */
136 readonly sub_type?: number | undefined;
137
138 /** The length of the binary. */
139 length(): number;
140 /** Updates this binary with byte_value */
141 put(byte_value: number | string): void;
142 /** Reads length bytes starting at position. */
143 read(position: number, length: number): Buffer;
144 /** Returns the value of this binary as a string. */
145 value(): string;
146 /** Writes a buffer or string to the binary */
147 write(buffer: Buffer | string, offset: number): void;
148}
149
150/** A class representation of the BSON Code type. */
151export class Code {
152
153 /**
154 * @param code A string or function.
155 * @param scope An optional scope for the function.
156 */
157 constructor(code: string | Function, scope?: any);
158
159 readonly code: string | Function;
160 readonly scope?: any;
161
162}
163
164/**
165 * A class representation of the BSON DBRef type.
166 */
167export class DBRef {
168 /**
169 * @param namespace The collection name.
170 * @param oid The reference ObjectId.
171 * @param db Optional db name, if omitted the reference is local to the current db
172 */
173 constructor(namespace: string, oid: ObjectId, db?: string);
174 namespace: string;
175 oid: ObjectId;
176 db?: string | undefined;
177}
178
179/** A class representation of the BSON Double type. */
180export class Double {
181 /**
182 * @param value The number we want to represent as a double.
183 */
184 constructor(value: number);
185
186 /**
187 * https://github.com/mongodb/js-bson/blob/master/lib/double.js#L17
188 */
189 value: number;
190
191
192 valueOf(): number;
193}
194
195/** A class representation of the BSON Int32 type. */
196export class Int32 {
197 /**
198 * @param value The number we want to represent as an int32.
199 */
200 constructor(value: number);
201
202 valueOf(): number;
203}
204
205/**
206 * Base class for Long and Timestamp.
207 * In original js-node@1.0.x code 'Timestamp' is a 100% copy-paste of 'Long'
208 * with 'Long' replaced by 'Timestamp' (changed to inheritance in js-node@2.0.0)
209 */
210declare class LongLike<T> {
211
212 /**
213 * @param low The low (signed) 32 bits.
214 * @param high The high (signed) 32 bits.
215 */
216 constructor(low: number, high: number);
217
218 /** Returns the sum of `this` and the `other`. */
219 add(other: T): T;
220 /** Returns the bitwise-AND of `this` and the `other`. */
221 and(other: T): T;
222 /**
223 * Compares `this` with the given `other`.
224 * @returns 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
225 */
226 compare(other: T): number;
227 /** Returns `this` divided by the given `other`. */
228 div(other: T): T;
229 /** Return whether `this` equals the `other` */
230 equals(other: T): boolean;
231 /** Return the high 32-bits value. */
232 getHighBits(): number;
233 /** Return the low 32-bits value. */
234 getLowBits(): number;
235 /** Return the low unsigned 32-bits value. */
236 getLowBitsUnsigned(): number;
237 /** Returns the number of bits needed to represent the absolute value of `this`. */
238 getNumBitsAbs(): number;
239 /** Return whether `this` is greater than the `other`. */
240 greaterThan(other: T): boolean;
241 /** Return whether `this` is greater than or equal to the `other`. */
242 greaterThanOrEqual(other: T): boolean;
243 /** Return whether `this` value is negative. */
244 isNegative(): boolean;
245 /** Return whether `this` value is odd. */
246 isOdd(): boolean;
247 /** Return whether `this` value is zero. */
248 isZero(): boolean;
249 /** Return whether `this` is less than the `other`. */
250 lessThan(other: T): boolean;
251 /** Return whether `this` is less than or equal to the `other`. */
252 lessThanOrEqual(other: T): boolean;
253 /** Returns `this` modulo the given `other`. */
254 modulo(other: T): T;
255 /** Returns the product of `this` and the given `other`. */
256 multiply(other: T): T;
257 /** The negation of this value. */
258 negate(): T;
259 /** The bitwise-NOT of this value. */
260 not(): T;
261 /** Return whether `this` does not equal to the `other`. */
262 notEquals(other: T): boolean;
263 /** Returns the bitwise-OR of `this` and the given `other`. */
264 or(other: T): T;
265 /**
266 * Returns `this` with bits shifted to the left by the given amount.
267 * @param numBits The number of bits by which to shift.
268 */
269 shiftLeft(numBits: number): T;
270 /**
271 * Returns `this` with bits shifted to the right by the given amount.
272 * @param numBits The number of bits by which to shift.
273 */
274 shiftRight(numBits: number): T;
275 /**
276 * Returns `this` with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
277 * @param numBits The number of bits by which to shift.
278 */
279 shiftRightUnsigned(numBits: number): T;
280 /** Returns the difference of `this` and the given `other`. */
281 subtract(other: T): T;
282 /** Return the int value (low 32 bits). */
283 toInt(): number;
284 /** Return the JSON value. */
285 toJSON(): string;
286 /** Returns closest floating-point representation to `this` value */
287 toNumber(): number;
288 /**
289 * Return as a string
290 * @param radix the radix in which the text should be written. {default:10}
291 */
292 toString(radix?: number): string;
293 /** Returns the bitwise-XOR of `this` and the given `other`. */
294 xor(other: T): T;
295
296}
297
298/**
299 * A class representation of the BSON Long type, a 64-bit two's-complement
300 * integer value, which faithfully simulates the behavior of a Java "Long". This
301 * implementation is derived from LongLib in GWT.
302 */
303export class Long extends LongLike<Long> {
304
305 static readonly MAX_VALUE: Long;
306 static readonly MIN_VALUE: Long;
307 static readonly NEG_ONE: Long;
308 static readonly ONE: Long;
309 static readonly ZERO: Long;
310
311 /** Returns a Long representing the given (32-bit) integer value. */
312 static fromInt(i: number): Long;
313 /** Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. */
314 static fromNumber(n: number): Long;
315 /**
316 * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
317 * @param lowBits The low 32-bits.
318 * @param highBits The high 32-bits.
319 */
320 static fromBits(lowBits: number, highBits: number): Long;
321 /**
322 * Returns a Long representation of the given string
323 * @param opt_radix The radix in which the text is written. {default:10}
324 */
325 static fromString(s: string, opt_radix?: number): Long;
326
327}
328
329/** A class representation of the BSON Decimal128 type. */
330export class Decimal128 {
331
332 /** Create a Decimal128 instance from a string representation. */
333 static fromString(s: string): Decimal128;
334
335 /**
336 * @param bytes A buffer containing the raw Decimal128 bytes.
337 */
338 constructor(bytes: Buffer);
339
340 /** A buffer containing the raw Decimal128 bytes. */
341 readonly bytes: Buffer;
342
343 toJSON(): string;
344 toString(): string;
345}
346
347/** A class representation of the BSON MaxKey type. */
348export class MaxKey {
349 constructor();
350}
351
352/** A class representation of the BSON MinKey type. */
353export class MinKey {
354 constructor();
355}
356
357/** A class representation of the BSON ObjectId type. */
358export class ObjectId {
359 /**
360 * Create a new ObjectId instance
361 * @param {(string|number|ObjectId)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
362 */
363 constructor(id?: string | number | ObjectId);
364 /** The generation time of this ObjectId instance */
365 generationTime: number;
366 /** If true cache the hex string representation of ObjectId */
367 static cacheHexString?: boolean | undefined;
368 /**
369 * Creates an ObjectId from a hex string representation of an ObjectId.
370 * @param {string} hexString create a ObjectId from a passed in 24 byte hexstring.
371 * @return {ObjectId} return the created ObjectId
372 */
373 static createFromHexString(hexString: string): ObjectId;
374 /**
375 * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
376 * @param {number} time an integer number representing a number of seconds.
377 * @return {ObjectId} return the created ObjectId
378 */
379 static createFromTime(time: number): ObjectId;
380 /**
381 * Checks if a value is a valid bson ObjectId
382 *
383 * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
384 */
385 static isValid(id: string | number | ObjectId): boolean;
386 /**
387 * Compares the equality of this ObjectId with `otherID`.
388 * @param {ObjectId|string} otherID ObjectId instance to compare against.
389 * @return {boolean} the result of comparing two ObjectId's
390 */
391 equals(otherID: ObjectId | string): boolean;
392 /**
393 * Generate a 12 byte id string used in ObjectId's
394 * @param {number} time optional parameter allowing to pass in a second based timestamp.
395 * @return {string} return the 12 byte id binary string.
396 */
397 static generate(time?: number): Buffer;
398 /**
399 * Returns the generation date (accurate up to the second) that this ID was generated.
400 * @return {Date} the generation date
401 */
402 getTimestamp(): Date;
403 /**
404 * Return the ObjectId id as a 24 byte hex string representation
405 * @return {string} return the 24 byte hex string representation.
406 */
407 toHexString(): string;
408}
409
410/**
411 * ObjectID (with capital "D") is deprecated. Use ObjectId (lowercase "d") instead.
412 * @deprecated
413 */
414export { ObjectId as ObjectID };
415
416/** A class representation of the BSON RegExp type. */
417export class BSONRegExp {
418
419 constructor(pattern: string, options: string);
420
421 readonly pattern: string;
422 readonly options: string;
423
424}
425
426/**
427 * A class representation of the BSON Symbol type.
428 * @deprecated
429 */
430export class Symbol {
431
432 constructor(value: string);
433
434 /** Access the wrapped string value. */
435 valueOf(): string;
436
437}
438
439/** A class representation of the BSON Timestamp type. */
440export class Timestamp extends LongLike<Timestamp> {
441
442 static readonly MAX_VALUE: Timestamp;
443 static readonly MIN_VALUE: Timestamp;
444 static readonly NEG_ONE: Timestamp;
445 static readonly ONE: Timestamp;
446 static readonly ZERO: Timestamp;
447
448 /** Returns a Timestamp represented by the given (32-bit) integer value */
449 static fromInt(value: number): Timestamp;
450 /** Returns a Timestamp representing the given number value, provided that it is a finite number. */
451 static fromNumber(value: number): Timestamp;
452 /**
453 * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
454 * @param lowBits The low 32-bits.
455 * @param highBits The high 32-bits.
456 */
457 static fromBits(lowBits: number, highBits: number): Timestamp;
458 /**
459 * Returns a Timestamp from the given string.
460 * @param opt_radix The radix in which the text is written. {default:10}
461 */
462 static fromString(str: string, opt_radix?: number): Timestamp;
463
464}
465
466/**
467 * Functions for serializing JavaScript objects into Mongodb Extended JSON (EJSON).
468 * @namespace EJSON
469 */
470export namespace EJSON {
471
472 /**
473 * Parse an Extended JSON string, constructing the JavaScript value or object described by that
474 * string.
475 *
476 * @memberof EJSON
477 * @param {string} text
478 * @param {object} [options] Optional settings
479 * @param {boolean} [options.relaxed=true] Attempt to return native JS types where possible, rather than BSON types (if true)
480 * @return {object}
481 *
482 * @example
483 * const { EJSON } = require('bson');
484 * const text = '{ "int32": { "$numberInt": "10" } }';
485 *
486 * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
487 * console.log(EJSON.parse(text, { relaxed: false }));
488 *
489 * // prints { int32: 10 }
490 * console.log(EJSON.parse(text));
491 */
492 export function parse(text: string, options?: {relaxed?: boolean | undefined;}): {};
493
494 /**
495 * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
496 *
497 * @memberof EJSON
498 * @param {object} ejson The Extended JSON object to deserialize
499 * @param {object} [options] Optional settings passed to the parse method
500 * @return {object}
501 */
502 export function deserialize(ejson: {}, options?: {relaxed?: boolean | undefined;}): {};
503
504 /**
505 * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
506 *
507 * @memberof EJSON
508 * @param {object} bson The object to serialize
509 * @param {object} [options] Optional settings passed to the `stringify` function
510 * @return {object}
511 */
512 export function serialize(bson: {}, options?: {relaxed?: boolean | undefined;}): {};
513
514 /**
515 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
516 * function is specified or optionally including only the specified properties if a replacer array
517 * is specified.
518 *
519 * @memberof EJSON
520 * @param {object} value The value to convert to extended JSON
521 * @param {function|array} [replacer] A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
522 * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
523 * @param {object} [options] Optional settings.
524 * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
525 * @returns {string}
526 *
527 * @example
528 * const { EJSON, Int32 } = require('bson');
529 * const doc = { int32: new Int32(10) };
530 *
531 * // prints '{"int32":{"$numberInt":"10"}}'
532 * console.log(EJSON.stringify(doc, { relaxed: false }));
533 *
534 * // prints '{"int32":10}'
535 * console.log(EJSON.stringify(doc));
536 */
537 export function stringify(
538 value: {},
539 options?: {relaxed?: boolean | undefined;}
540 ): string;
541
542 /**
543 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
544 * function is specified or optionally including only the specified properties if a replacer array
545 * is specified.
546 *
547 * @memberof EJSON
548 * @param {object} value The value to convert to extended JSON
549 * @param {function|array} [replacer] A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
550 * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
551 * @param {object} [options] Optional settings.
552 * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
553 * @returns {string}
554 *
555 * @example
556 * const { EJSON, Int32 } = require('bson');
557 * const doc = { int32: new Int32(10) };
558 *
559 * // prints '{"int32":{"$numberInt":"10"}}'
560 * console.log(EJSON.stringify(doc, { relaxed: false }));
561 *
562 * // prints '{"int32":10}'
563 * console.log(EJSON.stringify(doc));
564 */
565
566 export function stringify(
567 value: {},
568 replacer: ((key: string, value: any) => any) | Array<string|number> | null | undefined,
569 options?: {relaxed?: boolean | undefined;}
570 ): string;
571 /**
572 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
573 * function is specified or optionally including only the specified properties if a replacer array
574 * is specified.
575 *
576 * @memberof EJSON
577 * @param {object} value The value to convert to extended JSON
578 * @param {function|array} [replacer] A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
579 * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
580 * @param {object} [options] Optional settings.
581 * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
582 * @returns {string}
583 *
584 * @example
585 * const { EJSON, Int32 } = require('bson');
586 * const doc = { int32: new Int32(10) };
587 *
588 * // prints '{"int32":{"$numberInt":"10"}}'
589 * console.log(EJSON.stringify(doc, { relaxed: false }));
590 *
591 * // prints '{"int32":10}'
592 * console.log(EJSON.stringify(doc));
593 */
594 export function stringify(
595 value: {},
596 replacer: ((key: string, value: any) => any) | Array<string | number> | null | undefined,
597 indents?: string | number,
598 options?: {relaxed?: boolean | undefined;}
599 ): string;
600}