/
util.js
293 lines (264 loc) · 9.3 KB
/
util.js
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
"use strict";
/**
* Utility functions.
* @namespace
*/
var util = module.exports = {};
var LongBits =
util.LongBits = require("./util/longbits");
util.codegen = require("./util/codegen");
/**
* Whether running within node or not.
* @memberof util
* @type {boolean}
*/
var isNode = util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node);
/**
* Optional buffer class to use.
* If you assign any compatible buffer implementation to this property, the library will use it.
* @type {?Function}
*/
util.Buffer = null;
if (isNode)
try { util.Buffer = require("buffer").Buffer; } catch (e) {} // eslint-disable-line no-empty
/**
* Optional Long class to use.
* If you assign any compatible long implementation to this property, the library will use it.
* @type {?Function}
*/
util.Long = global.Long || null;
try { util.Long = require("long"); } catch (e) {} // eslint-disable-line no-empty
/**
* Tests if the specified value is a string.
* @memberof util
* @param {*} value Value to test
* @returns {boolean} `true` if the value is a string
*/
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
util.isString = isString;
/**
* Tests if the specified value is a non-null object.
* @param {*} value Value to test
* @returns {boolean} `true` if the value is a non-null object
*/
util.isObject = function isObject(value) {
return Boolean(value && typeof value === 'object');
};
/**
* Tests if the specified value is an integer.
* @function
* @param {*} value Value to test
* @returns {boolean} `true` if the value is an integer
*/
util.isInteger = Number.isInteger || function isInteger(value) {
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
};
/**
* Converts an object's values to an array.
* @param {Object.<string,*>} object Object to convert
* @returns {Array.<*>} Converted array
*/
util.toArray = function toArray(object) {
if (!object)
return [];
var names = Object.keys(object),
length = names.length;
var array = new Array(length);
for (var i = 0; i < length; ++i)
array[i] = object[names[i]];
return array;
};
/**
* Creates a type error.
* @param {string} name Argument name
* @param {string} [description=a string] Expected argument descripotion
* @returns {TypeError} Created type error
* @private
*/
util._TypeError = function(name, description) {
return TypeError(name + " must be " + (description || "a string"));
};
/**
* Returns a promise from a node-style function.
* @memberof util
* @param {function(Error, ...*)} fn Function to call
* @param {Object} ctx Function context
* @param {...*} params Function arguments
* @returns {Promise<*>} Promisified function
*/
function asPromise(fn, ctx/*, varargs */) {
var args = [];
for (var i = 2; i < arguments.length; ++i)
args.push(arguments[i]);
return new Promise(function(resolve, reject) {
fn.apply(ctx, args.concat(
function(err/*, varargs */) {
if (err) reject(err);
else resolve.apply(null, Array.prototype.slice.call(arguments, 1));
}
));
});
}
util.asPromise = asPromise;
/**
* Fetches the contents of a file.
* @memberof util
* @param {string} path File path or url
* @param {function(?Error, string=)} [callback] Node-style callback
* @returns {Promise<string>|undefined} Promise if callback has been omitted
*/
function fetch(path, callback) {
if (!callback)
return asPromise(fetch, util, path);
var fs; try { fs = require("fs"); } catch (e) {} // eslint-disable-line no-empty
if (fs && fs.readFile)
return fs.readFile(path, "utf8", callback);
var xhr = new XMLHttpRequest();
function onload() {
if (xhr.status !== 0 && xhr.status !== 200)
return callback(Error("status " + xhr.status));
if (isString(xhr.responseText))
return callback(null, xhr.responseText);
return callback(Error("request failed"));
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4)
onload();
};
xhr.open("GET", path, true);
xhr.send();
return undefined;
}
util.fetch = fetch;
/**
* Tests if the specified path is absolute.
* @memberof util
* @param {string} path Path to test
* @returns {boolean} `true` if path is absolute
*/
function isAbsolutePath(path) {
return /^(?:\/|[a-zA-Z0-9]+:)/.test(path);
}
util.isAbsolutePath = isAbsolutePath;
/**
* Normalizes the specified path.
* @memberof util
* @param {string} path Path to normalize
* @returns {string} Normalized path
*/
function normalizePath(path) {
path = path.replace(/\\/g, '/')
.replace(/\/{2,}/g, '/');
var parts = path.split('/');
var abs = isAbsolutePath(path);
var prefix = "";
if (abs)
prefix = parts.shift() + '/';
for (var i = 0; i < parts.length;) {
if (parts[i] === '..') {
if (i > 0)
parts.splice(--i, 2);
else if (abs)
parts.splice(i, 1);
else
++i;
} else if (parts[i] === '.')
parts.splice(i, 1);
else
++i;
}
return prefix + parts.join('/');
}
util.normalizePath = normalizePath;
/**
* Resolves the specified include path against the specified origin path.
* @param {string} originPath Path that was used to fetch the origin file
* @param {string} importPath Import path specified in the origin file
* @param {boolean} [alreadyNormalized] `true` if both paths are already known to be normalized
* @returns {string} Path to the imported file
*/
util.resolvePath = function resolvePath(originPath, importPath, alreadyNormalized) {
if (!alreadyNormalized)
importPath = normalizePath(importPath);
if (isAbsolutePath(importPath))
return importPath;
if (!alreadyNormalized)
originPath = normalizePath(originPath);
originPath = originPath.replace(/(?:\/|^)[^/]+$/, '');
return originPath.length ? normalizePath(originPath + '/' + importPath) : importPath;
};
/**
* Converts a number or long to an 8 characters long hash string.
* @param {Long|number} value Value to convert
* @returns {string} Hash
*/
util.longToHash = function longToHash(value) {
return value
? LongBits.from(value).toHash()
: '\0\0\0\0\0\0\0\0';
};
/**
* Converts an 8 characters long hash string to a long or number.
* @param {string} hash Hash
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {Long|number} Original value
*/
util.longFromHash = function longFromHash(hash, unsigned) {
var bits = LongBits.fromHash(hash);
if (util.Long)
return util.Long.fromBits(bits.lo, bits.hi, unsigned);
return bits.toNumber(Boolean(unsigned));
};
/**
* Tests if two possibly long values are not equal.
* @param {number|Long} a First value
* @param {number|Long} b Second value
* @returns {boolean} `true` if not equal
*/
util.longNeq = function longNeq(a, b) {
return typeof a === 'number'
? typeof b === 'number'
? a !== b
: (a = LongBits.fromNumber(a)).lo !== b.low || a.hi !== b.high
: typeof b === 'number'
? (b = LongBits.fromNumber(b)).lo !== a.low || b.hi !== a.high
: a.low !== b.low || a.high !== b.high;
};
/**
* Merges the properties of the source object into the destination object.
* @param {Object} dst Destination object
* @param {Object} src Source object
* @param {boolean} [ifNotSet=false] Merges only if the key is not already set
* @returns {Object} Destination object
*/
util.merge = function merge(dst, src, ifNotSet) {
if (src) {
var keys = Object.keys(src);
for (var i = 0; i < keys.length; ++i)
if (dst[keys[i]] === undefined || !ifNotSet)
dst[keys[i]] = src[keys[i]];
}
return dst;
};
// Reserved words, ref: https://msdn.microsoft.com/en-us/library/ttyab5c8.aspx
// var reserved = "break,case,catch,class,const,continue,debugger,default,delete,do,else,export,extends,false,finally,for,function,if,import,in,instanceof,new,null,protected,return,super,switch,this,throw,true,try,typeof,var,while,with,abstract,boolean,byte,char,decimal,double,enum,final,float,get,implements,int,interface,internal,long,package,private,protected,public,sbyte,set,short,static,uint,ulong,ushort,void,assert,ensure,event,goto,invariant,namespace,native,require,synchronized,throws,transient,use,volatile".split(',');
/**
* Returns a safe property accessor for the specified properly name.
* @param {string} prop Property name
* @returns {string} Safe accessor
*/
util.safeProp = function safeProp(prop) {
// NOTE: While dot notation looks cleaner it doesn't seem to have a significant impact on performance.
// Hence, we can safe the extra bytes from providing the reserved keywords above for pre-ES5 envs.
return /* /^[a-z_$][a-z0-9_$]*$/i.test(prop) && !reserved.indexOf(prop) ? "." + prop : */ "['" + prop.replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "']";
};
/**
* Creates a new buffer of whatever type supported by the environment.
* @param {number} [size=0] Buffer size
* @returns {Buffer|Uint8Array|Array} Buffer
*/
util.newBuffer = function newBuffer(size) {
return new (util.Buffer || typeof Uint8Array !== 'undefined' && Uint8Array || Array)(size || 0);
};