bson 5.2.0 β†’ 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/binary.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils';
2
1
  import { isUint8Array } from './parser/utils';
3
2
  import type { EJSONOptions } from './extended_json';
4
3
  import { BSONError } from './error';
@@ -224,8 +223,9 @@ export class Binary extends BSONValue {
224
223
  toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string {
225
224
  if (encoding === 'hex') return ByteUtils.toHex(this.buffer);
226
225
  if (encoding === 'base64') return ByteUtils.toBase64(this.buffer);
227
- if (encoding === 'utf8' || encoding === 'utf-8') return ByteUtils.toUTF8(this.buffer);
228
- return ByteUtils.toUTF8(this.buffer);
226
+ if (encoding === 'utf8' || encoding === 'utf-8')
227
+ return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
228
+ return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
229
229
  }
230
230
 
231
231
  /** @internal */
@@ -288,7 +288,7 @@ export class Binary extends BSONValue {
288
288
  }
289
289
  } else if ('$uuid' in doc) {
290
290
  type = 4;
291
- data = uuidHexStringToBuffer(doc.$uuid);
291
+ data = UUID.bytesFromString(doc.$uuid);
292
292
  }
293
293
  if (!data) {
294
294
  throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
@@ -311,42 +311,41 @@ export class Binary extends BSONValue {
311
311
  export type UUIDExtended = {
312
312
  $uuid: string;
313
313
  };
314
+
314
315
  const UUID_BYTE_LENGTH = 16;
316
+ const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
317
+ 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;
315
318
 
316
319
  /**
317
320
  * A class representation of the BSON UUID type.
318
321
  * @public
319
322
  */
320
323
  export class UUID extends Binary {
321
- static cacheHexString: boolean;
322
-
323
- /** UUID hexString cache @internal */
324
- private __id?: string;
325
-
324
+ /** @deprecated Hex string is no longer cached, this control will be removed in a future major release */
325
+ static cacheHexString = false;
326
326
  /**
327
- * Create an UUID type
327
+ * Create a UUID type
328
+ *
329
+ * When the argument to the constructor is omitted a random v4 UUID will be generated.
328
330
  *
329
331
  * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
330
332
  */
331
333
  constructor(input?: string | Uint8Array | UUID) {
332
334
  let bytes: Uint8Array;
333
- let hexStr;
334
335
  if (input == null) {
335
336
  bytes = UUID.generate();
336
337
  } else if (input instanceof UUID) {
337
338
  bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
338
- hexStr = input.__id;
339
339
  } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
340
340
  bytes = ByteUtils.toLocalBufferType(input);
341
341
  } else if (typeof input === 'string') {
342
- bytes = uuidHexStringToBuffer(input);
342
+ bytes = UUID.bytesFromString(input);
343
343
  } else {
344
344
  throw new BSONError(
345
345
  '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).'
346
346
  );
347
347
  }
348
348
  super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
349
- this.__id = hexStr;
350
349
  }
351
350
 
352
351
  /**
@@ -359,28 +358,23 @@ export class UUID extends Binary {
359
358
 
360
359
  set id(value: Uint8Array) {
361
360
  this.buffer = value;
362
-
363
- if (UUID.cacheHexString) {
364
- this.__id = bufferToUuidHexString(value);
365
- }
366
361
  }
367
362
 
368
363
  /**
369
364
  * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
370
365
  * @param includeDashes - should the string exclude dash-separators.
371
- * */
366
+ */
372
367
  toHexString(includeDashes = true): string {
373
- if (UUID.cacheHexString && this.__id) {
374
- return this.__id;
368
+ if (includeDashes) {
369
+ return [
370
+ ByteUtils.toHex(this.buffer.subarray(0, 4)),
371
+ ByteUtils.toHex(this.buffer.subarray(4, 6)),
372
+ ByteUtils.toHex(this.buffer.subarray(6, 8)),
373
+ ByteUtils.toHex(this.buffer.subarray(8, 10)),
374
+ ByteUtils.toHex(this.buffer.subarray(10, 16))
375
+ ].join('-');
375
376
  }
376
-
377
- const uuidHexString = bufferToUuidHexString(this.id, includeDashes);
378
-
379
- if (UUID.cacheHexString) {
380
- this.__id = uuidHexString;
381
- }
382
-
383
- return uuidHexString;
377
+ return ByteUtils.toHex(this.buffer);
384
378
  }
385
379
 
386
380
  /**
@@ -446,29 +440,24 @@ export class UUID extends Binary {
446
440
  * Checks if a value is a valid bson UUID
447
441
  * @param input - UUID, string or Buffer to validate.
448
442
  */
449
- static isValid(input: string | Uint8Array | UUID): boolean {
443
+ static isValid(input: string | Uint8Array | UUID | Binary): boolean {
450
444
  if (!input) {
451
445
  return false;
452
446
  }
453
447
 
454
- if (input instanceof UUID) {
455
- return true;
456
- }
457
-
458
448
  if (typeof input === 'string') {
459
- return uuidValidateString(input);
449
+ return UUID.isValidUUIDString(input);
460
450
  }
461
451
 
462
452
  if (isUint8Array(input)) {
463
- // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
464
- if (input.byteLength !== UUID_BYTE_LENGTH) {
465
- return false;
466
- }
467
-
468
- return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80;
453
+ return input.byteLength === UUID_BYTE_LENGTH;
469
454
  }
470
455
 
471
- return false;
456
+ return (
457
+ input._bsontype === 'Binary' &&
458
+ input.sub_type === this.SUBTYPE_UUID &&
459
+ input.buffer.byteLength === 16
460
+ );
472
461
  }
473
462
 
474
463
  /**
@@ -476,7 +465,7 @@ export class UUID extends Binary {
476
465
  * @param hexString - 32 or 36 character hex string (dashes excluded/included).
477
466
  */
478
467
  static override createFromHexString(hexString: string): UUID {
479
- const buffer = uuidHexStringToBuffer(hexString);
468
+ const buffer = UUID.bytesFromString(hexString);
480
469
  return new UUID(buffer);
481
470
  }
482
471
 
@@ -485,6 +474,26 @@ export class UUID extends Binary {
485
474
  return new UUID(ByteUtils.fromBase64(base64));
486
475
  }
487
476
 
477
+ /** @internal */
478
+ static bytesFromString(representation: string) {
479
+ if (!UUID.isValidUUIDString(representation)) {
480
+ throw new BSONError(
481
+ 'UUID string representation must be 32 hex digits or canonical hyphenated representation'
482
+ );
483
+ }
484
+ return ByteUtils.fromHex(representation.replace(/-/g, ''));
485
+ }
486
+
487
+ /**
488
+ * @internal
489
+ *
490
+ * Validates a string to be a hex digit sequence with or without dashes.
491
+ * The canonical hyphenated representation of a uuid is hex in 8-4-4-4-12 groups.
492
+ */
493
+ static isValidUUIDString(representation: string) {
494
+ return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
495
+ }
496
+
488
497
  /**
489
498
  * Converts to a string representation of this Id.
490
499
  *
package/src/bson.ts CHANGED
@@ -10,8 +10,8 @@ import { MinKey } from './min_key';
10
10
  import { ObjectId } from './objectid';
11
11
  import { internalCalculateObjectSize } from './parser/calculate_size';
12
12
  // Parts of the parser
13
- import { internalDeserialize, DeserializeOptions } from './parser/deserializer';
14
- import { serializeInto, SerializeOptions } from './parser/serializer';
13
+ import { internalDeserialize, type DeserializeOptions } from './parser/deserializer';
14
+ import { serializeInto, type SerializeOptions } from './parser/serializer';
15
15
  import { BSONRegExp } from './regexp';
16
16
  import { BSONSymbol } from './symbol';
17
17
  import { Timestamp } from './timestamp';
@@ -70,7 +70,7 @@ let buffer = ByteUtils.allocate(MAXSIZE);
70
70
  /**
71
71
  * Sets the size of the internal serialization buffer.
72
72
  *
73
- * @param size - The desired size for the internal serialization buffer
73
+ * @param size - The desired size for the internal serialization buffer in bytes
74
74
  * @public
75
75
  */
76
76
  export function setInternalBufferSize(size: number): void {
package/src/constants.ts CHANGED
@@ -138,4 +138,4 @@ export const BSONType = Object.freeze({
138
138
  } as const);
139
139
 
140
140
  /** @public */
141
- export type BSONType = typeof BSONType[keyof typeof BSONType];
141
+ export type BSONType = (typeof BSONType)[keyof typeof BSONType];
@@ -24,11 +24,19 @@ import { Timestamp } from './timestamp';
24
24
 
25
25
  /** @public */
26
26
  export type EJSONOptions = {
27
- /** Output using the Extended JSON v1 spec */
27
+ /**
28
+ * Output using the Extended JSON v1 spec
29
+ * @defaultValue `false`
30
+ */
28
31
  legacy?: boolean;
29
- /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */
32
+ /**
33
+ * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types
34
+ * @defaultValue `false` */
30
35
  relaxed?: boolean;
31
- /** Enable native bigint support */
36
+ /**
37
+ * Enable native bigint support
38
+ * @defaultValue `false`
39
+ */
32
40
  useBigInt64?: boolean;
33
41
  };
34
42
 
@@ -1,8 +1,8 @@
1
- import { Binary } from '../binary';
1
+ import { Binary, UUID } from '../binary';
2
2
  import type { Document } from '../bson';
3
3
  import { Code } from '../code';
4
4
  import * as constants from '../constants';
5
- import { DBRef, DBRefLike, isDBRefLike } from '../db_ref';
5
+ import { DBRef, type DBRefLike, isDBRefLike } from '../db_ref';
6
6
  import { Decimal128 } from '../decimal128';
7
7
  import { Double } from '../double';
8
8
  import { BSONError } from '../error';
@@ -19,21 +19,45 @@ import { validateUtf8 } from '../validate_utf8';
19
19
 
20
20
  /** @public */
21
21
  export interface DeserializeOptions {
22
- /** when deserializing a Long will return as a BigInt. */
22
+ /**
23
+ * when deserializing a Long return as a BigInt.
24
+ * @defaultValue `false`
25
+ */
23
26
  useBigInt64?: boolean;
24
- /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits. */
27
+ /**
28
+ * when deserializing a Long will fit it into a Number if it's smaller than 53 bits.
29
+ * @defaultValue `true`
30
+ */
25
31
  promoteLongs?: boolean;
26
- /** when deserializing a Binary will return it as a node.js Buffer instance. */
32
+ /**
33
+ * when deserializing a Binary will return it as a node.js Buffer instance.
34
+ * @defaultValue `false`
35
+ */
27
36
  promoteBuffers?: boolean;
28
- /** when deserializing will promote BSON values to their Node.js closest equivalent types. */
37
+ /**
38
+ * when deserializing will promote BSON values to their Node.js closest equivalent types.
39
+ * @defaultValue `true`
40
+ */
29
41
  promoteValues?: boolean;
30
- /** allow to specify if there what fields we wish to return as unserialized raw buffer. */
42
+ /**
43
+ * allow to specify if there what fields we wish to return as unserialized raw buffer.
44
+ * @defaultValue `null`
45
+ */
31
46
  fieldsAsRaw?: Document;
32
- /** return BSON regular expressions as BSONRegExp instances. */
47
+ /**
48
+ * return BSON regular expressions as BSONRegExp instances.
49
+ * @defaultValue `false`
50
+ */
33
51
  bsonRegExp?: boolean;
34
- /** allows the buffer to be larger than the parsed BSON object. */
52
+ /**
53
+ * allows the buffer to be larger than the parsed BSON object.
54
+ * @defaultValue `false`
55
+ */
35
56
  allowObjectSmallerThanBufferSize?: boolean;
36
- /** Offset into buffer to begin reading document from */
57
+ /**
58
+ * Offset into buffer to begin reading document from
59
+ * @defaultValue `0`
60
+ */
37
61
  index?: number;
38
62
 
39
63
  raw?: boolean;
@@ -212,7 +236,7 @@ function deserializeObject(
212
236
  if (i >= buffer.byteLength) throw new BSONError('Bad BSON Document: illegal CString');
213
237
 
214
238
  // Represents the key
215
- const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i));
239
+ const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i);
216
240
 
217
241
  // shouldValidateKey is true if the key should be validated, false otherwise
218
242
  let shouldValidateKey = true;
@@ -404,7 +428,7 @@ function deserializeObject(
404
428
  value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize));
405
429
  } else {
406
430
  value = new Binary(buffer.slice(index, index + binarySize), subType);
407
- if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) {
431
+ if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
408
432
  value = value.toUUID();
409
433
  }
410
434
  }
@@ -432,10 +456,11 @@ function deserializeObject(
432
456
 
433
457
  if (promoteBuffers && promoteValues) {
434
458
  value = _buffer;
435
- } else if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) {
436
- value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID();
437
459
  } else {
438
460
  value = new Binary(buffer.slice(index, index + binarySize), subType);
461
+ if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
462
+ value = value.toUUID();
463
+ }
439
464
  }
