/
binary.ts
508 lines (447 loc) · 15.3 KB
/
binary.ts
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
import { isUint8Array } from './parser/utils';
import type { EJSONOptions } from './extended_json';
import { BSONError } from './error';
import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants';
import { ByteUtils } from './utils/byte_utils';
import { BSONValue } from './bson_value';
/** @public */
export type BinarySequence = Uint8Array | number[];
/** @public */
export interface BinaryExtendedLegacy {
$type: string;
$binary: string;
}
/** @public */
export interface BinaryExtended {
$binary: {
subType: string;
base64: string;
};
}
/**
* A class representation of the BSON Binary type.
* @public
* @category BSONType
*/
export class Binary extends BSONValue {
get _bsontype(): 'Binary' {
return 'Binary';
}
/**
* Binary default subtype
* @internal
*/
private static readonly BSON_BINARY_SUBTYPE_DEFAULT = 0;
/** Initial buffer default size */
static readonly BUFFER_SIZE = 256;
/** Default BSON type */
static readonly SUBTYPE_DEFAULT = 0;
/** Function BSON type */
static readonly SUBTYPE_FUNCTION = 1;
/** Byte Array BSON type */
static readonly SUBTYPE_BYTE_ARRAY = 2;
/** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
static readonly SUBTYPE_UUID_OLD = 3;
/** UUID BSON type */
static readonly SUBTYPE_UUID = 4;
/** MD5 BSON type */
static readonly SUBTYPE_MD5 = 5;
/** Encrypted BSON type */
static readonly SUBTYPE_ENCRYPTED = 6;
/** Column BSON type */
static readonly SUBTYPE_COLUMN = 7;
/** User BSON type */
static readonly SUBTYPE_USER_DEFINED = 128;
buffer!: Uint8Array;
sub_type!: number;
position!: number;
/**
* Create a new Binary instance.
*
* This constructor can accept a string as its first argument. In this case,
* this string will be encoded using ISO-8859-1, **not** using UTF-8.
* This is almost certainly not what you want. Use `new Binary(Buffer.from(string))`
* instead to convert the string to a Buffer using UTF-8 first.
*
* @param buffer - a buffer object containing the binary data.
* @param subType - the option binary type.
*/
constructor(buffer?: string | BinarySequence, subType?: number) {
super();
if (
!(buffer == null) &&
!(typeof buffer === 'string') &&
!ArrayBuffer.isView(buffer) &&
!(buffer instanceof ArrayBuffer) &&
!Array.isArray(buffer)
) {
throw new BSONError(
'Binary can only be constructed from string, Buffer, TypedArray, or Array<number>'
);
}
this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
if (buffer == null) {
// create an empty binary buffer
this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
this.position = 0;
} else {
if (typeof buffer === 'string') {
// string
this.buffer = ByteUtils.fromISO88591(buffer);
} else if (Array.isArray(buffer)) {
// number[]
this.buffer = ByteUtils.fromNumberArray(buffer);
} else {
// Buffer | TypedArray | ArrayBuffer
this.buffer = ByteUtils.toLocalBufferType(buffer);
}
this.position = this.buffer.byteLength;
}
}
/**
* Updates this binary with byte_value.
*
* @param byteValue - a single byte we wish to write.
*/
put(byteValue: string | number | Uint8Array | number[]): void {
// If it's a string and a has more than one character throw an error
if (typeof byteValue === 'string' && byteValue.length !== 1) {
throw new BSONError('only accepts single character String');
} else if (typeof byteValue !== 'number' && byteValue.length !== 1)
throw new BSONError('only accepts single character Uint8Array or Array');
// Decode the byte value once
let decodedByte: number;
if (typeof byteValue === 'string') {
decodedByte = byteValue.charCodeAt(0);
} else if (typeof byteValue === 'number') {
decodedByte = byteValue;
} else {
decodedByte = byteValue[0];
}
if (decodedByte < 0 || decodedByte > 255) {
throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
}
if (this.buffer.byteLength > this.position) {
this.buffer[this.position++] = decodedByte;
} else {
const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
newSpace.set(this.buffer, 0);
this.buffer = newSpace;
this.buffer[this.position++] = decodedByte;
}
}
/**
* Writes a buffer or string to the binary.
*
* @param sequence - a string or buffer to be written to the Binary BSON object.
* @param offset - specify the binary of where to write the content.
*/
write(sequence: string | BinarySequence, offset: number): void {
offset = typeof offset === 'number' ? offset : this.position;
// If the buffer is to small let's extend the buffer
if (this.buffer.byteLength < offset + sequence.length) {
const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
newSpace.set(this.buffer, 0);
// Assign the new buffer
this.buffer = newSpace;
}
if (ArrayBuffer.isView(sequence)) {
this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
this.position =
offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
} else if (typeof sequence === 'string') {
const bytes = ByteUtils.fromISO88591(sequence);
this.buffer.set(bytes, offset);
this.position =
offset + sequence.length > this.position ? offset + sequence.length : this.position;
}
}
/**
* Reads **length** bytes starting at **position**.
*
* @param position - read from the given position in the Binary.
* @param length - the number of bytes to read.
*/
read(position: number, length: number): BinarySequence {
length = length && length > 0 ? length : this.position;
// Let's return the data based on the type we have
return this.buffer.slice(position, position + length);
}
/**
* Returns the value of this binary as a string.
* @param asRaw - Will skip converting to a string
* @remarks
* This is handy when calling this function conditionally for some key value pairs and not others
*/
value(asRaw?: boolean): string | BinarySequence {
asRaw = !!asRaw;
// Optimize to serialize for the situation where the data == size of buffer
if (asRaw && this.buffer.length === this.position) {
return this.buffer;
}
// If it's a node.js buffer object
if (asRaw) {
return this.buffer.slice(0, this.position);
}
// TODO(NODE-4361): remove binary string support, value(true) should be the default / only option here.
return ByteUtils.toISO88591(this.buffer.subarray(0, this.position));
}
/** the length of the binary sequence */
length(): number {
return this.position;
}
toJSON(): string {
return ByteUtils.toBase64(this.buffer);
}
toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string {
if (encoding === 'hex') return ByteUtils.toHex(this.buffer);
if (encoding === 'base64') return ByteUtils.toBase64(this.buffer);
if (encoding === 'utf8' || encoding === 'utf-8')
return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
}
/** @internal */
toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended {
options = options || {};
const base64String = ByteUtils.toBase64(this.buffer);
const subType = Number(this.sub_type).toString(16);
if (options.legacy) {
return {
$binary: base64String,
$type: subType.length === 1 ? '0' + subType : subType
};
}
return {
$binary: {
base64: base64String,
subType: subType.length === 1 ? '0' + subType : subType
}
};
}
toUUID(): UUID {
if (this.sub_type === Binary.SUBTYPE_UUID) {
return new UUID(this.buffer.slice(0, this.position));
}
throw new BSONError(
`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`
);
}
/** Creates an Binary instance from a hex digit string */
static createFromHexString(hex: string, subType?: number): Binary {
return new Binary(ByteUtils.fromHex(hex), subType);
}
/** Creates an Binary instance from a base64 string */
static createFromBase64(base64: string, subType?: number): Binary {
return new Binary(ByteUtils.fromBase64(base64), subType);
}
/** @internal */
static fromExtendedJSON(
doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended,
options?: EJSONOptions
): Binary {
options = options || {};
let data: Uint8Array | undefined;
let type;
if ('$binary' in doc) {
if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
type = doc.$type ? parseInt(doc.$type, 16) : 0;
data = ByteUtils.fromBase64(doc.$binary);
} else {
if (typeof doc.$binary !== 'string') {
type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
data = ByteUtils.fromBase64(doc.$binary.base64);
}
}
} else if ('$uuid' in doc) {
type = 4;
data = UUID.bytesFromString(doc.$uuid);
}
if (!data) {
throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
}
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 {
const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
}
}
/** @public */
export type UUIDExtended = {
$uuid: string;
};
const UUID_BYTE_LENGTH = 16;
const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
/**
* A class representation of the BSON UUID type.
* @public
*/
export class UUID extends Binary {
/**
* Create a UUID type
*
* When the argument to the constructor is omitted a random v4 UUID will be generated.
*
* @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
*/
constructor(input?: string | Uint8Array | UUID) {
let bytes: Uint8Array;
if (input == null) {
bytes = UUID.generate();
} else if (input instanceof UUID) {
bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
} else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
bytes = ByteUtils.toLocalBufferType(input);
} else if (typeof input === 'string') {
bytes = UUID.bytesFromString(input);
} else {
throw new BSONError(
'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'
);
}
super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
}
/**
* The UUID bytes
* @readonly
*/
get id(): Uint8Array {
return this.buffer;
}
set id(value: Uint8Array) {
this.buffer = value;
}
/**
* Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
* @param includeDashes - should the string exclude dash-separators.
*/
toHexString(includeDashes = true): string {
if (includeDashes) {
return [
ByteUtils.toHex(this.buffer.subarray(0, 4)),
ByteUtils.toHex(this.buffer.subarray(4, 6)),
ByteUtils.toHex(this.buffer.subarray(6, 8)),
ByteUtils.toHex(this.buffer.subarray(8, 10)),
ByteUtils.toHex(this.buffer.subarray(10, 16))
].join('-');
}
return ByteUtils.toHex(this.buffer);
}
/**
* Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
*/
toString(encoding?: 'hex' | 'base64'): string {
if (encoding === 'hex') return ByteUtils.toHex(this.id);
if (encoding === 'base64') return ByteUtils.toBase64(this.id);
return this.toHexString();
}
/**
* Converts the id into its JSON string representation.
* A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
*/
toJSON(): string {
return this.toHexString();
}
/**
* Compares the equality of this UUID with `otherID`.
*
* @param otherId - UUID instance to compare against.
*/
equals(otherId: string | Uint8Array | UUID): boolean {
if (!otherId) {
return false;
}
if (otherId instanceof UUID) {
return ByteUtils.equals(otherId.id, this.id);
}
try {
return ByteUtils.equals(new UUID(otherId).id, this.id);
} catch {
return false;
}
}
/**
* Creates a Binary instance from the current UUID.
*/
toBinary(): Binary {
return new Binary(this.id, Binary.SUBTYPE_UUID);
}
/**
* Generates a populated buffer containing a v4 uuid
*/
static generate(): Uint8Array {
const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
// Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
return bytes;
}
/**
* Checks if a value is a valid bson UUID
* @param input - UUID, string or Buffer to validate.
*/
static isValid(input: string | Uint8Array | UUID | Binary): boolean {
if (!input) {
return false;
}
if (typeof input === 'string') {
return UUID.isValidUUIDString(input);
}
if (isUint8Array(input)) {
return input.byteLength === UUID_BYTE_LENGTH;
}
return (
input._bsontype === 'Binary' &&
input.sub_type === this.SUBTYPE_UUID &&
input.buffer.byteLength === 16
);
}
/**
* Creates an UUID from a hex string representation of an UUID.
* @param hexString - 32 or 36 character hex string (dashes excluded/included).
*/
static override createFromHexString(hexString: string): UUID {
const buffer = UUID.bytesFromString(hexString);
return new UUID(buffer);
}
/** Creates an UUID from a base64 string representation of an UUID. */
static override createFromBase64(base64: string): UUID {
return new UUID(ByteUtils.fromBase64(base64));
}
/** @internal */
static bytesFromString(representation: string) {
if (!UUID.isValidUUIDString(representation)) {
throw new BSONError(
'UUID string representation must be 32 hex digits or canonical hyphenated representation'
);
}
return ByteUtils.fromHex(representation.replace(/-/g, ''));
}
/**
* @internal
*
* Validates a string to be a hex digit sequence with or without dashes.
* The canonical hyphenated representation of a uuid is hex in 8-4-4-4-12 groups.
*/
static isValidUUIDString(representation: string) {
return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
}
/**
* 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()}")`;
}
}