pax_global_header00006660000000000000000000000064143230642070014513gustar00rootroot0000000000000052 comment=ef984721db7150f651800e051de4314c9517d42c node-util-0.12.5/000077500000000000000000000000001432306420700135005ustar00rootroot00000000000000node-util-0.12.5/.airtap.yml000066400000000000000000000005271432306420700155650ustar00rootroot00000000000000browsers: - name: chrome version: - 49 # last supported on XP (keep it so long as it's easy to support) - -1..latest - name: firefox version: - 52 # extended support release - -1..latest - name: safari version: -1..latest - name: ie version: 9..latest sauce_connect: true loopback: airtap.local node-util-0.12.5/.github/000077500000000000000000000000001432306420700150405ustar00rootroot00000000000000node-util-0.12.5/.github/FUNDING.yml000066400000000000000000000012041432306420700166520ustar00rootroot00000000000000# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: npm/util community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] node-util-0.12.5/.gitignore000066400000000000000000000000511432306420700154640ustar00rootroot00000000000000node_modules yarn.lock package-lock.json node-util-0.12.5/.npmrc000066400000000000000000000000231432306420700146130ustar00rootroot00000000000000package-lock=false node-util-0.12.5/.travis.yml000066400000000000000000000025741432306420700156210ustar00rootroot00000000000000os: linux dist: bionic language: node_js .addons: &AIRTAP sauce_connect: true hosts: - airtap.local jobs: include: - name: Run tests on stable Node.js node_js: stable script: npm test - name: Run tests on Node.js 12 node_js: 12 script: npm test - name: Run tests on Node.js 10 node_js: 10 script: npm test - name: Run tests on Node.js 8 node_js: 8 script: npm test - name: Run tests on Node.js 6 node_js: 6 script: npm test - name: Run tests on Node.js 4 node_js: 4 script: npm test - name: Run tests on Node.js 0.12 node_js: '0.12' script: npm test - name: Run tests on Node.js 0.10 node_js: '0.10' script: npm test - name: Run browser tests node_js: lts/* script: npm run test:browsers addons: *AIRTAP - name: Run browser tests with polyfilled environment node_js: lts/* script: npm run test:browsers:with-polyfills addons: *AIRTAP env: global: - secure: AdUubswCR68/eGD+WWjwTHgFbelwQGnNo81j1IOaUxKw+zgFPzSnFEEtDw7z98pWgg7p9DpCnyzzSnSllP40wq6AG19OwyUJjSLoZK57fp+r8zwTQwWiSqUgMu2YSMmKJPIO/aoSGpRQXT+L1nRrHoUJXgFodyIZgz40qzJeZjc= - secure: heQuxPVsQ7jBbssoVKimXDpqGjQFiucm6W5spoujmspjDG7oEcHD9ANo9++LoRPrsAmNx56SpMK5fNfVmYediw6SvhXm4Mxt56/fYCrLDBtgGG+1neCeffAi8z1rO8x48m77hcQ6YhbUL5R9uBimUjMX92fZcygAt8Rg804zjFo= node-util-0.12.5/CHANGELOG.md000066400000000000000000000040731432306420700153150ustar00rootroot00000000000000# util change log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## 0.12.5 * Move `safe-buffer` dependency to a dev-only dependency. ([@goto-bus-stop](https://github.com/goto-bus-stop) in [e84cfd5](https://github.com/browserify/node-util/commit/e84cfd5e4923631d012e578d7aa140412a475646)) * Document usage with webpack 5+. ([@MatrixFrog](https://github.com/MatrixFrog) in [#69](https://github.com/browserify/node-util/pull/69)) ## 0.12.4 * Avoid SharedArrayBuffer until required. ([@snyamathi](https://github.com/snyamathi) in [#59](https://github.com/browserify/node-util/pull/59)) This fixes a [security warning](https://developers.google.com/search/blog/2021/03/sharedarraybuffer-notes) for SharedArrayBuffer. ## 0.12.3 * Use robust `which-typed-array`, `is-typed-array` modules for the `util.types.isTypedArray` family of functions. ([@wbinnssmith](https://github.com/wbinnssmith) in [#47](https://github.com/browserify/node-util/pull/47)) This fixes crash in IE11 when a polyfilled `Symbol` is available in the environment. ## 0.12.2 * Move `object.entries` dependency to a dev-only dependency. ([@goto-bus-stop](https://github.com/goto-bus-stop) in [622f036](https://github.com/browserify/node-util/commit/622f0361540997e7e7b8abcff9865b47b2fa658c)) ## 0.12.1 * Update `util.debuglog` compatibility to Node 10.4.0. ([@goto-bus-stop](https://github.com/goto-bus-stop) in [#27](https://github.com/browserify/node-util/pull/27)) * Allow newer versions of `inherits`. ([@snyamathi](https://github.com/snyamathi) in [#39](https://github.com/browserify/node-util/pull/39)) ## 0.12.0 * Add `util.types`. ([@lukechilds](https://github.com/lukechilds) in [#32](https://github.com/browserify/node-util/pull/35)) ## 0.11.1 * Fix an infinite loop in `util.deprecate` some build configurations. ([@bernardmcmanus](https://github.com/bernardmcmanus) in [#12](https://github.com/browserify/node-util/pull/12)) ## 0.11.0 * Add `util.promisify`. * Add `util.callbackify`. ## 0.10.4 * Update `inherits` dependency. node-util-0.12.5/LICENSE000066400000000000000000000021101432306420700144770ustar00rootroot00000000000000Copyright Joyent, Inc. and other Node contributors. All rights reserved. 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. node-util-0.12.5/README.md000066400000000000000000000051561432306420700147660ustar00rootroot00000000000000# util [![Build Status](https://travis-ci.org/browserify/node-util.png?branch=master)](https://travis-ci.org/browserify/node-util) > Node.js's [util][util] module for all engines. This implements the Node.js [`util`][util] module for environments that do not have it, like browsers. ## Install You usually do not have to install `util` yourself. If your code runs in Node.js, `util` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) (up to version 4 -- [see this documentation](https://webpack.js.org/configuration/resolve/#resolvefallback) for how to include polyfills like `util` in webpack 5+) also include the `util` module. But if none of those apply, with npm do: ```shell npm install util ``` ## Usage ```javascript var util = require('util') var EventEmitter = require('events') function MyClass() { EventEmitter.call(this) } util.inherits(MyClass, EventEmitter) ``` ## Browser Support The `util` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`. To use `util.promisify` and `util.callbackify`, Promises must already be available. If you need to support browsers like IE11 that do not support Promises, use a shim. [es6-promise](https://github.com/stefanpenner/es6-promise) is a popular one but there are many others available on npm. ## API See the [Node.js util docs][util]. `util` currently supports the Node 8 LTS API. However, some of the methods are outdated. The `inspect` and `format` methods included in this module are a lot more simple and barebones than the ones in Node.js. ## Contributing PRs are very welcome! The main way to contribute to `util` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. This module intends to provide exactly the same API as Node.js, so features that are not available in the core `util` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. If there is a difference in behaviour between Node.js's `util` module and this module, please open an issue! ## License [MIT](./LICENSE) [util]: https://nodejs.org/docs/latest-v8.x/api/util.html node-util-0.12.5/package.json000066400000000000000000000024421432306420700157700ustar00rootroot00000000000000{ "name": "util", "description": "Node.js's util module for all engines", "version": "0.12.5", "author": { "name": "Joyent", "url": "http://www.joyent.com" }, "browser": { "./support/isBuffer.js": "./support/isBufferBrowser.js" }, "dependencies": { "inherits": "^2.0.3", "is-arguments": "^1.0.4", "is-generator-function": "^1.0.7", "is-typed-array": "^1.1.3", "which-typed-array": "^1.1.2" }, "devDependencies": { "airtap": "~1.0.0", "core-js": "^3.6.5", "is-async-supported": "~1.2.0", "object.assign": "~4.1.0", "object.entries": "^1.1.0", "run-series": "~1.1.4", "safe-buffer": "^5.1.2", "tape": "~4.9.0" }, "files": [ "util.js", "support" ], "homepage": "https://github.com/browserify/node-util", "keywords": [ "util" ], "license": "MIT", "main": "./util.js", "repository": { "type": "git", "url": "git://github.com/browserify/node-util" }, "scripts": { "test": "node test/node/index.js", "test:browsers": "airtap test/browser/index.js", "test:browsers:with-polyfills": "airtap test/browser/with-polyfills.js", "test:browsers:with-polyfills:local": "npm run test:browsers:with-polyfills -- --local", "test:browsers:local": "npm run test:browsers -- --local" } } node-util-0.12.5/security.md000066400000000000000000000004461432306420700156750ustar00rootroot00000000000000# Security Policy ## Supported Versions Only the latest major version is supported at any given time. ## Reporting a Vulnerability To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. node-util-0.12.5/support/000077500000000000000000000000001432306420700152145ustar00rootroot00000000000000node-util-0.12.5/support/isBuffer.js000066400000000000000000000001141432306420700173130ustar00rootroot00000000000000module.exports = function isBuffer(arg) { return arg instanceof Buffer; } node-util-0.12.5/support/isBufferBrowser.js000066400000000000000000000003131432306420700206600ustar00rootroot00000000000000module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }node-util-0.12.5/support/types.js000066400000000000000000000207401432306420700167210ustar00rootroot00000000000000// Currently in sync with Node.js lib/internal/util/types.js // https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 'use strict'; var isArgumentsObject = require('is-arguments'); var isGeneratorFunction = require('is-generator-function'); var whichTypedArray = require('which-typed-array'); var isTypedArray = require('is-typed-array'); function uncurryThis(f) { return f.call.bind(f); } var BigIntSupported = typeof BigInt !== 'undefined'; var SymbolSupported = typeof Symbol !== 'undefined'; var ObjectToString = uncurryThis(Object.prototype.toString); var numberValue = uncurryThis(Number.prototype.valueOf); var stringValue = uncurryThis(String.prototype.valueOf); var booleanValue = uncurryThis(Boolean.prototype.valueOf); if (BigIntSupported) { var bigIntValue = uncurryThis(BigInt.prototype.valueOf); } if (SymbolSupported) { var symbolValue = uncurryThis(Symbol.prototype.valueOf); } function checkBoxedPrimitive(value, prototypeValueOf) { if (typeof value !== 'object') { return false; } try { prototypeValueOf(value); return true; } catch(e) { return false; } } exports.isArgumentsObject = isArgumentsObject; exports.isGeneratorFunction = isGeneratorFunction; exports.isTypedArray = isTypedArray; // Taken from here and modified for better browser support // https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js function isPromise(input) { return ( ( typeof Promise !== 'undefined' && input instanceof Promise ) || ( input !== null && typeof input === 'object' && typeof input.then === 'function' && typeof input.catch === 'function' ) ); } exports.isPromise = isPromise; function isArrayBufferView(value) { if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { return ArrayBuffer.isView(value); } return ( isTypedArray(value) || isDataView(value) ); } exports.isArrayBufferView = isArrayBufferView; function isUint8Array(value) { return whichTypedArray(value) === 'Uint8Array'; } exports.isUint8Array = isUint8Array; function isUint8ClampedArray(value) { return whichTypedArray(value) === 'Uint8ClampedArray'; } exports.isUint8ClampedArray = isUint8ClampedArray; function isUint16Array(value) { return whichTypedArray(value) === 'Uint16Array'; } exports.isUint16Array = isUint16Array; function isUint32Array(value) { return whichTypedArray(value) === 'Uint32Array'; } exports.isUint32Array = isUint32Array; function isInt8Array(value) { return whichTypedArray(value) === 'Int8Array'; } exports.isInt8Array = isInt8Array; function isInt16Array(value) { return whichTypedArray(value) === 'Int16Array'; } exports.isInt16Array = isInt16Array; function isInt32Array(value) { return whichTypedArray(value) === 'Int32Array'; } exports.isInt32Array = isInt32Array; function isFloat32Array(value) { return whichTypedArray(value) === 'Float32Array'; } exports.isFloat32Array = isFloat32Array; function isFloat64Array(value) { return whichTypedArray(value) === 'Float64Array'; } exports.isFloat64Array = isFloat64Array; function isBigInt64Array(value) { return whichTypedArray(value) === 'BigInt64Array'; } exports.isBigInt64Array = isBigInt64Array; function isBigUint64Array(value) { return whichTypedArray(value) === 'BigUint64Array'; } exports.isBigUint64Array = isBigUint64Array; function isMapToString(value) { return ObjectToString(value) === '[object Map]'; } isMapToString.working = ( typeof Map !== 'undefined' && isMapToString(new Map()) ); function isMap(value) { if (typeof Map === 'undefined') { return false; } return isMapToString.working ? isMapToString(value) : value instanceof Map; } exports.isMap = isMap; function isSetToString(value) { return ObjectToString(value) === '[object Set]'; } isSetToString.working = ( typeof Set !== 'undefined' && isSetToString(new Set()) ); function isSet(value) { if (typeof Set === 'undefined') { return false; } return isSetToString.working ? isSetToString(value) : value instanceof Set; } exports.isSet = isSet; function isWeakMapToString(value) { return ObjectToString(value) === '[object WeakMap]'; } isWeakMapToString.working = ( typeof WeakMap !== 'undefined' && isWeakMapToString(new WeakMap()) ); function isWeakMap(value) { if (typeof WeakMap === 'undefined') { return false; } return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap; } exports.isWeakMap = isWeakMap; function isWeakSetToString(value) { return ObjectToString(value) === '[object WeakSet]'; } isWeakSetToString.working = ( typeof WeakSet !== 'undefined' && isWeakSetToString(new WeakSet()) ); function isWeakSet(value) { return isWeakSetToString(value); } exports.isWeakSet = isWeakSet; function isArrayBufferToString(value) { return ObjectToString(value) === '[object ArrayBuffer]'; } isArrayBufferToString.working = ( typeof ArrayBuffer !== 'undefined' && isArrayBufferToString(new ArrayBuffer()) ); function isArrayBuffer(value) { if (typeof ArrayBuffer === 'undefined') { return false; } return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer; } exports.isArrayBuffer = isArrayBuffer; function isDataViewToString(value) { return ObjectToString(value) === '[object DataView]'; } isDataViewToString.working = ( typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined' && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) ); function isDataView(value) { if (typeof DataView === 'undefined') { return false; } return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView; } exports.isDataView = isDataView; // Store a copy of SharedArrayBuffer in case it's deleted elsewhere var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; function isSharedArrayBufferToString(value) { return ObjectToString(value) === '[object SharedArrayBuffer]'; } function isSharedArrayBuffer(value) { if (typeof SharedArrayBufferCopy === 'undefined') { return false; } if (typeof isSharedArrayBufferToString.working === 'undefined') { isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); } return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy; } exports.isSharedArrayBuffer = isSharedArrayBuffer; function isAsyncFunction(value) { return ObjectToString(value) === '[object AsyncFunction]'; } exports.isAsyncFunction = isAsyncFunction; function isMapIterator(value) { return ObjectToString(value) === '[object Map Iterator]'; } exports.isMapIterator = isMapIterator; function isSetIterator(value) { return ObjectToString(value) === '[object Set Iterator]'; } exports.isSetIterator = isSetIterator; function isGeneratorObject(value) { return ObjectToString(value) === '[object Generator]'; } exports.isGeneratorObject = isGeneratorObject; function isWebAssemblyCompiledModule(value) { return ObjectToString(value) === '[object WebAssembly.Module]'; } exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; function isNumberObject(value) { return checkBoxedPrimitive(value, numberValue); } exports.isNumberObject = isNumberObject; function isStringObject(value) { return checkBoxedPrimitive(value, stringValue); } exports.isStringObject = isStringObject; function isBooleanObject(value) { return checkBoxedPrimitive(value, booleanValue); } exports.isBooleanObject = isBooleanObject; function isBigIntObject(value) { return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); } exports.isBigIntObject = isBigIntObject; function isSymbolObject(value) { return SymbolSupported && checkBoxedPrimitive(value, symbolValue); } exports.isSymbolObject = isSymbolObject; function isBoxedPrimitive(value) { return ( isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value) ); } exports.isBoxedPrimitive = isBoxedPrimitive; function isAnyArrayBuffer(value) { return typeof Uint8Array !== 'undefined' && ( isArrayBuffer(value) || isSharedArrayBuffer(value) ); } exports.isAnyArrayBuffer = isAnyArrayBuffer; ['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { Object.defineProperty(exports, method, { enumerable: false, value: function() { throw new Error(method + ' is not supported in userland'); } }); }); node-util-0.12.5/test/000077500000000000000000000000001432306420700144575ustar00rootroot00000000000000node-util-0.12.5/test/browser/000077500000000000000000000000001432306420700161425ustar00rootroot00000000000000node-util-0.12.5/test/browser/callbackify.js000066400000000000000000000107331432306420700207500ustar00rootroot00000000000000'use strict'; var test = require('tape'); var callbackify = require('../../').callbackify; if (typeof Promise === 'undefined') { console.log('no global Promise found, skipping callbackify tests'); return; } function after (n, cb) { var i = 0; return function () { if (++i === n) cb(); } } var values = [ 'hello world', null, undefined, false, 0, {}, { key: 'value' }, function ok() {}, ['array', 'with', 4, 'values'], new Error('boo') ]; if (typeof Symbol !== 'undefined') { values.push(Symbol('I am a symbol')); } test('util.callbackify resolution value is passed as second argument to callback', function (t) { var end = after(values.length * 2, t.end); // Test that the resolution value is passed as second argument to callback values.forEach(function(value) { // Test Promise factory function promiseFn() { return Promise.resolve(value); } var cbPromiseFn = callbackify(promiseFn); cbPromiseFn(function(err, ret) { t.ifError(err); t.strictEqual(ret, value, 'cb ' + typeof value); end(); }); // Test Thenable function thenableFn() { return { then: function(onRes, onRej) { onRes(value); } }; } var cbThenableFn = callbackify(thenableFn); cbThenableFn(function(err, ret) { t.ifError(err); t.strictEqual(ret, value, 'thenable ' + typeof value); end(); }); }); }); test('util.callbackify rejection reason is passed as first argument to callback', function (t) { var end = after(values.length * 2, t.end); // Test that rejection reason is passed as first argument to callback values.forEach(function(value) { // test a Promise factory function promiseFn() { return Promise.reject(value); } var cbPromiseFn = callbackify(promiseFn); cbPromiseFn(function(err, ret) { t.strictEqual(ret, undefined, 'cb ' + typeof value); if (err instanceof Error) { if ('reason' in err) { t.ok(!value); t.strictEqual(err.message, 'Promise was rejected with a falsy value'); t.strictEqual(err.reason, value); } else { t.strictEqual(String(value).slice(-err.message.length), err.message); } } else { t.strictEqual(err, value); } end(); }); // Test Thenable function thenableFn() { return { then: function (onRes, onRej) { onRej(value); } }; } var cbThenableFn = callbackify(thenableFn); cbThenableFn(function(err, ret) { t.strictEqual(ret, undefined, 'thenable ' + typeof value); if (err instanceof Error) { if ('reason' in err) { t.ok(!value); t.strictEqual(err.message, 'Promise was rejected with a falsy value'); t.strictEqual(err.reason, value); } else { t.strictEqual(String(value).slice(-err.message.length), err.message); } } else { t.strictEqual(err, value); } end(); }); }); }); test('util.callbackify arguments passed to callbackified function are passed to original', function (t) { var end = after(values.length, t.end); // Test that arguments passed to callbackified function are passed to original values.forEach(function(value) { function promiseFn(arg) { t.strictEqual(arg, value); return Promise.resolve(arg); } var cbPromiseFn = callbackify(promiseFn); cbPromiseFn(value, function(err, ret) { t.ifError(err); t.strictEqual(ret, value); end(); }); }); }); test('util.callbackify `this` binding is the same for callbackified and original', function (t) { var end = after(values.length, t.end); // Test that `this` binding is the same for callbackified and original values.forEach(function(value) { var iAmThis = { fn: function(arg) { t.strictEqual(this, iAmThis); return Promise.resolve(arg); }, }; iAmThis.cbFn = callbackify(iAmThis.fn); iAmThis.cbFn(value, function(err, ret) { t.ifError(err); t.strictEqual(ret, value); t.strictEqual(this, iAmThis); end(); }); }); }); test('util.callbackify non-function inputs throw', function (t) { // Verify that non-function inputs throw. ['foo', null, undefined, false, 0, {}, typeof Symbol !== 'undefined' ? Symbol() : undefined, []].forEach(function(value) { t.throws( function() { callbackify(value); }, 'The "original" argument must be of type Function' ); }); t.end(); }); node-util-0.12.5/test/browser/index.js000066400000000000000000000001551432306420700176100ustar00rootroot00000000000000require('./inspect'); require('./is'); require('./promisify'); require('./callbackify'); require('./types'); node-util-0.12.5/test/browser/inspect.js000066400000000000000000000041141432306420700201450ustar00rootroot00000000000000// 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. var test = require('tape'); var util = require('../../'); test('util.inspect - test for sparse array', function (t) { var a = ['foo', 'bar', 'baz']; t.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); delete a[1]; t.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); t.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); t.equal(util.inspect(new Array(5)), '[ , , , , ]'); t.end(); }); test('util.inspect - exceptions should print the error message, not \'{}\'', function (t) { // Error objects have some additional properties in Safari (line, column, sourceURL) // so this uses indexOf() instead of strict comparison t.notEqual(util.inspect(new Error()).indexOf('[Error]'), -1); t.notEqual(util.inspect(new Error('FAIL')).indexOf('[Error: FAIL]'), -1); t.notEqual(util.inspect(new TypeError('FAIL')).indexOf('[TypeError: FAIL]'), -1); t.notEqual(util.inspect(new SyntaxError('FAIL')).indexOf('[SyntaxError: FAIL]'), -1); t.end(); }); node-util-0.12.5/test/browser/is.js000066400000000000000000000072561432306420700171250ustar00rootroot00000000000000// 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. var test = require('tape'); var util = require('../../'); test('util.isArray', function (t) { t.equal(true, util.isArray([])); t.equal(true, util.isArray(Array())); t.equal(true, util.isArray(new Array())); t.equal(true, util.isArray(new Array(5))); t.equal(true, util.isArray(new Array('with', 'some', 'entries'))); t.equal(false, util.isArray({})); t.equal(false, util.isArray({ push: function() {} })); t.equal(false, util.isArray(/regexp/)); t.equal(false, util.isArray(new Error())); t.equal(false, util.isArray(Object.create(Array.prototype))); t.end(); }); test('util.isRegExp', function (t) { t.equal(true, util.isRegExp(/regexp/)); t.equal(true, util.isRegExp(RegExp())); t.equal(true, util.isRegExp(new RegExp())); t.equal(false, util.isRegExp({})); t.equal(false, util.isRegExp([])); t.equal(false, util.isRegExp(new Date())); t.equal(false, util.isRegExp(Object.create(RegExp.prototype))); t.end(); }); test('util.isDate', function (t) { t.equal(true, util.isDate(new Date())); t.equal(true, util.isDate(new Date(0))); t.equal(false, util.isDate(Date())); t.equal(false, util.isDate({})); t.equal(false, util.isDate([])); t.equal(false, util.isDate(new Error())); t.equal(false, util.isDate(Object.create(Date.prototype))); t.end(); }); test('util.isError', function (t) { t.equal(true, util.isError(new Error())); t.equal(true, util.isError(new TypeError())); t.equal(true, util.isError(new SyntaxError())); t.equal(false, util.isError({})); t.equal(false, util.isError({ name: 'Error', message: '' })); t.equal(false, util.isError([])); t.equal(true, util.isError(Object.create(Error.prototype))); t.end(); }); test('util._extend', function (t) { t.deepEqual(util._extend({a:1}), {a:1}); t.deepEqual(util._extend({a:1}, []), {a:1}); t.deepEqual(util._extend({a:1}, null), {a:1}); t.deepEqual(util._extend({a:1}, true), {a:1}); t.deepEqual(util._extend({a:1}, false), {a:1}); t.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); t.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); t.end(); }); test('util.isBuffer', function (t) { t.equal(true, util.isBuffer(new Buffer(4))); t.equal(true, util.isBuffer(Buffer(4))); t.equal(true, util.isBuffer(new Buffer(4))); t.equal(true, util.isBuffer(new Buffer([1, 2, 3, 4]))); t.equal(false, util.isBuffer({})); t.equal(false, util.isBuffer([])); t.equal(false, util.isBuffer(new Error())); t.equal(false, util.isRegExp(new Date())); t.equal(true, util.isBuffer(Object.create(Buffer.prototype))); t.end(); }); node-util-0.12.5/test/browser/promisify.js000066400000000000000000000114121432306420700205200ustar00rootroot00000000000000var promisify = require('../../').promisify; var test = require('tape'); var hasSymbol = typeof Symbol !== 'undefined'; if (typeof Promise === 'undefined') { console.log('no global Promise found, skipping promisify tests'); return; } var callbacker = function (arg, cb) { setTimeout(function () { if (typeof arg === 'string') cb(null, arg.toUpperCase()); else cb(new TypeError('incorrect type')); }, 5); } var promiser = promisify(callbacker); test('util.promisify resolves', function (t) { var promise = promiser(__filename); t.ok(promise instanceof Promise); promise.then(function (value) { t.deepEqual(value, __filename.toUpperCase()); t.end(); }); }); test('util.promisify rejects', function (t) { var promise = promiser(42); promise.catch(function (error) { t.equal(error.message, 'incorrect type'); t.end(); }); }); test('util.promisify custom', { skip: !hasSymbol }, function (t) { function fn() {} function promisifedFn() {} fn[promisify.custom] = promisifedFn; t.strictEqual(promisify(fn), promisifedFn); t.strictEqual(promisify(promisify(fn)), promisifedFn); t.end(); }); test('util.promisify custom of invalid type', { skip: !hasSymbol }, function (t) { function fn2() {} fn2[promisify.custom] = 42; t.throws( function () { promisify(fn2); }, /must be of type Function/ ); t.end(); }); test('util.promisify multiple callback values', function (t) { function fn5(callback) { callback(null, 'foo', 'bar'); } promisify(fn5)().then(function (value) { t.strictEqual(value, 'foo'); t.end(); }); }); test('util.promisify no callback success value', function (t) { function fn6(callback) { callback(null); } promisify(fn6)().then(function (value) { t.strictEqual(value, undefined); t.end(); }); }); test('util.promisify no callback arguments at all', function (t) { function fn7(callback) { callback(); } promisify(fn7)().then(function (value) { t.strictEqual(value, undefined); t.end(); }); }); test('util.promisify passing arguments', function (t) { function fn8(err, val, callback) { callback(err, val); } promisify(fn8)(null, 42).then(function (value) { t.strictEqual(value, 42); t.end(); }); }); test('util.promisify passing arguments (rejects)', function (t) { function fn9(err, val, callback) { callback(err, val); } promisify(fn9)(new Error('oops'), null).catch(function (err) { t.strictEqual(err.message, 'oops'); t.end(); }); }); test('util.promisify chain', function (t) { function fn9(err, val, callback) { callback(err, val); } Promise.resolve() .then(function () { return promisify(fn9)(null, 42); }) .then(function (value) { t.strictEqual(value, 42); t.end(); }); }); test('util.promisify keeps correct `this`', function (t) { var o = {}; var fn10 = promisify(function(cb) { cb(null, this === o); }); o.fn = fn10; o.fn().then(function(val) { t.ok(val); t.end(); }); }); test('util.promisify calling callback multiple times', function (t) { var err = new Error('Should not have called the callback with the error.'); var stack = err.stack; var fn11 = promisify(function(cb) { cb(null); cb(err); }); Promise.resolve() .then(function () { return fn11(); }) .then(function () { return Promise.resolve(); }) .then(function () { t.strictEqual(stack, err.stack); t.end(); }); }); // Can't do this without Symbol() unfortunately test('util.promisify promisifying a promisified function', { skip: !hasSymbol }, function (t) { function c() { } var a = promisify(function() { }); var b = promisify(a); t.notStrictEqual(c, a); t.strictEqual(a, b); t.end(); }); test('util.promisify sync throw becomes rejection', function (t) { var errToThrow; var thrower = promisify(function(a, b, c, cb) { errToThrow = new Error(); throw errToThrow; }); thrower(1, 2, 3) .then(t.fail) .then(t.fail, function (e) { t.strictEqual(e, errToThrow); t.end(); }); }); test('util.promisify callback and sync throw', function (t) { var err = new Error(); var a = promisify(function (cb) { cb(err) })(); var b = promisify(function () { throw err; })(); Promise.all([ a.then(t.fail, function(e) { t.strictEqual(err, e); }), b.then(t.fail, function(e) { t.strictEqual(err, e); }) ]).then(function () { t.end(); }); }); test('util.promisify throws for incorrect argument types', function (t) { var array = [undefined, null, true, 0, 'str', {}, []]; if (typeof Symbol !== 'undefined') array.push(Symbol()); array.forEach(function (input) { t.throws( function () { promisify(input); }, 'The "original" argument must be of type Function' ); }); t.end(); }); node-util-0.12.5/test/browser/types.js000066400000000000000000000002571432306420700176500ustar00rootroot00000000000000var test = require('tape'); var util = require('../../'); test('util.types', function (t) { t.doesNotThrow(function () { return require('../node/types') }); t.end(); }); node-util-0.12.5/test/browser/with-polyfills.js000066400000000000000000000000531432306420700214640ustar00rootroot00000000000000require('core-js'); require('./index.js'); node-util-0.12.5/test/node/000077500000000000000000000000001432306420700154045ustar00rootroot00000000000000node-util-0.12.5/test/node/callbackify-async.js000066400000000000000000000055561432306420700213340ustar00rootroot00000000000000'use strict'; // Separate test file for tests using new syntax (async/await). var common = require('./common'); var assert = require('assert'); var callbackify = require('../../').callbackify; var execFile = require('child_process').execFile; var values = [ 'hello world', null, undefined, false, 0, {}, { key: 'value' }, Symbol('I am a symbol'), function ok() {}, ['array', 'with', 4, 'values'], new Error('boo') ]; { // Test that the resolution value is passed as second argument to callback values.forEach(function(value) { // Test and `async function` async function asyncFn() { return value; } var cbAsyncFn = callbackify(asyncFn); cbAsyncFn(common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); })); }); } { // Test that rejection reason is passed as first argument to callback values.forEach(function(value) { // Test an `async function` async function asyncFn() { return Promise.reject(value); } var cbAsyncFn = callbackify(asyncFn); cbAsyncFn(common.mustCall(function (err, ret) { assert.strictEqual(ret, undefined); if (err instanceof Error) { if ('reason' in err) { assert(!value); assert.strictEqual(err.message, 'Promise was rejected with a falsy value'); assert.strictEqual(err.reason, value); } else { assert.strictEqual(String(value).endsWith(err.message), true); } } else { assert.strictEqual(err, value); } })); }); } { // Test that arguments passed to callbackified function are passed to original values.forEach(function(value) { async function asyncFn(arg) { assert.strictEqual(arg, value); return arg; } var cbAsyncFn = callbackify(asyncFn); cbAsyncFn(value, common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); })); }); } { // Test that `this` binding is the same for callbackified and original values.forEach(function(value) { var iAmThat = { async fn(arg) { assert.strictEqual(this, iAmThat); return arg; }, }; iAmThat.cbFn = callbackify(iAmThat.fn); iAmThat.cbFn(value, common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); assert.strictEqual(this, iAmThat); })); }); } { async function asyncFn() { return 42; } var cb = callbackify(asyncFn); var args = []; // Verify that the last argument to the callbackified function is a function. ['foo', null, undefined, false, 0, {}, Symbol(), []].forEach(function(value) { args.push(value); common.expectsError(function() { cb(...args); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, message: 'The last argument must be of type Function' }); }); } node-util-0.12.5/test/node/callbackify.js000066400000000000000000000122131432306420700202050ustar00rootroot00000000000000'use strict'; // This test checks that the semantics of `util.callbackify` are as described in // the API docs var common = require('./common'); var assert = require('assert'); var callbackify = require('../../').callbackify; var execFile = require('child_process').execFile; if (typeof Promise === 'undefined') { console.log('no global Promise found, skipping callbackify tests'); return; } var values = [ 'hello world', null, undefined, false, 0, {}, { key: 'value' }, function ok() {}, ['array', 'with', 4, 'values'], new Error('boo') ]; if (typeof Symbol !== 'undefined') { values.push(Symbol('I am a symbol')); } { // Test that the resolution value is passed as second argument to callback values.forEach(function(value) { // Test Promise factory function promiseFn() { return Promise.resolve(value); } var cbPromiseFn = callbackify(promiseFn); cbPromiseFn(common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); })); // Test Thenable function thenableFn() { return { then: function(onRes, onRej) { onRes(value); } }; } var cbThenableFn = callbackify(thenableFn); cbThenableFn(common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); })); }); } { // Test that rejection reason is passed as first argument to callback values.forEach(function(value) { // test a Promise factory function promiseFn() { return Promise.reject(value); } var cbPromiseFn = callbackify(promiseFn); cbPromiseFn(common.mustCall(function(err, ret) { assert.strictEqual(ret, undefined); if (err instanceof Error) { if ('reason' in err) { assert(!value); assert.strictEqual(err.message, 'Promise was rejected with a falsy value'); assert.strictEqual(err.reason, value); } else { assert.strictEqual(String(value).slice(-err.message.length), err.message); } } else { assert.strictEqual(err, value); } })); // Test Thenable function thenableFn() { return { then: function (onRes, onRej) { onRej(value); } }; } var cbThenableFn = callbackify(thenableFn); cbThenableFn(common.mustCall(function(err, ret) { assert.strictEqual(ret, undefined); if (err instanceof Error) { if ('reason' in err) { assert(!value); assert.strictEqual(err.message, 'Promise was rejected with a falsy value'); assert.strictEqual(err.reason, value); } else { assert.strictEqual(String(value).slice(-err.message.length), err.message); } } else { assert.strictEqual(err, value); } })); }); } { // Test that arguments passed to callbackified function are passed to original values.forEach(function(value) { function promiseFn(arg) { assert.strictEqual(arg, value); return Promise.resolve(arg); } var cbPromiseFn = callbackify(promiseFn); cbPromiseFn(value, common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); })); }); } { // Test that `this` binding is the same for callbackified and original values.forEach(function(value) { var iAmThis = { fn: function(arg) { assert.strictEqual(this, iAmThis); return Promise.resolve(arg); }, }; iAmThis.cbFn = callbackify(iAmThis.fn); iAmThis.cbFn(value, common.mustCall(function(err, ret) { assert.ifError(err); assert.strictEqual(ret, value); assert.strictEqual(this, iAmThis); })); }); } // These tests are not necessary in the browser. if (false) { // Test that callback that throws emits an `uncaughtException` event var fixture = fixtures.path('uncaught-exceptions', 'callbackify1.js'); execFile( process.execPath, [fixture], common.mustCall(function (err, stdout, stderr) { assert.strictEqual(err.code, 1); assert.strictEqual(Object.getPrototypeOf(err).name, 'Error'); assert.strictEqual(stdout, ''); var errLines = stderr.trim().split(/[\r\n]+/); var errLine = errLines.find(function (l) { return /^Error/.exec(l) }); assert.strictEqual(errLine, 'Error: ' + fixture); }) ); } if (false) { // Test that handled `uncaughtException` works and passes rejection reason var fixture = fixtures.path('uncaught-exceptions', 'callbackify2.js'); execFile( process.execPath, [fixture], common.mustCall(function (err, stdout, stderr) { assert.ifError(err); assert.strictEqual(stdout.trim(), fixture); assert.strictEqual(stderr, ''); }) ); } { // Verify that non-function inputs throw. ['foo', null, undefined, false, 0, {}, typeof Symbol !== 'undefined' ? Symbol() : undefined, []].forEach(function(value) { common.expectsError(function() { callbackify(value); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, message: 'The "original" argument must be of type Function' }); }); } if (require('is-async-supported')()) { require('./callbackify-async'); } node-util-0.12.5/test/node/common.js000066400000000000000000000012141432306420700172300ustar00rootroot00000000000000var assert = require('assert'); var mustCalls = []; var common = { expectsError: function (fn, props) { try { fn(); } catch (err) { if (props.type) assert.equal(err.constructor, props.type); if (props.message) assert.equal(err.message, props.message); return; } assert.fail('expected error'); }, mustCall: function (fn) { function mustCall() { mustCall.called = true return fn.apply(this, arguments); } mustCalls.push(mustCall); return mustCall; } }; process.on('exit', function () { mustCalls.forEach(function (mc) { assert(mc.called); }); }); module.exports = common; node-util-0.12.5/test/node/debug.js000066400000000000000000000062251432306420700170350ustar00rootroot00000000000000// 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'; var assert = require('assert'); var ObjectAssign = require('object.assign'); var modeArgv = process.argv[2] var sectionArgv = process.argv[3] if (modeArgv === 'child') child(sectionArgv); else parent(); function parent() { test('foo,tud,bar', true, 'tud'); test('foo,tud', true, 'tud'); test('tud,bar', true, 'tud'); test('tud', true, 'tud'); test('foo,bar', false, 'tud'); test('', false, 'tud'); test('###', true, '###'); test('hi:)', true, 'hi:)'); test('f$oo', true, 'f$oo'); test('f$oo', false, 'f.oo'); test('no-bar-at-all', false, 'bar'); test('test-abc', true, 'test-abc'); test('test-a', false, 'test-abc'); test('test-*', true, 'test-abc'); test('test-*c', true, 'test-abc'); test('test-*abc', true, 'test-abc'); test('abc-test', true, 'abc-test'); test('a*-test', true, 'abc-test'); test('*-test', true, 'abc-test'); } function test(environ, shouldWrite, section) { var expectErr = ''; var expectOut = 'ok\n'; var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child', section], { env: ObjectAssign(process.env, { NODE_DEBUG: environ }) }); if (shouldWrite) { expectErr = section.toUpperCase() + ' ' + child.pid + ': this { is: \'a\' } /debugging/\n' + section.toUpperCase() + ' ' + child.pid + ': num=1 str=a obj={"foo":"bar"}\n'; } var err = ''; child.stderr.setEncoding('utf8'); child.stderr.on('data', function (c) { err += c; }); var out = ''; child.stdout.setEncoding('utf8'); child.stdout.on('data', function (c) { out += c; }); var didTest = false; child.on('close', function (c) { assert(!c); assert.strictEqual(err, expectErr); assert.strictEqual(out, expectOut); didTest = true; }); process.on('exit', function () { assert(didTest); }); } function child(section) { var util = require('../../util'); var debug = util.debuglog(section); debug('this', { is: 'a' }, /debugging/); debug('num=%d str=%s obj=%j', 1, 'a', { foo: 'bar' }); console.log('ok'); } node-util-0.12.5/test/node/format.js000066400000000000000000000060231432306420700172330ustar00rootroot00000000000000// 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. var assert = require('assert'); var util = require('../../'); assert.equal(util.format(), ''); assert.equal(util.format(''), ''); assert.equal(util.format([]), '[]'); assert.equal(util.format({}), '{}'); assert.equal(util.format(null), 'null'); assert.equal(util.format(true), 'true'); assert.equal(util.format(false), 'false'); assert.equal(util.format('test'), 'test'); // CHECKME this is for console.log() compatibility - but is it *right*? assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); assert.equal(util.format('%d', 42.0), '42'); assert.equal(util.format('%d', 42), '42'); assert.equal(util.format('%s', 42), '42'); assert.equal(util.format('%j', 42), '42'); assert.equal(util.format('%d', '42.0'), '42'); assert.equal(util.format('%d', '42'), '42'); assert.equal(util.format('%s', '42'), '42'); assert.equal(util.format('%j', '42'), '"42"'); assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); assert.equal(util.format('%s'), '%s'); assert.equal(util.format('%s', undefined), 'undefined'); assert.equal(util.format('%s', 'foo'), 'foo'); assert.equal(util.format('%s:%s'), '%s:%s'); assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); (function() { var o = {}; o.o = o; assert.equal(util.format('%j', o), '[Circular]'); })(); // Errors assert.equal(util.format(new Error('foo')), '[Error: foo]'); function CustomError(msg) { Error.call(this); Object.defineProperty(this, 'message', { value: msg, enumerable: false }); Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); } util.inherits(CustomError, Error); assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); node-util-0.12.5/test/node/index.js000066400000000000000000000012651432306420700170550ustar00rootroot00000000000000var spawn = require('child_process').spawn; var path = require('path'); var series = require('run-series'); function test(filename) { return function(cb) { var proc = spawn(process.argv[0], [ filename ], { stdio: 'inherit' }); proc.on('close', function (code) { cb(code !== 0 ? new Error('test ' + path.basename(filename) + ' failed') : null); }); }; } series([ test(require.resolve('./debug')), test(require.resolve('./format')), test(require.resolve('./inspect')), test(require.resolve('./log')), test(require.resolve('./promisify')), test(require.resolve('./callbackify')), test(require.resolve('./types')) ], function (err) { if (err) throw err }); node-util-0.12.5/test/node/inspect.js000066400000000000000000000151251432306420700174130ustar00rootroot00000000000000// 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. var assert = require('assert'); var util = require('../../'); // test the internal isDate implementation var Date2 = require('vm').runInNewContext('Date'); var d = new Date2(); var orig = util.inspect(d); Date2.prototype.foo = 'bar'; var after = util.inspect(d); assert.equal(orig, after); // test for sparse array var a = ['foo', 'bar', 'baz']; assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); delete a[1]; assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); // test for property descriptors var getter = Object.create(null, { a: { get: function() { return 'aaa'; } } }); var setter = Object.create(null, { b: { set: function() {} } }); var getterAndSetter = Object.create(null, { c: { get: function() { return 'ccc'; }, set: function() {} } }); assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); // exceptions should print the error message, not '{}' assert.equal(util.inspect(new Error()), '[Error]'); assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); try { undef(); } catch (e) { assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); } var ex = util.inspect(new Error('FAIL'), true); assert.ok(ex.indexOf('[Error: FAIL]') != -1); /* Unsure why these don't work assert.ok(ex.indexOf('[stack]') != -1); assert.ok(ex.indexOf('[message]') != -1); */ // GH-1941 // should not throw: assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); // GH-1944 assert.doesNotThrow(function() { var d = new Date(); d.toUTCString = null; util.inspect(d); }); assert.doesNotThrow(function() { var r = /regexp/; r.toString = null; util.inspect(r); }); // bug with user-supplied inspect function returns non-string assert.doesNotThrow(function() { util.inspect([{ inspect: function() { return 123; } }]); }); // GH-2225 var x = { inspect: util.inspect }; assert.ok(util.inspect(x).indexOf('inspect') != -1); // util.inspect.styles and util.inspect.colors function test_color_style(style, input, implicit) { var color_name = util.inspect.styles[style]; var color = ['', '']; if(util.inspect.colors[color_name]) color = util.inspect.colors[color_name]; var without_color = util.inspect(input, false, 0, false); var with_color = util.inspect(input, false, 0, true); var expect = '\u001b[' + color[0] + 'm' + without_color + '\u001b[' + color[1] + 'm'; assert.equal(with_color, expect, 'util.inspect color for style '+style); } test_color_style('special', function(){}); test_color_style('number', 123.456); test_color_style('boolean', true); test_color_style('undefined', undefined); test_color_style('null', null); test_color_style('string', 'test string'); test_color_style('date', new Date); test_color_style('regexp', /regexp/); // an object with "hasOwnProperty" overwritten should not throw assert.doesNotThrow(function() { util.inspect({ hasOwnProperty: null }); }); // new API, accepts an "options" object var subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); assert(util.inspect(subject, { showHidden: false }).indexOf('hidden') === -1); assert(util.inspect(subject, { showHidden: true }).indexOf('hidden') !== -1); assert(util.inspect(subject, { colors: false }).indexOf('\u001b[32m') === -1); assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1); assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1); assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1); assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); // "customInspect" option can enable/disable calling inspect() on objects subject = { inspect: function() { return 123; } }; assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); // custom inspect() functions should be able to return other Objects subject.inspect = function() { return { foo: 'bar' }; }; assert.equal(util.inspect(subject), '{ foo: \'bar\' }'); subject.inspect = function(depth, opts) { assert.strictEqual(opts.customInspectOptions, true); }; util.inspect(subject, { customInspectOptions: true }); // util.inspect with "colors" option should produce as many lines as without it function test_lines(input) { var count_lines = function(str) { return (str.match(/\n/g) || []).length; } var without_color = util.inspect(input); var with_color = util.inspect(input, {colors: true}); assert.equal(count_lines(without_color), count_lines(with_color)); } test_lines([1, 2, 3, 4, 5, 6, 7]); test_lines(function() { var big_array = []; for (var i = 0; i < 100; i++) { big_array.push(i); } return big_array; }()); test_lines({foo: 'bar', baz: 35, b: {a: 35}}); test_lines({ foo: 'bar', baz: 35, b: {a: 35}, very_long_key: 'very_long_value', even_longer_key: ['with even longer value in array'] }); node-util-0.12.5/test/node/log.js000066400000000000000000000043301432306420700165230ustar00rootroot00000000000000// 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. var assert = require('assert'); var util = require('../../'); assert.ok(process.stdout.writable); assert.ok(process.stderr.writable); var stdout_write = global.process.stdout.write; var strings = []; global.process.stdout.write = function(string) { strings.push(string); }; console._stderr = process.stdout; var propFnsAreNamed = { a: function () {} }.a.name === 'a'; var tests = [ {input: 'foo', output: 'foo'}, {input: undefined, output: 'undefined'}, {input: null, output: 'null'}, {input: false, output: 'false'}, {input: 42, output: '42'}, {input: function(){}, output: propFnsAreNamed ? '[Function: input]' : '[Function]'}, {input: parseInt('not a number', 10), output: 'NaN'}, {input: {answer: 42}, output: '{ answer: 42 }'}, {input: [1,2,3], output: '[ 1, 2, 3 ]'} ]; // test util.log() tests.forEach(function(test) { util.log(test.input); var result = strings.shift().trim(), re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/), match = re.exec(result); assert.ok(match); assert.equal(match[1], test.output); }); global.process.stdout.write = stdout_write; node-util-0.12.5/test/node/promisify.js000066400000000000000000000104251432306420700177650ustar00rootroot00000000000000var common = require('./common'); var assert = require('assert'); var fs = require('fs'); var vm = require('vm'); var promisify = require('../../util').promisify; if (typeof Promise === 'undefined') { console.log('no global Promise found, skipping promisify tests'); return; } var stat = promisify(fs.stat); { var promise = stat(__filename); assert(promise instanceof Promise); promise.then(common.mustCall(function (value) { assert.deepStrictEqual(value, fs.statSync(__filename)); })); } { var promise = stat('/dontexist'); promise.catch(common.mustCall(function (error) { assert(error.message.indexOf('ENOENT: no such file or directory, stat') !== -1); })); } { function fn() {} function promisifedFn() {} fn[promisify.custom] = promisifedFn; assert.strictEqual(promisify(fn), promisifedFn); assert.strictEqual(promisify(promisify(fn)), promisifedFn); } { function fn2() {} fn2[promisify.custom] = 42; common.expectsError( function () { promisify(fn2); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError } ); } // promisify args test disabled, it is an internal core API that is // not used anywhere anymore and this package does not implement it. if (false) { var firstValue = 5; var secondValue = 17; function fn3(callback) { callback(null, firstValue, secondValue); } fn3[customPromisifyArgs] = ['first', 'second']; promisify(fn3)().then(common.mustCall(function (obj) { assert.deepStrictEqual(obj, { first: firstValue, second: secondValue }); })); } { var fn4 = vm.runInNewContext('(function() {})'); assert.notStrictEqual(Object.getPrototypeOf(promisify(fn4)), Function.prototype); } { function fn5(callback) { callback(null, 'foo', 'bar'); } promisify(fn5)().then(common.mustCall(function (value) { assert.deepStrictEqual(value, 'foo'); })); } { function fn6(callback) { callback(null); } promisify(fn6)().then(common.mustCall(function (value) { assert.strictEqual(value, undefined); })); } { function fn7(callback) { callback(); } promisify(fn7)().then(common.mustCall(function (value) { assert.strictEqual(value, undefined); })); } { function fn8(err, val, callback) { callback(err, val); } promisify(fn8)(null, 42).then(common.mustCall(function (value) { assert.strictEqual(value, 42); })); } { function fn9(err, val, callback) { callback(err, val); } promisify(fn9)(new Error('oops'), null).catch(common.mustCall(function (err) { assert.strictEqual(err.message, 'oops'); })); } { function fn9(err, val, callback) { callback(err, val); } Promise.resolve() .then(function () { return promisify(fn9)(null, 42); }) .then(function (value) { assert.strictEqual(value, 42); }); } { var o = {}; var fn10 = promisify(function(cb) { cb(null, this === o); }); o.fn = fn10; o.fn().then(common.mustCall(function(val) { assert(val); })); } (function () { var err = new Error('Should not have called the callback with the error.'); var stack = err.stack; var fn11 = promisify(function(cb) { cb(null); cb(err); }); Promise.resolve() .then(function () { return fn11(); }) .then(function () { return Promise.resolve(); }) .then(function () { assert.strictEqual(stack, err.stack); }); })(); { function c() { } var a = promisify(function() { }); var b = promisify(a); assert.notStrictEqual(c, a); assert.strictEqual(a, b); } { var errToThrow; var thrower = promisify(function(a, b, c, cb) { errToThrow = new Error(); throw errToThrow; }); thrower(1, 2, 3) .then(assert.fail) .then(assert.fail, function (e) { assert.strictEqual(e, errToThrow); }); } { var err = new Error(); var a = promisify(function (cb) { cb(err) })(); var b = promisify(function () { throw err; })(); Promise.all([ a.then(assert.fail, function(e) { assert.strictEqual(err, e); }), b.then(assert.fail, function(e) { assert.strictEqual(err, e); }) ]); } [undefined, null, true, 0, 'str', {}, [], Symbol()].forEach(function (input) { common.expectsError( function () { promisify(input); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, message: 'The "original" argument must be of type Function' }); }); node-util-0.12.5/test/node/types.js000066400000000000000000000460521432306420700171150ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-util-types.js // https://github.com/nodejs/node/commit/519a11b24fa453e5cefe13df10ab9696616b5b91 // Flags: --experimental-vm-modules --expose-internals 'use strict'; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } require('./common'); var assert = require('assert'); var _require = require('../../'), types = _require.types; var vm = require('vm'); var Buffer = require('safe-buffer').Buffer var objectEntries = require('object.entries'); // "polyfill" deepStrictEqual on Node 0.12 and below if (!assert.deepStrictEqual) { assert.deepStrictEqual = assert.deepEqual; } function uncurryThis(f) { return f.call.bind(f); } var ObjectToString = uncurryThis(Object.prototype.toString); var inspect = function inspect(value) { try { return JSON.stringify(value); } catch (e) { return ObjectToString(value); } }; // [browserify] We can't test this in userland // const { internalBinding } = require('internal/test/binding'); // const { JSStream } = internalBinding('js_stream'); // const external = (new JSStream())._externalStream; var wasmBuffer = Buffer.from('0061736d01000000', 'hex'); for (var _i = 0, _arr = [ // [ external, 'isExternal' ], [function () { return new Date(); }, 'isDate'], [function () { return function () { return arguments; }(); }, 'isArgumentsObject'], [function () { return new Boolean(); }, 'isBooleanObject'], [function () { return new Number(); }, 'isNumberObject'], [function () { return new String(); }, 'isStringObject'], [function () { return Object(Symbol()); }, 'isSymbolObject'], [function () { return Object(BigInt(0)); }, 'isBigIntObject'], [function () { return new Error(); }, 'isNativeError'], [function () { return new RegExp(); }, 'isRegExp'], [function () { return eval('(async function() {})'); }, 'isAsyncFunction'], [function () { return eval('(function*() {})') }, 'isGeneratorFunction'], [function () { return eval('((function*() {})())') }, 'isGeneratorObject'], [function () { return Promise.resolve(); }, 'isPromise'], [function () { return new Map(); }, 'isMap'], [function () { return new Set(); }, 'isSet'], [function () { return new Map()[Symbol.iterator](); }, 'isMapIterator'], [function () { return new Set()[Symbol.iterator](); }, 'isSetIterator'], [function () { return new WeakMap(); }, 'isWeakMap'], [function () { return new WeakSet(); }, 'isWeakSet'], [function () { return new ArrayBuffer(1); }, 'isArrayBuffer'], [function () { return new Uint8Array(); }, 'isUint8Array'], [function () { return new Uint8ClampedArray(); }, 'isUint8ClampedArray'], [function () { return new Uint16Array(); }, 'isUint16Array'], [function () { return new Uint32Array(); }, 'isUint32Array'], [function () { return new Int8Array(); }, 'isInt8Array'], [function () { return new Int16Array(); }, 'isInt16Array'], [function () { return new Int32Array(); }, 'isInt32Array'], [function () { return new Float32Array(); }, 'isFloat32Array'], [function () { return new Float64Array(); }, 'isFloat64Array'], [function () { return new BigInt64Array(); }, 'isBigInt64Array'], [function () { return new BigUint64Array(); }, 'isBigUint64Array'], [function () { if (typeof Symbol === 'undefined' || typeof Symbol.toStringTag === 'undefined') { throw Error(); } return Object.defineProperty(new Uint8Array(), Symbol.toStringTag, { value: 'foo' }); }, 'isUint8Array'], [function () { return new DataView(new ArrayBuffer(1), 0, 1); }, 'isDataView'], [function () { return new SharedArrayBuffer(); }, 'isSharedArrayBuffer'], // [ new Proxy({}, {}), 'isProxy' ], [function () { return new WebAssembly.Module(wasmBuffer); }, 'isWebAssemblyCompiledModule'] ]; _i < _arr.length; _i++) { var _arr$_i = _slicedToArray(_arr[_i], 2), getValue = _arr$_i[0], method = _arr$_i[1]; var _value = void 0; try { _value = getValue(); } catch (e) { console.log('Skipping unsupported type:', getValue); continue; } console.log('Testing', method); assert(method in types, "Missing ".concat(method, " for ").concat(inspect(_value))); assert(types[method](_value), "Want ".concat(inspect(_value), " to match ").concat(method)); for (var _i3 = 0, _Object$keys2 = Object.keys(types); _i3 < _Object$keys2.length; _i3++) { var key = _Object$keys2[_i3]; if ((types.isArrayBufferView(_value) || types.isAnyArrayBuffer(_value)) && key.indexOf('Array') > -1 || key === 'isBoxedPrimitive') { continue; } assert.strictEqual(types[key](_value), key === method, "".concat(inspect(_value), ": ").concat(key, ", ") + "".concat(method, ", ").concat(types[key](_value))); } } // Check boxed primitives. console.log('Testing', 'isBoxedPrimitive'); [ function () { return new Boolean(); }, function () { return new Number(); }, function () { return new String(); }, function () { return Object(Symbol()); }, function () { return Object(BigInt(0)); } ].forEach(function (getEntry) { var entry; try { entry = getEntry(); } catch (e) { return; } assert(types.isBoxedPrimitive(entry)); }); var SymbolSupported = typeof Symbol !== 'undefined'; var SymbolToStringTagSupported = SymbolSupported && typeof Symbol.toStringTag !== 'undefined'; var isBuggyFirefox = typeof navigator !== 'undefined' && /Firefox\/\d+/.test(navigator.userAgent) && parseInt(navigator.userAgent.split('Firefox/')[1], 10) < 66 if (SymbolToStringTagSupported && !isBuggyFirefox) { [ 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array' ].forEach(function (typedArray) { var method = 'is' + typedArray; var constructor = 'new ' + typedArray; var array; try { array = vm.runInNewContext(constructor); } catch (e) { return; } console.log('Testing fake typed arrays', method); assert(!types[method](_defineProperty({}, Symbol.toStringTag, typedArray))); assert(types[method](array)); }); } if (isBuggyFirefox) { console.log('skipping fake typed array tests because they do not work in FF') } // Old Node.js had a fully custom Buffer implementation, newer are based on ArrayBuffer // This is important for the ArrayBuffer and typed array tests var isBufferBasedOnArrayBuffer = Buffer.alloc(1).buffer !== undefined; { var primitive = function primitive() { return true; }; var arrayBuffer = function arrayBuffer() { return new ArrayBuffer(1); }; var buffer = function buffer() { return Buffer.from(arrayBuffer()); }; var dataView = function dataView() { return new DataView(arrayBuffer(), 0, 1); }; var uint8Array = function uint8Array() { return new Uint8Array(arrayBuffer()); }; var uint8ClampedArray = function uint8ClampedArray() { return new Uint8ClampedArray(arrayBuffer()); }; var uint16Array = function uint16Array() { return new Uint16Array(arrayBuffer()); }; var uint32Array = function uint32Array() { return new Uint32Array(arrayBuffer()); }; var int8Array = function int8Array() { return new Int8Array(arrayBuffer()); }; var int16Array = function int16Array() { return new Int16Array(arrayBuffer()); }; var int32Array = function int32Array() { return new Int32Array(arrayBuffer()); }; var float32Array = function float32Array() { return new Float32Array(arrayBuffer()); }; var float64Array = function float64Array() { return new Float64Array(arrayBuffer()); }; var bigInt64Array = function bigInt64Array() { return new BigInt64Array(arrayBuffer()); }; var bigUint64Array = function bigUint64Array() { return new BigUint64Array(arrayBuffer()); }; var fakeBuffer = function fakeBuffer() { if (!SymbolToStringTagSupported) { throw new Error(); } return Object.create(Buffer.prototype); }; var fakeDataView = function fakeDataView() { if (!SymbolToStringTagSupported) { throw new Error(); } return Object.create(DataView.prototype); }; var fakeUint8Array = function fakeUint8Array() { return Object.create(Uint8Array.prototype); }; var fakeUint8ClampedArray = function fakeUint8ClampedArray() { return Object.create(Uint8ClampedArray.prototype); }; var fakeUint16Array = function fakeUint16Array() { return Object.create(Uint16Array.prototype); }; var fakeUint32Array = function fakeUint32Array() { return Object.create(Uint32Array.prototype); }; var fakeInt8Array = function fakeInt8Array() { return Object.create(Int8Array.prototype); }; var fakeInt16Array = function fakeInt16Array() { return Object.create(Int16Array.prototype); }; var fakeInt32Array = function fakeInt32Array() { return Object.create(Int32Array.prototype); }; var fakeFloat32Array = function fakeFloat32Array() { return Object.create(Float32Array.prototype); }; var fakeFloat64Array = function fakeFloat64Array() { return Object.create(Float64Array.prototype); }; var fakeBigInt64Array = function fakeBigInt64Array() { return Object.create(BigInt64Array.prototype); }; var fakeBigUint64Array = function fakeBigUint64Array() { return Object.create(BigUint64Array.prototype); }; var stealthyDataView = function stealthyDataView() { return Object.setPrototypeOf(new DataView(arrayBuffer(), 0, 1), Uint8Array.prototype); }; var stealthyUint8Array = function stealthyUint8Array() { return Object.setPrototypeOf(new Uint8Array(arrayBuffer()), ArrayBuffer.prototype); }; var stealthyUint8ClampedArray = function stealthyUint8ClampedArray() { return Object.setPrototypeOf(new Uint8ClampedArray(arrayBuffer()), ArrayBuffer.prototype); }; var stealthyUint16Array = function stealthyUint16Array() { return Object.setPrototypeOf(new Uint16Array(arrayBuffer()), Uint16Array.prototype); }; var stealthyUint32Array = function stealthyUint32Array() { return Object.setPrototypeOf(new Uint32Array(arrayBuffer()), Uint32Array.prototype); }; var stealthyInt8Array = function stealthyInt8Array() { return Object.setPrototypeOf(new Int8Array(arrayBuffer()), Int8Array.prototype); }; var stealthyInt16Array = function stealthyInt16Array() { return Object.setPrototypeOf(new Int16Array(arrayBuffer()), Int16Array.prototype); }; var stealthyInt32Array = function stealthyInt32Array() { return Object.setPrototypeOf(new Int32Array(arrayBuffer()), Int32Array.prototype); }; var stealthyFloat32Array = function stealthyFloat32Array() { return Object.setPrototypeOf(new Float32Array(arrayBuffer()), Float32Array.prototype); }; var stealthyFloat64Array = function stealthyFloat64Array() { return Object.setPrototypeOf(new Float64Array(arrayBuffer()), Float64Array.prototype); }; var stealthyBigInt64Array = function stealthyBigInt64Array() { return Object.setPrototypeOf(new BigInt64Array(arrayBuffer()), BigInt64Array.prototype); }; var stealthyBigUint64Array = function stealthyBigUint64Array() { return Object.setPrototypeOf(new BigUint64Array(arrayBuffer()), BigUint64Array.prototype); }; var typedArrays = objectEntries({ primitive: primitive, arrayBuffer: arrayBuffer, buffer: buffer, fakeBuffer: fakeBuffer, dataView: dataView, fakeDataView: fakeDataView, stealthyDataView: stealthyDataView, uint8Array: uint8Array, fakeUint8Array: fakeUint8Array, stealthyUint8Array: stealthyUint8Array, uint8ClampedArray: uint8ClampedArray, fakeUint8ClampedArray: fakeUint8ClampedArray, stealthyUint8ClampedArray: stealthyUint8ClampedArray, uint16Array: uint16Array, fakeUint16Array: fakeUint16Array, stealthyUint16Array: stealthyUint16Array, uint32Array: uint32Array, fakeUint32Array: fakeUint32Array, stealthyUint32Array: stealthyUint32Array, int8Array: int8Array, fakeInt8Array: fakeInt8Array, stealthyInt8Array: stealthyInt8Array, int16Array: int16Array, fakeInt16Array: fakeInt16Array, stealthyInt16Array: stealthyInt16Array, int32Array: int32Array, fakeInt32Array: fakeInt32Array, stealthyInt32Array: stealthyInt32Array, float32Array: float32Array, fakeFloat32Array: fakeFloat32Array, stealthyFloat32Array: stealthyFloat32Array, float64Array: float64Array, fakeFloat64Array: fakeFloat64Array, stealthyFloat64Array: stealthyFloat64Array, bigInt64Array: bigInt64Array, fakeBigInt64Array: fakeBigInt64Array, stealthyBigInt64Array: stealthyBigInt64Array, bigUint64Array: bigUint64Array, fakeBigUint64Array: fakeBigUint64Array, stealthyBigUint64Array: stealthyBigUint64Array }); typedArrays.forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], createTypedArray = _ref2[1]; try { typedArrays[key] = createTypedArray(); } catch (e) { typedArrays[key] = undefined; } }); primitive = typedArrays.primitive; arrayBuffer = typedArrays.arrayBuffer; buffer = typedArrays.buffer; fakeBuffer = typedArrays.fakeBuffer; dataView = typedArrays.dataView; fakeDataView = typedArrays.fakeDataView; stealthyDataView = typedArrays.stealthyDataView; uint8Array = typedArrays.uint8Array; fakeUint8Array = typedArrays.fakeUint8Array; stealthyUint8Array = typedArrays.stealthyUint8Array; uint8ClampedArray = typedArrays.uint8ClampedArray; fakeUint8ClampedArray = typedArrays.fakeUint8ClampedArray; stealthyUint8ClampedArray = typedArrays.stealthyUint8ClampedArray; uint16Array = typedArrays.uint16Array; fakeUint16Array = typedArrays.fakeUint16Array; stealthyUint16Array = typedArrays.stealthyUint16Array; uint32Array = typedArrays.uint32Array; fakeUint32Array = typedArrays.fakeUint32Array; stealthyUint32Array = typedArrays.stealthyUint32Array; int8Array = typedArrays.int8Array; fakeInt8Array = typedArrays.fakeInt8Array; stealthyInt8Array = typedArrays.stealthyInt8Array; int16Array = typedArrays.int16Array; fakeInt16Array = typedArrays.fakeInt16Array; stealthyInt16Array = typedArrays.stealthyInt16Array; int32Array = typedArrays.int32Array; fakeInt32Array = typedArrays.fakeInt32Array; stealthyInt32Array = typedArrays.stealthyInt32Array; float32Array = typedArrays.float32Array; fakeFloat32Array = typedArrays.fakeFloat32Array; stealthyFloat32Array = typedArrays.stealthyFloat32Array; float64Array = typedArrays.float64Array; fakeFloat64Array = typedArrays.fakeFloat64Array; stealthyFloat64Array = typedArrays.stealthyFloat64Array; bigInt64Array = typedArrays.bigInt64Array; fakeBigInt64Array = typedArrays.fakeBigInt64Array; stealthyBigInt64Array = typedArrays.stealthyBigInt64Array; bigUint64Array = typedArrays.bigUint64Array; fakeBigUint64Array = typedArrays.fakeBigUint64Array; stealthyBigUint64Array = typedArrays.stealthyBigUint64Array; var all = [ primitive, arrayBuffer, buffer, fakeBuffer, dataView, fakeDataView, stealthyDataView, uint8Array, fakeUint8Array, stealthyUint8Array, uint8ClampedArray, fakeUint8ClampedArray, stealthyUint8ClampedArray, uint16Array, fakeUint16Array, stealthyUint16Array, uint32Array, fakeUint32Array, stealthyUint32Array, int8Array, fakeInt8Array, stealthyInt8Array, int16Array, fakeInt16Array, stealthyInt16Array, int32Array, fakeInt32Array, stealthyInt32Array, float32Array, fakeFloat32Array, stealthyFloat32Array, float64Array, fakeFloat64Array, stealthyFloat64Array, bigInt64Array, fakeBigInt64Array, stealthyBigInt64Array, bigUint64Array, fakeBigUint64Array, stealthyBigUint64Array ]; var expected = { isArrayBufferView: [ isBufferBasedOnArrayBuffer ? buffer : undefined, dataView, stealthyDataView, uint8Array, stealthyUint8Array, uint8ClampedArray, stealthyUint8ClampedArray, uint16Array, stealthyUint16Array, uint32Array, stealthyUint32Array, int8Array, stealthyInt8Array, int16Array, stealthyInt16Array, int32Array, stealthyInt32Array, float32Array, stealthyFloat32Array, float64Array, stealthyFloat64Array, bigInt64Array, stealthyBigInt64Array, bigUint64Array, stealthyBigUint64Array ], isTypedArray: [ isBufferBasedOnArrayBuffer ? buffer : undefined, uint8Array, stealthyUint8Array, uint8ClampedArray, stealthyUint8ClampedArray, uint16Array, stealthyUint16Array, uint32Array, stealthyUint32Array, int8Array, stealthyInt8Array, int16Array, stealthyInt16Array, int32Array, stealthyInt32Array, float32Array, stealthyFloat32Array, float64Array, stealthyFloat64Array, bigInt64Array, stealthyBigInt64Array, bigUint64Array, stealthyBigUint64Array ], isUint8Array: [ isBufferBasedOnArrayBuffer ? buffer : undefined, uint8Array, stealthyUint8Array ], isUint8ClampedArray: [ uint8ClampedArray, stealthyUint8ClampedArray ], isUint16Array: [ uint16Array, stealthyUint16Array ], isUint32Array: [ uint32Array, stealthyUint32Array ], isInt8Array: [ int8Array, stealthyInt8Array ], isInt16Array: [ int16Array, stealthyInt16Array ], isInt32Array: [ int32Array, stealthyInt32Array ], isFloat32Array: [ float32Array, stealthyFloat32Array ], isFloat64Array: [ float64Array, stealthyFloat64Array ], isBigInt64Array: [ bigInt64Array, stealthyBigInt64Array ], isBigUint64Array: [ bigUint64Array, stealthyBigUint64Array ] }; Object.keys(expected).forEach(function (testedFunc) { console.log('Testing values for:', testedFunc); var func = types[testedFunc]; var yup = []; all .filter(function (a) { return typeof a !== 'undefined'; }) .forEach(function (value) { if (func(value)) { yup.push(value); } }); assert.deepStrictEqual( yup, expected[testedFunc].filter(function (a) { return typeof a !== 'undefined'; }) ); }); } // (async () => { // const m = new vm.SourceTextModule(''); // await m.link(() => 0); // m.instantiate(); // await m.evaluate(); // assert.ok(types.isModuleNamespaceObject(m.namespace)); // })(); node-util-0.12.5/test/node/util.js000066400000000000000000000070651432306420700167270ustar00rootroot00000000000000// 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. var assert = require('assert'); var context = require('vm').runInNewContext; var util = require('../../'); // isArray assert.equal(true, util.isArray([])); assert.equal(true, util.isArray(Array())); assert.equal(true, util.isArray(new Array())); assert.equal(true, util.isArray(new Array(5))); assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); assert.equal(true, util.isArray(context('Array')())); assert.equal(false, util.isArray({})); assert.equal(false, util.isArray({ push: function() {} })); assert.equal(false, util.isArray(/regexp/)); assert.equal(false, util.isArray(new Error)); assert.equal(false, util.isArray(Object.create(Array.prototype))); // isRegExp assert.equal(true, util.isRegExp(/regexp/)); assert.equal(true, util.isRegExp(RegExp())); assert.equal(true, util.isRegExp(new RegExp())); assert.equal(true, util.isRegExp(context('RegExp')())); assert.equal(false, util.isRegExp({})); assert.equal(false, util.isRegExp([])); assert.equal(false, util.isRegExp(new Date())); assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); // isDate assert.equal(true, util.isDate(new Date())); assert.equal(true, util.isDate(new Date(0))); assert.equal(true, util.isDate(new (context('Date')))); assert.equal(false, util.isDate(Date())); assert.equal(false, util.isDate({})); assert.equal(false, util.isDate([])); assert.equal(false, util.isDate(new Error)); assert.equal(false, util.isDate(Object.create(Date.prototype))); // isError assert.equal(true, util.isError(new Error)); assert.equal(true, util.isError(new TypeError)); assert.equal(true, util.isError(new SyntaxError)); assert.equal(true, util.isError(new (context('Error')))); assert.equal(true, util.isError(new (context('TypeError')))); assert.equal(true, util.isError(new (context('SyntaxError')))); assert.equal(false, util.isError({})); assert.equal(false, util.isError({ name: 'Error', message: '' })); assert.equal(false, util.isError([])); assert.equal(true, util.isError(Object.create(Error.prototype))); // isObject assert.ok(util.isObject({}) === true); // _extend assert.deepEqual(util._extend({a:1}), {a:1}); assert.deepEqual(util._extend({a:1}, []), {a:1}); assert.deepEqual(util._extend({a:1}, null), {a:1}); assert.deepEqual(util._extend({a:1}, true), {a:1}); assert.deepEqual(util._extend({a:1}, false), {a:1}); assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); node-util-0.12.5/util.js000066400000000000000000000463611432306420700150250ustar00rootroot00000000000000// 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. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { if (typeof process !== 'undefined' && process.noDeprecation === true) { return fn; } // Allow for deprecating things in the process of starting up. if (typeof process === 'undefined') { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnvRegex = /^$/; if (process.env.NODE_DEBUG) { var debugEnv = process.env.NODE_DEBUG; debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') .replace(/\*/g, '.*') .replace(/,/g, '$|^') .toUpperCase(); debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); } exports.debuglog = function(set) { set = set.toUpperCase(); if (!debugs[set]) { if (debugEnvRegex.test(set)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').slice(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.slice(1, -1); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. exports.types = require('./support/types'); function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; exports.types.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; exports.types.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; exports.types.isNativeError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * 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. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; exports.promisify = function promisify(original) { if (typeof original !== 'function') throw new TypeError('The "original" argument must be of type Function'); if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { var fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== 'function') { throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { var promiseResolve, promiseReject; var promise = new Promise(function (resolve, reject) { promiseResolve = resolve; promiseReject = reject; }); var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } args.push(function (err, value) { if (err) { promiseReject(err); } else { promiseResolve(value); } }); try { original.apply(this, args); } catch (err) { promiseReject(err); } return promise; } Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties( fn, getOwnPropertyDescriptors(original) ); } exports.promisify.custom = kCustomPromisifiedSymbol function 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) { var newReason = new Error('Promise was rejected with a falsy value'); newReason.reason = reason; reason = newReason; } return cb(reason); } function callbackify(original) { if (typeof original !== 'function') { throw new TypeError('The "original" argument must be of type Function'); } // 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() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args) .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); } Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); return callbackified; } exports.callbackify = callbackify;