440
465
  }
441
466
 
@@ -451,7 +476,7 @@ function deserializeObject(
451
476
  // If are at the end of the buffer there is a problem with the document
452
477
  if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
453
478
  // Return the C string
454
- const source = ByteUtils.toUTF8(buffer.subarray(index, i));
479
+ const source = ByteUtils.toUTF8(buffer, index, i);
455
480
  // Create the regexp
456
481
  index = i + 1;
457
482
 
@@ -464,7 +489,7 @@ function deserializeObject(
464
489
  // If are at the end of the buffer there is a problem with the document
465
490
  if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
466
491
  // Return the C string
467
- const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i));
492
+ const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
468
493
  index = i + 1;
469
494
 
470
495
  // For each option add the corresponding one for javascript
@@ -496,7 +521,7 @@ function deserializeObject(
496
521
  // If are at the end of the buffer there is a problem with the document
497
522
  if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
498
523
  // Return the C string
499
- const source = ByteUtils.toUTF8(buffer.subarray(index, i));
524
+ const source = ByteUtils.toUTF8(buffer, index, i);
500
525
  index = i + 1;
501
526
 
502
527
  // Get the start search index
@@ -508,7 +533,7 @@ function deserializeObject(
508
533
  // If are at the end of the buffer there is a problem with the document
509
534
  if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
510
535
  // Return the C string
511
- const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i));
536
+ const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
512
537
  index = i + 1;
