-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
util.js
491 lines (448 loc) Β· 14.7 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
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
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const {
ArrayIsArray,
ArrayPrototypePop,
ArrayPrototypePush,
Error,
ErrorCaptureStackTrace,
FunctionPrototypeBind,
NumberIsSafeInteger,
ObjectDefineProperties,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptors,
ObjectKeys,
ObjectSetPrototypeOf,
ObjectValues,
ReflectApply,
StringPrototypeToWellFormed,
} = primordials;
const {
ErrnoException,
ExceptionWithHostPort,
codes: {
ERR_FALSY_VALUE_REJECTION,
ERR_INVALID_ARG_TYPE,
ERR_OUT_OF_RANGE,
},
isErrorStackTraceLimitWritable,
} = require('internal/errors');
const {
format,
formatWithOptions,
inspect,
stripVTControlCharacters,
} = require('internal/util/inspect');
const { debuglog } = require('internal/util/debuglog');
const {
validateBoolean,
validateFunction,
validateNumber,
validateString,
validateOneOf,
validateObject,
} = require('internal/validators');
const {
isReadableStream,
isWritableStream,
isNodeStream,
} = require('internal/streams/utils');
const types = require('internal/util/types');
let utilColors;
function lazyUtilColors() {
utilColors ??= require('internal/util/colors');
return utilColors;
}
const { getOptionValue } = require('internal/options');
const binding = internalBinding('util');
const {
deprecate,
getLazy,
getSystemErrorMap,
getSystemErrorName: internalErrorName,
getSystemErrorMessage: internalErrorMessage,
promisify,
defineLazyProperties,
} = require('internal/util');
let abortController;
function lazyAbortController() {
abortController ??= require('internal/abort_controller');
return abortController;
}
let internalDeepEqual;
/**
* @param {string} code
* @returns {string}
*/
function escapeStyleCode(code) {
return `\u001b[${code}m`;
}
/**
* @param {string | string[]} format
* @param {string} text
* @param {object} [options={}]
* @param {boolean} [options.validateStream=true] - Whether to validate the stream.
* @param {Stream} [options.stream=process.stdout] - The stream used for validation.
* @returns {string}
*/
function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) {
validateString(text, 'text');
validateBoolean(validateStream, 'options.validateStream');
if (validateStream) {
if (
!isReadableStream(stream) &&
!isWritableStream(stream) &&
!isNodeStream(stream)
) {
throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream);
}
}
if (ArrayIsArray(format)) {
let left = '';
let right = '';
for (const key of format) {
const formatCodes = inspect.colors[key];
if (formatCodes == null) {
validateOneOf(key, 'format', ObjectKeys(inspect.colors));
}
left += escapeStyleCode(formatCodes[0]);
right = `${escapeStyleCode(formatCodes[1])}${right}`;
}
return `${left}${text}${right}`;
}
const formatCodes = inspect.colors[format];
if (formatCodes == null) {
validateOneOf(format, 'format', ObjectKeys(inspect.colors));
}
// Check colorize only after validating arg type and value
if (
validateStream &&
(
!stream ||
!lazyUtilColors().shouldColorize(stream)
)
) {
return text;
}
return `${escapeStyleCode(formatCodes[0])}${text}${escapeStyleCode(formatCodes[1])}`;
}
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
* @param {Function} ctor Constructor function which needs to inherit the
* prototype.
* @param {Function} superCtor Constructor function to inherit prototype from.
* @throws {TypeError} Will error if either constructor is null, or if
* the super constructor lacks a prototype.
*/
function inherits(ctor, superCtor) {
if (ctor === undefined || ctor === null)
throw new ERR_INVALID_ARG_TYPE('ctor', 'Function', ctor);
if (superCtor === undefined || superCtor === null)
throw new ERR_INVALID_ARG_TYPE('superCtor', 'Function', superCtor);
if (superCtor.prototype === undefined) {
throw new ERR_INVALID_ARG_TYPE('superCtor.prototype',
'Object', superCtor.prototype);
}
ObjectDefineProperty(ctor, 'super_', {
__proto__: null,
value: superCtor,
writable: true,
configurable: true,
});
ObjectSetPrototypeOf(ctor.prototype, superCtor.prototype);
}
/**
* @deprecated since v6.0.0
* @template T
* @template S
* @param {T} target
* @param {S} source
* @returns {S extends null ? T : (T & S)}
*/
function _extend(target, source) {
// Don't do anything if source isn't an object
if (source === null || typeof source !== 'object') return target;
const keys = ObjectKeys(source);
let i = keys.length;
while (i--) {
target[keys[i]] = source[keys[i]];
}
return target;
}
const callbackifyOnRejected = (reason, cb) => {
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
// Because `null` is a special error value in callbacks which means "no error
// occurred", we error-wrap so the callback consumer can distinguish between
// "the promise rejected with null" or "the promise fulfilled with undefined".
if (!reason) {
reason = new ERR_FALSY_VALUE_REJECTION.HideStackFramesError(reason);
ErrorCaptureStackTrace(reason, callbackifyOnRejected);
}
return cb(reason);
};
/**
* @template {(...args: any[]) => Promise<any>} T
* @param {T} original
* @returns {T extends (...args: infer TArgs) => Promise<infer TReturn> ?
* ((...params: [...TArgs, ((err: Error, ret: TReturn) => any)]) => void) :
* never
* }
*/
function callbackify(original) {
validateFunction(original, 'original');
// We DO NOT return the promise as it gives the user a false sense that
// the promise is actually somehow related to the callback's execution
// and that the callback throwing will reject the promise.
function callbackified(...args) {
const maybeCb = ArrayPrototypePop(args);
validateFunction(maybeCb, 'last argument');
const cb = FunctionPrototypeBind(maybeCb, this);
// In true node style we process the callback on `nextTick` with all the
// implications (stack, `uncaughtException`, `async_hooks`)
ReflectApply(original, this, args)
.then((ret) => process.nextTick(cb, null, ret),
(rej) => process.nextTick(callbackifyOnRejected, rej, cb));
}
const descriptors = ObjectGetOwnPropertyDescriptors(original);
// It is possible to manipulate a functions `length` or `name` property. This
// guards against the manipulation.
if (typeof descriptors.length.value === 'number') {
descriptors.length.value++;
}
if (typeof descriptors.name.value === 'string') {
descriptors.name.value += 'Callbackified';
}
const propertiesValues = ObjectValues(descriptors);
for (let i = 0; i < propertiesValues.length; i++) {
// We want to use null-prototype objects to not rely on globally mutable
// %Object.prototype%.
ObjectSetPrototypeOf(propertiesValues[i], null);
}
ObjectDefineProperties(callbackified, descriptors);
return callbackified;
}
/**
* @param {number} err
* @returns {string}
*/
function getSystemErrorMessage(err) {
validateNumber(err, 'err');
if (err >= 0 || !NumberIsSafeInteger(err)) {
throw new ERR_OUT_OF_RANGE('err', 'a negative integer', err);
}
return internalErrorMessage(err);
}
/**
* @param {number} err
* @returns {string}
*/
function getSystemErrorName(err) {
validateNumber(err, 'err');
if (err >= 0 || !NumberIsSafeInteger(err)) {
throw new ERR_OUT_OF_RANGE('err', 'a negative integer', err);
}
return internalErrorName(err);
}
function _errnoException(...args) {
if (isErrorStackTraceLimitWritable()) {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
const e = new ErrnoException(...args);
Error.stackTraceLimit = limit;
ErrorCaptureStackTrace(e, _exceptionWithHostPort);
return e;
}
return new ErrnoException(...args);
}
function _exceptionWithHostPort(...args) {
if (isErrorStackTraceLimitWritable()) {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
const e = new ExceptionWithHostPort(...args);
Error.stackTraceLimit = limit;
ErrorCaptureStackTrace(e, _exceptionWithHostPort);
return e;
}
return new ExceptionWithHostPort(...args);
}
/**
* Parses the content of a `.env` file.
* @param {string} content
* @returns {Record<string, string>}
*/
function parseEnv(content) {
validateString(content, 'content');
return binding.parseEnv(content);
}
const lazySourceMap = getLazy(() => require('internal/source_map/source_map_cache'));
/**
* @typedef {object} CallSite // The call site
* @property {string} scriptName // The name of the resource that contains the
* script for the function for this StackFrame
* @property {string} functionName // The name of the function associated with this stack frame
* @property {number} lineNumber // The number, 1-based, of the line for the associate function call
* @property {number} columnNumber // The 1-based column offset on the line for the associated function call
*/
/**
* @param {CallSite} callSite // The call site object to reconstruct from source map
* @returns {CallSite | undefined} // The reconstructed call site object
*/
function reconstructCallSite(callSite) {
const { scriptName, lineNumber, column } = callSite;
const sourceMap = lazySourceMap().findSourceMap(scriptName);
if (!sourceMap) return;
const entry = sourceMap.findEntry(lineNumber - 1, column - 1);
if (!entry?.originalSource) return;
return {
__proto__: null,
// If the name is not found, it is an empty string to match the behavior of `util.getCallSite()`
functionName: entry.name ?? '',
scriptName: entry.originalSource,
lineNumber: entry.originalLine + 1,
column: entry.originalColumn + 1,
};
}
/**
*
* The call site array to map
* @param {CallSite[]} callSites
* Array of objects with the reconstructed call site
* @returns {CallSite[]}
*/
function mapCallSite(callSites) {
const result = [];
for (let i = 0; i < callSites.length; ++i) {
const callSite = callSites[i];
const found = reconstructCallSite(callSite);
ArrayPrototypePush(result, found ?? callSite);
}
return result;
}
/**
* @typedef {object} CallSiteOptions // The call site options
* @property {boolean} sourceMap // Enable source map support
*/
/**
* Returns the callSite
* @param {number} frameCount
* @param {CallSiteOptions} options
* @returns {CallSite[]}
*/
function getCallSites(frameCount = 10, options) {
// If options is not provided check if frameCount is an object
if (options === undefined) {
if (typeof frameCount === 'object') {
// If frameCount is an object, it is the options object
options = frameCount;
validateObject(options, 'options');
validateBoolean(options.sourceMap, 'options.sourceMap');
frameCount = 10;
} else {
// If options is not provided, set it to an empty object
options = {};
};
} else {
// If options is provided, validate it
validateObject(options, 'options');
validateBoolean(options.sourceMap, 'options.sourceMap');
}
// Using kDefaultMaxCallStackSizeToCapture as reference
validateNumber(frameCount, 'frameCount', 1, 200);
// If options.sourceMaps is true or if sourceMaps are enabled but the option.sourceMaps is not set explictly to false
if (options.sourceMap === true || (getOptionValue('--enable-source-maps') && options.sourceMap !== false)) {
return mapCallSite(binding.getCallSites(frameCount));
}
return binding.getCallSites(frameCount);
};
// Keep the `exports =` so that various functions can still be monkeypatched
module.exports = {
_errnoException,
_exceptionWithHostPort,
_extend: deprecate(_extend,
'The `util._extend` API is deprecated. Please use Object.assign() instead.',
'DEP0060'),
callbackify,
debug: debuglog,
debuglog,
deprecate,
format,
styleText,
formatWithOptions,
// Deprecated getCallSite.
// This API can be removed in next semver-minor release.
getCallSite: deprecate(getCallSites,
'The `util.getCallSite` API has been renamed to `util.getCallSites()`.',
'ExperimentalWarning'),
getCallSites,
getSystemErrorMap,
getSystemErrorName,
getSystemErrorMessage,
inherits,
inspect,
isArray: deprecate(ArrayIsArray,
'The `util.isArray` API is deprecated. Please use `Array.isArray()` instead.',
'DEP0044'),
isDeepStrictEqual(a, b) {
if (internalDeepEqual === undefined) {
internalDeepEqual = require('internal/util/comparisons')
.isDeepStrictEqual;
}
return internalDeepEqual(a, b);
},
promisify,
stripVTControlCharacters,
toUSVString(input) {
return StringPrototypeToWellFormed(`${input}`);
},
get transferableAbortSignal() {
return lazyAbortController().transferableAbortSignal;
},
get transferableAbortController() {
return lazyAbortController().transferableAbortController;
},
get aborted() {
return lazyAbortController().aborted;
},
types,
parseEnv,
};
defineLazyProperties(
module.exports,
'internal/util/parse_args/parse_args',
['parseArgs'],
);
defineLazyProperties(
module.exports,
'internal/encoding',
['TextDecoder', 'TextEncoder'],
);
defineLazyProperties(
module.exports,
'internal/mime',
['MIMEType', 'MIMEParams'],
);