source: node_modules/yaml/dist/schema/yaml-1.1/binary.js@ 65b6638

main
Last change on this file since 65b6638 was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 2.6 KB
Line 
1'use strict';
2
3var Scalar = require('../../nodes/Scalar.js');
4var stringifyString = require('../../stringify/stringifyString.js');
5
6const binary = {
7 identify: value => value instanceof Uint8Array,
8 default: false,
9 tag: 'tag:yaml.org,2002:binary',
10 /**
11 * Returns a Buffer in node and an Uint8Array in browsers
12 *
13 * To use the resulting buffer as an image, you'll want to do something like:
14 *
15 * const blob = new Blob([buffer], { type: 'image/jpeg' })
16 * document.querySelector('#photo').src = URL.createObjectURL(blob)
17 */
18 resolve(src, onError) {
19 if (typeof Buffer === 'function') {
20 return Buffer.from(src, 'base64');
21 }
22 else if (typeof atob === 'function') {
23 // On IE 11, atob() can't handle newlines
24 const str = atob(src.replace(/[\n\r]/g, ''));
25 const buffer = new Uint8Array(str.length);
26 for (let i = 0; i < str.length; ++i)
27 buffer[i] = str.charCodeAt(i);
28 return buffer;
29 }
30 else {
31 onError('This environment does not support reading binary tags; either Buffer or atob is required');
32 return src;
33 }
34 },
35 stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
36 const buf = value; // checked earlier by binary.identify()
37 let str;
38 if (typeof Buffer === 'function') {
39 str =
40 buf instanceof Buffer
41 ? buf.toString('base64')
42 : Buffer.from(buf.buffer).toString('base64');
43 }
44 else if (typeof btoa === 'function') {
45 let s = '';
46 for (let i = 0; i < buf.length; ++i)
47 s += String.fromCharCode(buf[i]);
48 str = btoa(s);
49 }
50 else {
51 throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
52 }
53 if (!type)
54 type = Scalar.Scalar.BLOCK_LITERAL;
55 if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
56 const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
57 const n = Math.ceil(str.length / lineWidth);
58 const lines = new Array(n);
59 for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
60 lines[i] = str.substr(o, lineWidth);
61 }
62 str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\n' : ' ');
63 }
64 return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
65 }
66};
67
68exports.binary = binary;
Note: See TracBrowser for help on using the repository browser.