513
538
 
514
539
  // Set the object
@@ -653,7 +678,7 @@ function deserializeObject(
653
678
  throw new BSONError('Invalid UTF-8 string in BSON document');
654
679
  }
655
680
  }
656
- const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1));
681
+ const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1);
657
682
  // Update parse index position
658
683
  index = index + stringSize;
659
684
 
@@ -710,7 +735,7 @@ function getValidatedString(
710
735
  end: number,
711
736
  shouldValidateUtf8: boolean
712
737
  ) {
713
- const value = ByteUtils.toUTF8(buffer.subarray(start, end));
738
+ const value = ByteUtils.toUTF8(buffer, start, end);
714
739
  // if utf8 validation is on, do the check
715
740
  if (shouldValidateUtf8) {
716
741
  for (let i = 0; i < value.length; i++) {
@@ -16,15 +16,28 @@ import { isAnyArrayBuffer, isDate, isMap, isRegExp, isUint8Array } from './utils
16
16
 
17
17
  /** @public */
18
18
  export interface SerializeOptions {
19
- /** the serializer will check if keys are valid. */
19
+ /**
20
+ * the serializer will check if keys are valid.
21
+ * @defaultValue `false`
22
+ */
20
23
  checkKeys?: boolean;
21
- /** serialize the javascript functions **(default:false)**. */
24
+ /**
25
+ * serialize the javascript functions
26
+ * @defaultValue `false`
27
+ */
22
28
  serializeFunctions?: boolean;
23
- /** serialize will not emit undefined fields **(default:true)** */
29
+ /**
30
+ * serialize will not emit undefined fields
31
+ * note that the driver sets this to `false`
32
+ * @defaultValue `true`
33
+ */
24
34
  ignoreUndefined?: boolean;
25
35
  /** @internal Resize internal buffer */
26
36
  minInternalBufferSize?: number;
27
- /** the index in the buffer where we wish to start serializing into */
37
+ /**
38
+ * the index in the buffer where we wish to start serializing into
39
+ * @defaultValue `0`
40
+ */
28
41
  index?: number;
29
42
  }
30
43
 
package/src/timestamp.ts CHANGED
@@ -27,7 +27,7 @@ export interface TimestampExtended {
27
27
  /**
28
28
  * @public
29
29
  * @category BSONType
30
- * */
30
+ */
31
31
  export class Timestamp extends LongWithoutOverridesClass {
32
32
  get _bsontype(): 'Timestamp' {
33
33
  return 'Timestamp';
@@ -61,24 +61,26 @@ export class Timestamp extends LongWithoutOverridesClass {
61
61
  if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
62
62
  throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
63
63
  }
64
- if (low.t < 0) {
64
+ const t = Number(low.t);
65
+ const i = Number(low.i);
66
+ if (t < 0 || Number.isNaN(t)) {
65
67
  throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
66
68
  }
67
- if (low.i < 0) {
69
+ if (i < 0 || Number.isNaN(i)) {
68
70
  throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
69
71
  }
70
- if (low.t > 0xffff_ffff) {
72
+ if (t > 0xffff_ffff) {
71
73
  throw new BSONError(
72
74
  'Timestamp constructed from { t, i } must provide t equal or less than uint32 max'
73
75
  );
74
76
  }
75
- if (low.i > 0xffff_ffff) {
77
+ if (i > 0xffff_ffff) {
76
78
  throw new BSONError(
77
79
  'Timestamp constructed from { t, i } must provide i equal or less than uint32 max'
78
80
  );
79
81
  }
80
82
 
81
- super(low.i.valueOf(), low.t.valueOf(), true);
83
+ super(i, t, true);
82
84
  } else {
83
85
  throw new BSONError(
84
86
  'A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'
@@ -26,7 +26,7 @@ export type ByteUtils = {
26
26
  /** Create a Uint8Array containing utf8 code units from a string */
27
27
  fromUTF8: (text: string) => Uint8Array;
28
28
  /** Create a string from utf8 code units */
29
- toUTF8: (buffer: Uint8Array) => string;
29
+ toUTF8: (buffer: Uint8Array, start: number, end: number) => string;
30
30
  /** Get the utf8 code unit count from a string if it were to be transformed to utf8 */
31
31
  utf8ByteLength: (input: string) => number;
32
32
  /** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */
@@ -5,7 +5,7 @@ type NodeJsBuffer = ArrayBufferView &
5
5
  Uint8Array & {
6
6
  write(string: string, offset: number, length: undefined, encoding: 'utf8'): number;
7
7
  copy(target: Uint8Array, targetStart: number, sourceStart: number, sourceEnd: number): number;
8
- toString: (this: Uint8Array, encoding: NodeJsEncoding) => string;
8
+ toString: (this: Uint8Array, encoding: NodeJsEncoding, start?: number, end?: number) => string;
9
9
  equals: (this: Uint8Array, other: Uint8Array) => boolean;
10
10
  };
11
11
  type NodeJsBufferConstructor = Omit<Uint8ArrayConstructor, 'from'> & {
@@ -125,8 +125,8 @@ export const nodeJsByteUtils = {
125
125
  return Buffer.from(text, 'utf8');
126
126
  },
127
127
 
128
- toUTF8(buffer: Uint8Array): string {
129
- return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8');
128
+ toUTF8(buffer: Uint8Array, start: number, end: number): string {
129
+ return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
130
130
  },
131
131
 
132
132
  utf8ByteLength(input: string): number {
@@ -172,8 +172,8 @@ export const webByteUtils = {
172
172
  return new TextEncoder().encode(text);
173
173
  },
174
174
 
175
- toUTF8(uint8array: Uint8Array): string {
176
- return new TextDecoder('utf8', { fatal: false }).decode(uint8array);
175
+ toUTF8(uint8array: Uint8Array, start: number, end: number): string {
176
+ return new TextDecoder('utf8', { fatal: false }).decode(uint8array.slice(start, end));
177
177
  },
178
178
 
179
179
  utf8ByteLength(input: string): number {
@@ -0,0 +1,20 @@
1
+ Copyright Mathias Bynens <https://mathiasbynens.be/>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,112 @@
1
+ # base64 [![Build status](https://travis-ci.org/mathiasbynens/base64.svg?branch=master)](https://travis-ci.org/mathiasbynens/base64) [![Code coverage status](http://img.shields.io/coveralls/mathiasbynens/base64/master.svg)](https://coveralls.io/r/mathiasbynens/base64)
2
+
3
+ _base64_ is a robust base64 encoder/decoder that is fully compatible with [`atob()` and `btoa()`](https://html.spec.whatwg.org/multipage/webappapis.html#atob), written in JavaScript. The base64-encoding and -decoding algorithms it uses are fully [RFC 4648](https://tools.ietf.org/html/rfc4648#section-4) compliant.
4
+
5
+ ## Installation
6
+
7
+ Via [npm](https://www.npmjs.com/):
8
+
9
+ ```bash
10
+ npm install base-64
11
+ ```
12
+
13
+ In a browser:
14
+
15
+ ```html
16
+ <script src="base64.js"></script>
17
+ ```
18
+
19
+ In [Narwhal](http://narwhaljs.org/), [Node.js](https://nodejs.org/), and [RingoJS](http://ringojs.org/):
20
+
21
+ ```js
22
+ var base64 = require('base-64');
23
+ ```
24
+
25
+ In [Rhino](http://www.mozilla.org/rhino/):
26
+
27
+ ```js
28
+ load('base64.js');
29
+ ```
30
+
31
+ Using an AMD loader like [RequireJS](http://requirejs.org/):
32
+
33
+ ```js
34
+ require(
35
+ {
36
+ 'paths': {
37
+ 'base64': 'path/to/base64'
38
+ }
39
+ },
40
+ ['base64'],
41
+ function(base64) {
42
+ console.log(base64);
43
+ }
44
+ );
45
+ ```
46
+
47
+ ## API
48
+
49
+ ### `base64.version`
50
+
51
+ A string representing the semantic version number.
52
+
53
+ ### `base64.encode(input)`
54
+
55
+ This function takes a byte string (the `input` parameter) and encodes it according to base64. The input data must be in the form of a string containing only characters in the range from U+0000 to U+00FF, each representing a binary byte with values `0x00` to `0xFF`. The `base64.encode()` function is designed to be fully compatible with [`btoa()` as described in the HTML Standard](https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-btoa).
56
+
57
+ ```js
58
+ var encodedData = base64.encode(input);
59
+ ```
60
+
61
+ To base64-encode any Unicode string, [encode it as UTF-8 first](https://github.com/mathiasbynens/utf8.js#utf8encodestring):
62
+
63
+ ```js
64
+ var base64 = require('base-64');
65
+ var utf8 = require('utf8');
66
+
67
+ var text = 'foo Β© bar πŒ† baz';
68
+ var bytes = utf8.encode(text);
69
+ var encoded = base64.encode(bytes);
70
+ console.log(encoded);
71
+ // β†’ 'Zm9vIMKpIGJhciDwnYyGIGJheg=='
72
+ ```
73
+
74
+ ### `base64.decode(input)`
75
+
76
+ This function takes a base64-encoded string (the `input` parameter) and decodes it. The return value is in the form of a string containing only characters in the range from U+0000 to U+00FF, each representing a binary byte with values `0x00` to `0xFF`. The `base64.decode()` function is designed to be fully compatible with [`atob()` as described in the HTML Standard](https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-atob).
77
+
78
+ ```js
79
+ var decodedData = base64.decode(encodedData);
80
+ ```
81
+
82
+ To base64-decode UTF-8-encoded data back into a Unicode string, [UTF-8-decode it](https://github.com/mathiasbynens/utf8.js#utf8decodebytestring) after base64-decoding it:
83
+
84
+ ```js
85
+ var encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg==';
86
+ var bytes = base64.decode(encoded);
87
+ var text = utf8.decode(bytes);
88
+ console.log(text);
89
+ // β†’ 'foo Β© bar πŒ† baz'
90
+ ```
91
+
92
+ ## Support
93
+
94
+ _base64_ is designed to work in at least Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.9, PhantomJS 1.9.0, Rhino 1.7RC4, as well as old and modern versions of Chrome, Firefox, Safari, Opera, and Internet Explorer.
95
+
96
+ ## Unit tests & code coverage
97
+
98
+ After cloning this repository, run `npm install` to install the dependencies needed for development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`.
99
+
100
+ Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`.
101
+
102
+ To generate the code coverage report, use `grunt cover`.
103
+
104
+ ## Author
105
+
106
+ | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
107
+ |---|
108
+ | [Mathias Bynens](https://mathiasbynens.be/) |
109
+
110
+ ## License
111
+
112
+ _base64_ is available under the [MIT](https://mths.be/mit) license.