Files
DefinitelyTyped/node/node-tests.ts
Mohamed Hegazy 80060c94ef Merge 10/04 (#11739)
* Add ERROR_STATE flag

* added prop options and func timeFormatter

added property `options`, which can be found in [the code](15fc4b62f5/smoothie.js (L270)).
Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme.

added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](15fc4b62f5/smoothie.js (L795))

* Fix type errors

* Added typings for css-modules-require-hook

* Remove spaces

* Added semver, added explicit ignore callback, unified array definition and removed one time interface

* Overwriting method signature

* Correct parameter type

* Add MobilePhoneLocale

* Add isMobilePhone tests

* Type definitions for bit-array

* Add emit for cluster

* To use the definition inline

* [logat.d.ts] Type definition for node module 'logat' (#11485)

* Create logat.d.ts

* Create logat-tests.ts

* Update logat-tests.ts

* Update logat-tests.ts

* Update logat.d.ts

* updated logat test

* updated type definiton

* [dateformat.d.ts] Add definitions for dateformat

* Remove the ES6 module hack

* Yayson definitions (#11484)

* Add yayson Store typings

* Add yayson Store tests

* Improve yayson coverage

* Specify version in yayson definition

* Remove yayson generics and tidy

* Changed namespace from angularTouchspin to angular.touchspin (#11414)

* [perfect-scrollbar.d.ts] Add definitions for perfect-scrollbar (#11486)

* Added types for klaw (#11492)

* Added types for klaw

* addressed pr comments and `tsfmt -r klaw/*.ts`

* add typings for onselected and onunselected methods, refs #11493 (#11496)

* Improve through2 declarations (#11499)

* [through2] Fix typos

* [through2] Change return types to stream.Transform

`through2` creates `stream.Transform`-flavored streams, so switching the return types to `stream.Transform` gives us richer typing information than using `NodeJS.ReadWriteStream`, which is missing methods (e.g. `stream.Transform#push`) and the ability to use object mode.

* [through2] Add through2.ctor method

* [through2] Update header and docs

* Add module declaration to crossfilter so that it can be explicitly imported (#11521)

* Add typings for murmurhash3js

* fix module import to be ES6 compliant

* newline at EOF

* [rethinkdb] Adds missing promise methods to Cursor and Connection

* [rethinkdb] Applied TypeScript formatting to the file

* [rethinkdb] Adds types to Cursor methods

* webpack - HotModuleReplacementPlugin has opts arg

* [openlayers] forEachFeatureAtPixel can return a value

See doc http://openlayers.org/en/latest/apidoc/ol.Map.html#forEachFeatureAtPixel

* Update react.d.ts

Added myself as an author so I get notifications of PRs / updates from GitHub.

* vue: fixed definition for activate() in ComponentOption

* Fix error that came using typescript 2

This error come when try compile with typescript 2
kue.d.ts(13,3): error TS2440: Import declaration conflicts with local declaration of 'redis'

* path can be string or a hash of options

As per http://restify.com/#client-api it states:

> Note that all further documentation refers to the "short-hand"
> form of methods like get/put/del which take a string path. You
> can also pass in an object to any of those methods with extra
> params (notably headers):

So the path can be either a string or a hash of options.

* Add CognitoIdentity into aws-sdk

* Font advanced config options added (for v2.0.6+)

* Add missing slider parameters

* Add backspaceToRemoveMessage prop

* fixup! path can be string or a hash of options

* add request.body (#11395)

* add request.body

* Update koa-bodyparser.d.ts

According to the documentation of `koa-bodyparser`:
```javascript
 // the parsed body will store in this.request.body
 // if nothing was parsed, body will be an empty object {}
 ctx.body = ctx.request.body;
```

Therefore the `body` property will exit in the `request` object.
Changing the `body` property from optional to required can also fix the conflict problem in Koa's declaration file:
```ts
 class Koa extend Request, Response {}
```

* Implement tilebelt definition (#11495)

* Add import test (#11476)

* [validator] Add new stuff which document not mentioned (#11498)

* Add new stuff which document not mentioned

* Add related test

* http.ServerRequest => http.IncomingMessage (#11500)

* [node] Add events for dgram (#11501)

* Add events for dgram

* Add tests for dgram

* Correct dgram.RemoteInfo interface

* Correct emit

* Correct emit

* [node] Add events for tls.Server and tls.TLSSocket (#11502)

* Add events for tls.Server

* Add tests for tls.Server

* Add tests for TLSSocket

* Add events for TLSSocket

* [react-router] Update getComponents signatures (#11319)

Update `getComponent(s)` all over the place. See #9530 for more info.

* Updated jquery.dataTables for 1.10.7. (#11408)

* Updated jquery.dataTables for 1.10.7.

Version release notes: https://cdn.datatables.net/1.10.7/

* Added any()
* Added i18n()

Note: selector-modifier support currently exists with interface ObjectSelectorModifier.

* Added strong variable typing in jquery.dataTables-tests.ts

* For parameter 'def', replaced 'Object' data type with 'any' per TypeScript declaration file guidance.

* [HAPI] Add `IStrictSessionHandler` (#11523)

* Fix #11519

* Added FileResizeOptions for the changed resize function call

* getEvent should not be set to void it should return a value (#11135)

* getEvent should not be set to void it should return a value

* Add type to getActionData for testing

* pnotify Add type fpr notice styling and state

* fix pnotify test

* Remove Generics and replaces by return any

* convert space tp tabs

* Add barTintColor to NavigatorIOS (#11522)

* GreenSock TweenMax TweenLite config Object typed refs #11265 (#11310)

* refs #9944

* refs #11265

* refs #11265

* Call strategy with only mode or options (#11466)

* Call strategy with only mode or options

* Refactor `server.auth.strategy`

* - add client.exists([params, [callback]]) (#11515)

* Update to Electron 1.4.1 (#11481)

* Correct fs.createWriteStream (#11560)

* add  declaration file for  weapp (#11554)

* add  declaration file of  weapp

* rename "weapp" to "weapp-api"

rename "weapp" to "weapp-api" to avoid naming conflicts

* Added more methods to Turf (#11558)

* Added more methods to Turf
- circle
- geojsonType
- propReduce
- coordAll
- tesselate

* Replace Object with GeoJSON

* Implemented cheap-ruler definition

* Remove GeoJSON dependency

* Cheap-ruler fixes
- Removed GeoJSON from tests
- Added return-type to fromTile

* Update JSDocs cheap-ruler
Update based on comments https://github.com/mapbox/cheap-ruler/pull/20
- Removed `{@name}`
- Changed {Object} to {CheapRuler}

* [bluebird] document .suppressUnhandledRejections

http://bluebirdjs.com/docs/api/suppressunhandledrejections.html

* Add typings for shallowequal.

* URIjs fix .joinPaths()

the .joinPaths function is on URIStatic, not an instance of URI
https://medialize.github.io/URI.js/docs.html#static-joinPaths

* set document id property to be optional

* Fixed type of onchallenge

* feat(CKEditor): Add missing typings for `focusManager`

* sequelize: fix return value type of Model.findOrXXX methods

http://docs.sequelizejs.com/en/latest/api/model/#findorinitialize-promiseinstance-initialized

* Added type Point for simplicity
Comments from @vladima

* add interface for mongoose document optional properties

* optional constructor for RecurrenceRule

* fix the framework type

* add parameter support in initialize()

* add callback parameter

* Added promise() to the JQueryPromise<T> interface

jQuery allows calling a promise() function on a Promise object. Updated the interface to reflect this.

* optional authorize

* add contains fn

* Update ip-tests.ts

* Added tests for the promise() method on jqXHR

Ensures that the jqXHR object exposes a standard promise because it implements the JQueryPromise<T> interface.

* angular-dynamic-local Add "storageKey" definition (#11566)

Add "storageKey" definition

cf : https://github.com/lgalfaso/angular-dynamic-locale/blob/master/src/tmhDynamicLocale.js#L197

* Added declare module for easier including. (#11562)

* Adding recompose@0.20.2 typings (#11577)

* Added typings for change-emitter@0.1.2

* Adding recompose@0.20.2 typings

* Update typescript definition for selectize to 0.12.13 (#11570)

* [react-router-redux] Update action payload type (#11559)

The payload for React Redux Router action is a location object. For more information look at the source code [here](https://github.com/reactjs/react-router-redux/blob/master/src/sync.js#L95)

* [openlayers] Rewrite for openlayers 3.18.2 (#11339)

* Added missing config options for release v2.0.8 (#11595)

* [graphql] Create graphql (#11598)

* Complete graphql/language

* Update graphql/error

* Update graphql.d.ts

* Create graphql-tests.ts

* Update graphql/type

* Update graphql/error and graphql/execution

* Remove null type

* Remove comma

* ej typings v14.3.0.49 added (#11597)

* ej typings v14.3.0.49 added

* jquery dependent added

* react-bootstrap-table: add ignoreSinglePage option (#11581)

As shown in the [docs](http://allenfang.github.io/react-bootstrap-table/docs.html)

```
ignoreSinglePage : Bool
Enable to ignore the pagination if only one page, default is false.
```

* There is no INST_EDGE_FALLING exported const but INT_EDGE_FALLING (#11603)

Exporting correct `const` `INST_EDGE_FALLING` -> `INT_EDGE_FALLING`

* Complete HighchartsBarStates interface. Add Color interface (#11505)

- HighchartsBarStates interfaces didn't include `borderColor` and `color` properties, as documented in http://api.highcharts.com/highcharts/plotOptions.bar.states.hover
- A Color interface was added, since the documentation refers many times to `Color` as a type. This colors can be either a string or a gradient, as stated in http://www.highcharts.com/docs/chart-design-and-style/colors. The introduction of this type should help alleviating the errors currently present where certain "color" properties are only allowed to be strings.

* Add definition for swagger-jsdoc (#11298)

* Add definition for swagger-jsdoc

* Update files

* Remove interface and use any instead for options, fix tests

* Fix Usage example

* Add definitions for: "bunyan-config", "express-mung", "node-vitalsigns" and "memwatch-next" (#11285)

* Add definition for "bunnymq".

* Add definition for "strftime".

* Add definitions for: "bunyan-config", "express-mung" and
"node-vitalsigns".

* Add definitions for: "bunyan-config", "express-mung" and
"node-vitalsigns".

* Add definition for "memwatch-next".

* Fix project URL address.

* Rename "node-vitalsigns" to "vitalsigns".

* Update definitions.

* Use {} instead of "Object" type.
Remove unnecessary namespace for "memwatch-next" definition.
Rewrite "bunyan-config" definition.

* Replace "Object" by "{}".

* (helmet): change to namespace and export interfaces (#11585)

* Replace reference to deprecated http.ClientResponse with newer http.IncomingMessage (#11596)

* [cheerio] Adds missing load(CheerioElement) (#11520)

* add id (#11619)

* add id

* remove readonly

* add touch after

* fix typo

* change Topic property latch to boolean type (#11607)

* Add AngularJS linky filter definition (#11507)

* Support universal modules for SAT (#11632)

* changed versionKey in Schema spec to string

* better structure

* Add argumentless Q()

* add definitions for tz-format (#11565)

* add definitions for tz-format

* fix return type

* Create typings for ngeohash (#11634)

* [nprogress] Update configuration properties (#11627)

Update a couple of nprogress configuration properties:
* `ease` is renamed to `easing`.
* `trickleRate` is removed.
* `parent` is added.

More info [here](https://github.com/rstacruz/nprogress/blob/master/nprogress.js#L19-L31)

* Fix leaflet L.GeoJSON.addData et al (#11590) (#11591)

* NotificationAlertOptions can have a subtitle (#11638)

* Parse5 comment data (#11649)

* Add test for data

* Update parse5.d.ts

* feat: add localforage-cordovasqlitedriver definition (#11650)

* Fix export for "bunyan-config" and improve definitions (#11653)

* Fix export for "bunyan-config".

* Update definitions.
Replace "Object" to "{}" type.
Add "express" property in "VitalSigns" class.

* Update ejs.d.ts (#11467)

This typings give an error when templating HTML 

Error: Cannot invoke an expression whose type lacks a call signature.

my code 
```javascript
var templateFunction = EJS.compile(SOMESTRTEMPLATE);
myDomElement.innerHTML = templateFunction(someDataObject) // <= ERROR
```

* Added hyperscript module (#11661)

* update parsimmon typings for parsimmon 0.9.2 (#11648)

* update parsimmon typings for parsimmon 0.9.2

* add overloads for parsimmon#seq

* code review

* Fix babel-traverse buildCodeFrameError signature (#11654)

The Error argument is not an error instance, instead it is a constructor function that returns an error instance. 
Additionally, the constructor function is optional, by default SyntaxError is used

* Added type definition for riot library (#11664)

* Added type definition for riot

* Added type information for compile function, version, settings and template error handler

* Updated namespace name Riot -> riot

* Renamed riot-test.ts -> riot-tests.ts

* Add definitions for pem (#11666)

https://github.com/andris9/pem

* Added hapi-decorators.d.ts (#11668)

* Add missing each, and correct type of Date.now() (#11670)

* Add definitions for spdy (#11672)

https://github.com/indutny/node-spdy

* Allow interface to be named (#11673)

> error TS4023: Exported variable 'DevTools' has or is using name 'IDevTools' from external module "/Users/remojansen/CODE/forks/redux-bootstrap/node_modules/@types/redux-devtools/index" but cannot be named.

* Add array methods to LoDashExplicitArrayWrapper to match LoDashImplicitArrayWrapper. (#11518)

* add transducers-js types w/ tests (#11676)

* Fix redeclare block-scoped Base64 (#11677)

Issue found by https://github.com/dankogai/js-base64/issues/38#issuecomment-250999729

* added seed, randomTests and randomizeTests property (#11678)

* Add toJSON method to signature (#11682)

* Fix instance of cropperjs for library version > 0.8 (#11490)

* Updated fbsdk definitions for authentication responses and api calls. (#11686)

Fixes #11327
May help with #11007

* Create typings for jquery-alertable (#11642)

* ADD: definition file for the moment-duration-format library (#11557)

* Update d.ts file for Dialog API updates (#11526)

* Add support for Highcharts modules: offline exporting and boost (#11030)

* Create highcharts-modules-offline-exporting

* Rename highcharts-modules-offline-exporting to highcharts-modules-offline-exporting.d.ts

* Create highcharts-modules-boost.d.ts

* Added cash-js.d.ts File (#10765)

* Added cash-js.d.ts File

* Fixed Link break issue

* Renamed from cash-js to cash

* Fixed the module name as suggested

* Update headroom.d.ts (#11313)

notBottom  missing from definition

* Added the definition for the npm package simple-url-cache (#11296)

* Added the definition for the npm package simple-url-cache

https://www.npmjs.com/package/simple-url-cache

* - Some problems with shells.js missing the touch fucntion deifnition

* More details on the touch parameters - nice screenshot btw

* Updated the RowMethods interface (#11665)

* Updated the RowMethods interface

This Interface was missing the Definition of the id() method.

Link to official documentation: https://datatables.net/reference/api/row().id()

* Changed indentation from tabs to spaces

* Added definition file for Defaults Js Library (#11451)

* Added missing className property to CardProps (#10823)

The className property for CardPros is missing, so using it like
<Card className={this.myClass}>...</Card>
is not possible.

* Add missing perMessageDeflate server option (#11380)

* Add missing class AgendaView (#11371)

* Add missing class AgendaView

* Move class to kendo.ui namespace

* Change path to interface

* Add static fn

* Add static extend

* Add static extend

* Resolve conflicts

* adds system faker methods (#11432)

* added definitions for SharePoint file Search.ClientControls.js (#11652)

* added definitions for SharePoint file Search.ClientControls.js (Srch namespace, heavily used in Search Display Templates)

* --noImplicitAny compatibility fixes
also small improvements

* more fixes for --noImplicitAny

* Adding union type for offset (#11689)

* add type definitions for msgpack-lite package. (#11690)

* Updating jasmine to version 2.5 (#11688)

* Updating jasmine to version 2.5

* Fixing 2 small errors in the update of jasmine

* withMock now takes a  "() => void"

* fixed the withMock syntax error

* number added as type to seed function

* add missing isEmpty function (#11698)

* Added type definitions for terminal-menu (#11697)

* Update THREE.js definitions to r81 (#11679)

* Update THREE.js definitions to r81

* Update test_unit_maths.ts to r81

* Update version in header to r81

* UPDATE localForage type definitions (#11702)

* Update Google Maps API type definition to 3.25 (#11626)

* Update Google Maps Places Library definition

- According to the Places Library documentation (https://goo.gl/EJFiuQ), certain fields are being removed
- I have aligned the Places Library definitions with the API reference (https://goo.gl/kYoi9V) and added deprecation comments for the old properties as they are still accepted until February
- I could not find an official deprecation attribute or similar for Typescript definitions so I just left a comment

* Update the API version in the header

* Apply API changes between version 3.20 and 3.25

- Used the Google Maps API release notes (https://goo.gl/nRUZGJ) as a reference

* Fix inconsistant type definition

* Override ol.layer.Vector#getSource() (#11703)

Reference: http://openlayers.org/en/latest/apidoc/ol.layer.Vector.html

* Replace number[] by [number, number] (#11704)

* [lodash]: memoize.Cache expects construcor (#11707)

https://lodash.com/docs/4.15.0#memoize

* Added jquery.flagstrap.js definition suport (#11710)

* apply declaration merging (#10900)

* Update material-ui.d.ts (#11353)

Expose ThemePalette interface.

* Change ChartAxisXOptions (#11449)

Change the type for minimum and maximum options in ChartAxisXOptions to
support both number and Date.

* Improve support for arrays of promises (#11685)

* Alias IWhenable<T> = IPromise<T> | T

* Allow all Q functions to work with either promises or raw values

* Allow functions expecting arrays to take promises for arrays

Q.race is deliberately excluded, as this does not support this type of argument.

* scheduler options (#11543)

* Added missing move function (#11563)

* Added missing move function

Added missing move function in typings so that the move function is recognised by the IDE and the compiler.

* Minor derp here

* Add missing Valdr typings for validation results and constraints (#11636)

* Add missing Valdr types

Add ValdrValidationConstraints and ValdrValidationResult typings

* Refine Valdr-message typings

Set a more refined type to messages instead of any

* Expand Valdr typings tests

Expand tests to include added typings for ValdrValidationResult and ValdrConstraints

* Fix spacing

Replace tabs by spaces

* Rename vars in test

Rename vars to make test clearer

* Fix TS issues

Added missing types

* Remove undefined

In TS by default null and undefined are subtypes of all other types

* Fix wrong type

Add missing namespace

* Fix wrong version number

Set version to only numbers

* Fix wrong version number

Keep version to only numbers

* Use douple quotes

* Remove invalid triple-slash references

* Add tsconfig.json files and move main file to index.d.ts

* Rename file to index.d.ts

* Remove tscparams files

* Remove unused file

* Remove invalid references

* Move hapi-decorator to use index.d.ts

* Switch to use external modules

* Correctely extend angular

* Fix tsconfig.json

* Remove unused references

* HACK: Put back /// reference tag.
2016-10-05 11:40:00 -07:00

1799 lines
53 KiB
TypeScript

import * as assert from "assert";
import * as fs from "fs";
import * as events from "events";
import * as zlib from "zlib";
import * as url from "url";
import * as util from "util";
import * as crypto from "crypto";
import * as tls from "tls";
import * as http from "http";
import * as https from "https";
import * as net from "net";
import * as tty from "tty";
import * as dgram from "dgram";
import * as querystring from "querystring";
import * as path from "path";
import * as readline from "readline";
import * as childProcess from "child_process";
import * as cluster from "cluster";
import * as os from "os";
import * as vm from "vm";
import * as console2 from "console";
import * as string_decoder from "string_decoder";
import * as stream from "stream";
import * as timers from "timers";
// Specifically test buffer module regression.
import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer";
//////////////////////////////////////////////////////////
/// Assert Tests : https://nodejs.org/api/assert.html ///
//////////////////////////////////////////////////////////
namespace assert_tests {
{
assert(1 + 1 - 2 === 0, "The universe isn't how it should.");
assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP");
assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator");
assert.doesNotThrow(() => {
const b = false;
if (b) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
assert.equal(3, "3", "uses == comparator");
assert.fail(1, 2, undefined, '>');
assert.ifError(0);
assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator");
assert.notEqual(1, 2, "uses != comparator");
assert.notStrictEqual(2, "2", "uses === comparator");
assert.ok(true);
assert.ok(1);
assert.strictEqual(1, 1, "uses === comparator");
assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT");
}
}
////////////////////////////////////////////////////
/// Events tests : http://nodejs.org/api/events.html
////////////////////////////////////////////////////
namespace events_tests {
let emitter: events.EventEmitter;
let event: string | symbol;
let listener: Function;
let any: any;
{
let result: events.EventEmitter;
result = emitter.addListener(event, listener);
result = emitter.on(event, listener);
result = emitter.once(event, listener);
result = emitter.prependListener(event, listener);
result = emitter.prependOnceListener(event, listener);
result = emitter.removeListener(event, listener);
result = emitter.removeAllListeners();
result = emitter.removeAllListeners(event);
result = emitter.setMaxListeners(42);
}
{
let result: number;
result = events.EventEmitter.defaultMaxListeners;
result = events.EventEmitter.listenerCount(emitter, event); // deprecated
result = emitter.getMaxListeners();
result = emitter.listenerCount(event);
}
{
let result: Function[];
result = emitter.listeners(event);
}
{
let result: boolean;
result = emitter.emit(event);
result = emitter.emit(event, any);
result = emitter.emit(event, any, any);
result = emitter.emit(event, any, any, any);
}
{
let result: (string | symbol)[];
result = emitter.eventNames();
}
{
class Networker extends events.EventEmitter {
constructor() {
super();
this.emit("mingling");
}
}
}
}
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
namespace fs_tests {
{
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.write(1234, "test");
fs.writeFile("Harry Potter",
"\"You be wizzing, Harry,\" jived Dumbledore.",
{
encoding: "ascii"
},
assert.ifError);
}
{
var content: string;
var buffer: Buffer;
content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', { encoding: 'utf8' });
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', { flag: 'r' });
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data);
}
{
var errno: string;
fs.readFile('testfile', (err, data) => {
if (err && err.errno) {
errno = err.errno;
}
});
}
{
fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
// Prints: /tmp/foo-itXde2
});
}
{
var tempDir: string;
tempDir = fs.mkdtempSync('/tmp/foo-');
}
{
fs.watch('/tmp/foo-', (event, filename) => {
console.log(event, filename);
});
fs.watch('/tmp/foo-', 'utf8', (event, filename) => {
console.log(event, filename);
});
fs.watch('/tmp/foo-', {
recursive: true,
persistent: true,
encoding: 'utf8'
}, (event, filename) => {
console.log(event, filename);
});
}
{
fs.access('/path/to/folder', (err) => { });
fs.access(Buffer.from(''), (err) => { });
fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { });
fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { });
fs.accessSync('/path/to/folder');
fs.accessSync(Buffer.from(''));
fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK);
fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK);
}
}
///////////////////////////////////////////////////////
/// Buffer tests : https://nodejs.org/api/buffer.html
///////////////////////////////////////////////////////
function bufferTests() {
var utf8Buffer = new Buffer('test');
var base64Buffer = new Buffer('', 'base64');
var octets: Uint8Array = null;
var octetBuffer = new Buffer(octets);
var sharedBuffer = new Buffer(octets.buffer);
var copiedBuffer = new Buffer(utf8Buffer);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.byteLength('xyz123'));
console.log(Buffer.byteLength('xyz123', 'ascii'));
var result1 = Buffer.concat([utf8Buffer, base64Buffer]);
var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999);
// Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64()
{
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
buf.swap16();
buf.swap32();
buf.swap64();
}
// Class Method: Buffer.from(array)
{
const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
}
// Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
{
const arr: Uint16Array = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
let buf: Buffer;
buf = Buffer.from(arr.buffer);
buf = Buffer.from(arr.buffer, 1);
buf = Buffer.from(arr.buffer, 0, 1);
}
// Class Method: Buffer.from(buffer)
{
const buf1: Buffer = Buffer.from('buffer');
const buf2: Buffer = Buffer.from(buf1);
}
// Class Method: Buffer.from(str[, encoding])
{
const buf1: Buffer = Buffer.from('this is a tést');
const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex');
}
// Test that TS 1.6 works with the 'as Buffer' annotation
// on isBuffer.
var a: Buffer | number;
a = new Buffer(10);
if (Buffer.isBuffer(a)) {
a.writeUInt8(3, 4);
}
// write* methods return offsets.
var b = new Buffer(16);
var result: number = b.writeUInt32LE(0, 0);
result = b.writeUInt16LE(0, 4);
result = b.writeUInt8(0, 6);
result = b.writeInt8(0, 7);
result = b.writeDoubleLE(0, 8);
// fill returns the input buffer.
b.fill('a').fill('b');
{
let buffer = new Buffer('123');
let index: number;
index = buffer.indexOf("23");
index = buffer.indexOf("23", 1);
index = buffer.indexOf("23", 1, "utf8");
index = buffer.indexOf(23);
index = buffer.indexOf(buffer);
}
{
let buffer = new Buffer('123');
let index: number;
index = buffer.lastIndexOf("23");
index = buffer.lastIndexOf("23", 1);
index = buffer.lastIndexOf("23", 1, "utf8");
index = buffer.lastIndexOf(23);
index = buffer.lastIndexOf(buffer);
}
{
let buffer = new Buffer('123');
let val: [number, number];
/* comment out for --target es5
for (let entry of buffer.entries()) {
val = entry;
}
*/
}
{
let buffer = new Buffer('123');
let includes: boolean;
includes = buffer.includes("23");
includes = buffer.includes("23", 1);
includes = buffer.includes("23", 1, "utf8");
includes = buffer.includes(23);
includes = buffer.includes(23, 1);
includes = buffer.includes(23, 1, "utf8");
includes = buffer.includes(buffer);
includes = buffer.includes(buffer, 1);
includes = buffer.includes(buffer, 1, "utf8");
}
{
let buffer = new Buffer('123');
let val: number;
/* comment out for --target es5
for (let key of buffer.keys()) {
val = key;
}
*/
}
{
let buffer = new Buffer('123');
let val: number;
/* comment out for --target es5
for (let value of buffer.values()) {
val = value;
}
*/
}
// Imported Buffer from buffer module works properly
{
let b = new ImportedBuffer('123');
b.writeUInt8(0, 6);
let sb = new ImportedSlowBuffer(43);
b.writeUInt8(0, 6);
}
// Buffer has Uint8Array's buffer field (an ArrayBuffer).
{
let buffer = new Buffer('123');
let octets = new Uint8Array(buffer.buffer);
}
}
////////////////////////////////////////////////////
/// Url tests : http://nodejs.org/api/url.html
////////////////////////////////////////////////////
namespace url_tests {
{
url.format(url.parse('http://www.example.com/xyz'));
// https://google.com/search?q=you're%20a%20lizard%2C%20gary
url.format({
protocol: 'https',
host: "google.com",
pathname: 'search',
query: { q: "you're a lizard, gary" }
});
}
{
var helloUrl = url.parse('http://example.com/?hello=world', true)
assert.equal(helloUrl.query.hello, 'world');
}
}
/////////////////////////////////////////////////////
/// util tests : https://nodejs.org/api/util.html ///
/////////////////////////////////////////////////////
namespace util_tests {
{
// Old and new util.inspect APIs
util.inspect(["This is nice"], false, 5);
util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false });
}
}
////////////////////////////////////////////////////
/// Stream tests : http://nodejs.org/api/stream.html
////////////////////////////////////////////////////
// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
function stream_readable_pipe_test() {
var r = fs.createReadStream('file.txt');
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
r.close();
}
// Simplified constructors
function simplified_stream_ctor_test() {
new stream.Readable({
read: function(size) {
size.toFixed();
}
});
new stream.Writable({
write: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb()
},
writev: function(chunks, cb) {
chunks[0].chunk.slice(0);
chunks[0].encoding.charAt(0);
cb();
}
});
new stream.Duplex({
read: function(size) {
size.toFixed();
},
write: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb()
},
writev: function(chunks, cb) {
chunks[0].chunk.slice(0);
chunks[0].encoding.charAt(0);
cb();
},
readableObjectMode: true,
writableObjectMode: true
});
new stream.Transform({
transform: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb();
},
flush: function(cb) {
cb()
},
read: function(size) {
size.toFixed();
},
write: function(chunk, enc, cb) {
chunk.slice(1);
enc.charAt(0);
cb()
},
writev: function(chunks, cb) {
chunks[0].chunk.slice(0);
chunks[0].encoding.charAt(0);
cb();
}
})
}
////////////////////////////////////////////////////////
/// Crypto tests : http://nodejs.org/api/crypto.html ///
////////////////////////////////////////////////////////
namespace crypto_tests {
{
var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex');
}
{
let hmac: crypto.Hmac;
(hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => {
let hash: Buffer | string = hmac.read();
});
}
{
//crypto_cipher_decipher_string_test
let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
let clearText: string = "This is the clear text.";
let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
let cipherText: string = cipher.update(clearText, "utf8", "hex");
cipherText += cipher.final("hex");
let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
let clearText2: string = decipher.update(cipherText, "hex", "utf8");
clearText2 += decipher.final("utf8");
assert.equal(clearText2, clearText);
}
{
//crypto_cipher_decipher_buffer_test
let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
let cipherBuffers: Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherBuffers.push(cipher.final());
let cipherText: Buffer = Buffer.concat(cipherBuffers);
let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key);
let decipherBuffers: Buffer[] = [];
decipherBuffers.push(decipher.update(cipherText));
decipherBuffers.push(decipher.final());
let clearText2: Buffer = Buffer.concat(decipherBuffers);
assert.deepEqual(clearText2, clearText);
}
{
let buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]);
let buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]);
let buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]);
assert(crypto.timingSafeEqual(buffer1, buffer2))
assert(!crypto.timingSafeEqual(buffer1, buffer3))
}
}
//////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html ///
//////////////////////////////////////////////////
namespace tls_tests {
{
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
var blah = ctx.context;
var connOpts: tls.ConnectionOptions = {
host: "127.0.0.1",
port: 55
};
var tlsSocket = tls.connect(connOpts);
}
{
let _server: tls.Server;
let _boolean: boolean;
let _func1 = function(err: Error, resp: Buffer){};
let _func2 = function(err: Error, sessionData: any){};
/**
* events.EventEmitter
* 1. tlsClientError
* 2. newSession
* 3. OCSPRequest
* 4. resumeSession
* 5. secureConnection
**/
_server = _server.addListener("tlsClientError", (err, tlsSocket) => {
let _err: Error = err;
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.addListener("newSession", (sessionId, sessionData, callback) => {
let _sessionId: any = sessionId;
let _sessionData: any = sessionData;
let _func1 = callback;
})
_server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => {
let _certificate: Buffer = certificate;
let _issuer: Buffer = issuer;
let _callback: Function = callback;
})
_server = _server.addListener("resumeSession", (sessionId, callback) => {
let _sessionId: any = sessionId;
let _func2 = callback;
})
_server = _server.addListener("secureConnection", (tlsSocket) => {
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
let _err: Error;
let _tlsSocket: tls.TLSSocket;
let _any: any;
let _func: Function;
let _buffer: Buffer;
_boolean = _server.emit("tlsClientError", _err, _tlsSocket);
_boolean = _server.emit("newSession", _any, _any, _func1);
_boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func);
_boolean = _server.emit("resumeSession", _any, _func2);
_boolean = _server.emit("secureConnection", _tlsSocket);
_server = _server.on("tlsClientError", (err, tlsSocket) => {
let _err: Error = err;
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.on("newSession", (sessionId, sessionData, callback) => {
let _sessionId: any = sessionId;
let _sessionData: any = sessionData;
let _func1 = callback;
})
_server = _server.on("OCSPRequest", (certificate, issuer, callback) => {
let _certificate: Buffer = certificate;
let _issuer: Buffer = issuer;
let _callback: Function = callback;
})
_server = _server.on("resumeSession", (sessionId, callback) => {
let _sessionId: any = sessionId;
let _func2 = callback;
})
_server = _server.on("secureConnection", (tlsSocket) => {
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.once("tlsClientError", (err, tlsSocket) => {
let _err: Error = err;
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.once("newSession", (sessionId, sessionData, callback) => {
let _sessionId: any = sessionId;
let _sessionData: any = sessionData;
let _func1 = callback;
})
_server = _server.once("OCSPRequest", (certificate, issuer, callback) => {
let _certificate: Buffer = certificate;
let _issuer: Buffer = issuer;
let _callback: Function = callback;
})
_server = _server.once("resumeSession", (sessionId, callback) => {
let _sessionId: any = sessionId;
let _func2 = callback;
})
_server = _server.once("secureConnection", (tlsSocket) => {
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.prependListener("tlsClientError", (err, tlsSocket) => {
let _err: Error = err;
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.prependListener("newSession", (sessionId, sessionData, callback) => {
let _sessionId: any = sessionId;
let _sessionData: any = sessionData;
let _func1 = callback;
})
_server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => {
let _certificate: Buffer = certificate;
let _issuer: Buffer = issuer;
let _callback: Function = callback;
})
_server = _server.prependListener("resumeSession", (sessionId, callback) => {
let _sessionId: any = sessionId;
let _func2 = callback;
})
_server = _server.prependListener("secureConnection", (tlsSocket) => {
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => {
let _err: Error = err;
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
_server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => {
let _sessionId: any = sessionId;
let _sessionData: any = sessionData;
let _func1 = callback;
})
_server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => {
let _certificate: Buffer = certificate;
let _issuer: Buffer = issuer;
let _callback: Function = callback;
})
_server = _server.prependOnceListener("resumeSession", (sessionId, callback) => {
let _sessionId: any = sessionId;
let _func2 = callback;
})
_server = _server.prependOnceListener("secureConnection", (tlsSocket) => {
let _tlsSocket: tls.TLSSocket = tlsSocket;
})
}
{
let _TLSSocket: tls.TLSSocket;
let _boolean: boolean;
/**
* events.EventEmitter
* 1. close
* 2. error
* 3. listening
* 4. message
**/
_TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => {
let _response: Buffer = response;
})
_TLSSocket = _TLSSocket.addListener("secureConnect", () => { });
let _buffer: Buffer;
_boolean = _TLSSocket.emit("OCSPResponse", _buffer);
_boolean = _TLSSocket.emit("secureConnect");
_TLSSocket = _TLSSocket.on("OCSPResponse", (response) => {
let _response: Buffer = response;
})
_TLSSocket = _TLSSocket.on("secureConnect", () => { });
_TLSSocket = _TLSSocket.once("OCSPResponse", (response) => {
let _response: Buffer = response;
})
_TLSSocket = _TLSSocket.once("secureConnect", () => { });
_TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => {
let _response: Buffer = response;
})
_TLSSocket = _TLSSocket.prependListener("secureConnect", () => { });
_TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => {
let _response: Buffer = response;
})
_TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { });
}
}
////////////////////////////////////////////////////
/// Http tests : http://nodejs.org/api/http.html ///
////////////////////////////////////////////////////
namespace http_tests {
{
// Status codes
var codeMessage = http.STATUS_CODES['400'];
var codeMessage = http.STATUS_CODES[400];
}
{
var agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256
});
var agent: http.Agent = http.globalAgent;
http.request({ agent: false });
http.request({ agent: agent });
http.request({ agent: undefined });
}
{
// Make sure .listen() and .close() retuern a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();
}
{
var request = http.request('http://0.0.0.0');
request.once('error', function() { });
request.setNoDelay(true);
request.abort();
}
}
//////////////////////////////////////////////////////
/// Https tests : http://nodejs.org/api/https.html ///
//////////////////////////////////////////////////////
namespace https_tests {
var agent: https.Agent = new https.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100
});
var agent: https.Agent = https.globalAgent;
https.request({
agent: false
});
https.request({
agent: agent
});
https.request({
agent: undefined
});
}
////////////////////////////////////////////////////
/// TTY tests : http://nodejs.org/api/tty.html
////////////////////////////////////////////////////
namespace tty_tests {
let rs: tty.ReadStream;
let ws: tty.WriteStream;
let rsIsRaw: boolean = rs.isRaw;
rs.setRawMode(true);
let wsColumns: number = ws.columns;
let wsRows: number = ws.rows;
let isTTY: boolean = tty.isatty(1);
}
////////////////////////////////////////////////////
/// Dgram tests : http://nodejs.org/api/dgram.html
////////////////////////////////////////////////////
namespace dgram_tests {
{
var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => {
});
ds.bind();
ds.bind(41234);
var ai: dgram.AddressInfo = ds.address();
ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => {
});
ds.send(new Buffer("hello"), 5000, "127.0.0.1");
}
{
let _socket: dgram.Socket;
let _boolean: boolean;
let _err: Error;
let _str: string;
let _rinfo: dgram.AddressInfo;
/**
* events.EventEmitter
* 1. close
* 2. error
* 3. listening
* 4. message
**/
_socket = _socket.addListener("close", () => {});
_socket = _socket.addListener("error", (err) => {
let _err: Error = err;
})
_socket = _socket.addListener("listening", () => {});
_socket = _socket.addListener("message", (msg, rinfo) => {
let _msg: string = msg;
let _rinfo: dgram.AddressInfo = rinfo;
})
_boolean = _socket.emit("close")
_boolean = _socket.emit("error", _err);
_boolean = _socket.emit("listening");
_boolean = _socket.emit("message", _str, _rinfo);
_socket = _socket.on("close", () => {});
_socket = _socket.on("error", (err) => {
let _err: Error = err;
})
_socket = _socket.on("listening", () => {});
_socket = _socket.on("message", (msg, rinfo) => {
let _msg: string = msg;
let _rinfo: dgram.AddressInfo = rinfo;
})
_socket = _socket.once("close", () => {});
_socket = _socket.once("error", (err) => {
let _err: Error = err;
})
_socket = _socket.once("listening", () => {});
_socket = _socket.once("message", (msg, rinfo) => {
let _msg: string = msg;
let _rinfo: dgram.AddressInfo = rinfo;
})
_socket = _socket.prependListener("close", () => {});
_socket = _socket.prependListener("error", (err) => {
let _err: Error = err;
})
_socket = _socket.prependListener("listening", () => {});
_socket = _socket.prependListener("message", (msg, rinfo) => {
let _msg: string = msg;
let _rinfo: dgram.AddressInfo = rinfo;
})
_socket = _socket.prependOnceListener("close", () => {});
_socket = _socket.prependOnceListener("error", (err) => {
let _err: Error = err;
})
_socket = _socket.prependOnceListener("listening", () => {});
_socket = _socket.prependOnceListener("message", (msg, rinfo) => {
let _msg: string = msg;
let _rinfo: dgram.AddressInfo = rinfo;
})
}
}
////////////////////////////////////////////////////
///Querystring tests : https://nodejs.org/api/querystring.html
////////////////////////////////////////////////////
namespace querystring_tests {
type SampleObject = { a: string; b: number; }
{
let obj: SampleObject;
let sep: string;
let eq: string;
let options: querystring.StringifyOptions;
let result: string;
result = querystring.stringify<SampleObject>(obj);
result = querystring.stringify<SampleObject>(obj, sep);
result = querystring.stringify<SampleObject>(obj, sep, eq);
result = querystring.stringify<SampleObject>(obj, sep, eq);
result = querystring.stringify<SampleObject>(obj, sep, eq, options);
}
{
let str: string;
let sep: string;
let eq: string;
let options: querystring.ParseOptions;
let result: SampleObject;
result = querystring.parse<SampleObject>(str);
result = querystring.parse<SampleObject>(str, sep);
result = querystring.parse<SampleObject>(str, sep, eq);
result = querystring.parse<SampleObject>(str, sep, eq, options);
}
{
let str: string;
let result: string;
result = querystring.escape(str);
result = querystring.unescape(str);
}
}
////////////////////////////////////////////////////
/// path tests : http://nodejs.org/api/path.html
////////////////////////////////////////////////////
namespace path_tests {
path.normalize('/foo/bar//baz/asdf/quux/..');
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// returns
//'/foo/bar/baz/asdf'
try {
path.join('foo', {}, 'bar');
}
catch (error) {
}
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile');
//Is similar to:
//
//cd foo/bar
//cd /tmp/file/
//cd ..
// cd a/../subfile
//pwd
path.resolve('/foo/bar', './baz')
// returns
// '/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// returns
// '/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
// '/home/myself/node/wwwroot/static_files/gif/image.gif'
path.isAbsolute('/foo/bar') // true
path.isAbsolute('/baz/..') // true
path.isAbsolute('qux/') // false
path.isAbsolute('.') // false
path.isAbsolute('//server') // true
path.isAbsolute('C:/foo/..') // true
path.isAbsolute('bar\\baz') // false
path.isAbsolute('.') // false
path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
// '..\\..\\impl\\bbb'
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
// '../../impl/bbb'
path.dirname('/foo/bar/baz/asdf/quux')
// returns
// '/foo/bar/baz/asdf'
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
// 'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
// 'quux'
path.extname('index.html')
// returns
// '.html'
path.extname('index.coffee.md')
// returns
// '.md'
path.extname('index.')
// returns
// '.'
path.extname('index')
// returns
// ''
'foo/bar/baz'.split(path.sep)
// returns
// ['foo', 'bar', 'baz']
'foo\\bar\\baz'.split(path.sep)
// returns
// ['foo', 'bar', 'baz']
console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
process.env.PATH.split(path.delimiter)
// returns
// ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
console.log(process.env.PATH)
// 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\'
process.env.PATH.split(path.delimiter)
// returns
// ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\']
path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }
path.parse('C:\\path\\dir\\index.html')
// returns
// {
// root : "C:\",
// dir : "C:\path\dir",
// base : "index.html",
// ext : ".html",
// name : "index"
// }
path.format({
root: "/",
dir: "/home/user/dir",
base: "file.txt",
ext: ".txt",
name: "file"
});
// returns
// '/home/user/dir/file.txt'
}
////////////////////////////////////////////////////
/// readline tests : https://nodejs.org/api/readline.html
////////////////////////////////////////////////////
namespace readline_tests {
let rl: readline.ReadLine;
{
let options: readline.ReadLineOptions;
let input: NodeJS.ReadableStream;
let output: NodeJS.WritableStream;
let completer: readline.Completer;
let terminal: boolean;
let result: readline.ReadLine;
result = readline.createInterface(options);
result = readline.createInterface(input);
result = readline.createInterface(input, output);
result = readline.createInterface(input, output, completer);
result = readline.createInterface(input, output, completer, terminal);
result = readline.createInterface({
input: input,
completer: function(str: string): readline.CompleterResult {
return [['test'], 'test'];
}
});
}
{
let prompt: string;
rl.setPrompt(prompt);
}
{
let preserveCursor: boolean;
rl.prompt();
rl.prompt(preserveCursor);
}
{
let query: string;
let callback: (answer: string) => void;
rl.question(query, callback);
}
{
let result: readline.ReadLine;
result = rl.pause();
}
{
let result: readline.ReadLine;
result = rl.resume();
}
{
rl.close();
}
{
let data: string | Buffer;
let key: readline.Key;
rl.write(data);
rl.write(null, key);
}
{
let stream: NodeJS.WritableStream;
let x: number;
let y: number;
readline.cursorTo(stream, x, y);
}
{
let stream: NodeJS.WritableStream;
let dx: number | string;
let dy: number | string;
readline.moveCursor(stream, dx, dy);
}
{
let stream: NodeJS.WritableStream;
let dir: number;
readline.clearLine(stream, dir);
}
{
let stream: NodeJS.WritableStream;
readline.clearScreenDown(stream);
}
}
////////////////////////////////////////////////////
/// string_decoder tests : https://nodejs.org/api/string_decoder.html
////////////////////////////////////////////////////
namespace string_decoder_tests {
const StringDecoder = string_decoder.StringDecoder;
const buffer = new Buffer('test');
const decoder1 = new StringDecoder();
const decoder2 = new StringDecoder('utf8');
const part1: string = decoder1.write(new Buffer('test'));
const end1: string = decoder1.end();
const part2: string = decoder2.write(new Buffer('test'));
const end2: string = decoder1.end(new Buffer('test'));
}
//////////////////////////////////////////////////////////////////////
/// Child Process tests: https://nodejs.org/api/child_process.html ///
//////////////////////////////////////////////////////////////////////
namespace child_process_tests {
{
childProcess.exec("echo test");
childProcess.spawnSync("echo test");
}
}
//////////////////////////////////////////////////////////////////////
/// cluster tests: https://nodejs.org/api/cluster.html ///
//////////////////////////////////////////////////////////////////////
namespace cluster_tests {
{
cluster.fork();
Object.keys(cluster.workers).forEach(key => {
const worker = cluster.workers[key];
if (worker.isDead()) {
console.log('worker %d is dead', worker.process.pid);
}
});
}
}
////////////////////////////////////////////////////
/// os tests : https://nodejs.org/api/os.html
////////////////////////////////////////////////////
namespace os_tests {
{
let result: string;
result = os.tmpdir();
result = os.homedir();
result = os.endianness();
result = os.hostname();
result = os.type();
result = os.platform();
result = os.arch();
result = os.release();
result = os.EOL;
}
{
let result: number;
result = os.uptime();
result = os.totalmem();
result = os.freemem();
}
{
let result: number[];
result = os.loadavg();
}
{
let result: os.CpuInfo[];
result = os.cpus();
}
{
let result: { [index: string]: os.NetworkInterfaceInfo[] };
result = os.networkInterfaces();
}
}
////////////////////////////////////////////////////
/// vm tests : https://nodejs.org/api/vm.html
////////////////////////////////////////////////////
namespace vm_tests {
{
const sandbox = {
animal: 'cat',
count: 2
};
const context = vm.createContext(sandbox);
console.log(vm.isContext(context));
const script = new vm.Script('count += 1; name = "kitty"');
for (let i = 0; i < 10; ++i) {
script.runInContext(context);
}
console.log(util.inspect(sandbox));
vm.runInNewContext('count += 1; name = "kitty"', sandbox);
console.log(util.inspect(sandbox));
}
{
const sandboxes = [{}, {}, {}];
const script = new vm.Script('globalVar = "set"');
sandboxes.forEach((sandbox) => {
script.runInNewContext(sandbox);
script.runInThisContext();
});
console.log(util.inspect(sandboxes));
var localVar = 'initial value';
vm.runInThisContext('localVar = "vm";');
console.log(localVar);
}
{
const Debug = vm.runInDebugContext('Debug');
Debug.scripts().forEach(function(script: any) { console.log(script.name); });
}
}
/////////////////////////////////////////////////////
/// Timers tests : https://nodejs.org/api/timers.html
/////////////////////////////////////////////////////
namespace timers_tests {
{
let immediateId = timers.setImmediate(function() { console.log("immediate"); });
timers.clearImmediate(immediateId);
}
{
let counter = 0;
let timeout = timers.setInterval(function() { console.log("interval"); }, 20);
timeout.unref();
timeout.ref();
timers.clearInterval(timeout);
}
{
let counter = 0;
let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20);
timeout.unref();
timeout.ref();
timers.clearTimeout(timeout);
}
}
/////////////////////////////////////////////////////////
/// Errors Tests : https://nodejs.org/api/errors.html ///
/////////////////////////////////////////////////////////
namespace errors_tests {
{
Error.stackTraceLimit = Infinity;
}
{
const myObject = {};
Error.captureStackTrace(myObject);
}
}
///////////////////////////////////////////////////////////
/// Process Tests : https://nodejs.org/api/process.html ///
///////////////////////////////////////////////////////////
import * as p from "process";
namespace process_tests {
{
var eventEmitter: events.EventEmitter;
eventEmitter = process; // Test that process implements EventEmitter...
var _p: NodeJS.Process = process;
_p = p;
}
}
///////////////////////////////////////////////////////////
/// Console Tests : https://nodejs.org/api/console.html ///
///////////////////////////////////////////////////////////
import * as c from "console";
namespace console_tests {
{
var _c: Console = console;
_c = c;
}
}
///////////////////////////////////////////////////
/// Net Tests : https://nodejs.org/api/net.html ///
///////////////////////////////////////////////////
namespace net_tests {
{
// Make sure .listen() and .close() retuern a Server instance
net.createServer().listen(0).close().address();
}
{
/**
* net.Socket - events.EventEmitter
* 1. close
* 2. connect
* 3. data
* 4. drain
* 5. end
* 6. error
* 7. lookup
* 8. timeout
*/
let _socket: net.Socket;
let bool: boolean;
let buffer: Buffer;
let error: Error;
let str: string;
let num: number;
/// addListener
_socket = _socket.addListener("close", had_error => {
bool = had_error;
})
_socket = _socket.addListener("connect", () => { })
_socket = _socket.addListener("data", data => {
buffer = data;
})
_socket = _socket.addListener("drain", () => { })
_socket = _socket.addListener("end", () => { })
_socket = _socket.addListener("error", err => {
error = err;
})
_socket = _socket.addListener("lookup", (err, address, family, host) => {
error = err;
if (typeof family === 'string') {
str = family;
} else if (typeof family === 'number') {
num = family;
}
str = host;
})
_socket = _socket.addListener("timeout", () => { })
/// emit
bool = _socket.emit("close", bool);
bool = _socket.emit("connect");
bool = _socket.emit("data", buffer);
bool = _socket.emit("drain");
bool = _socket.emit("end");
bool = _socket.emit("error", error);
bool = _socket.emit("lookup", error, str, str, str);
bool = _socket.emit("lookup", error, str, num, str);
bool = _socket.emit("timeout");
/// on
_socket = _socket.on("close", had_error => {
bool = had_error;
})
_socket = _socket.on("connect", () => { })
_socket = _socket.on("data", data => {
buffer = data;
})
_socket = _socket.on("drain", () => { })
_socket = _socket.on("end", () => { })
_socket = _socket.on("error", err => {
error = err;
})
_socket = _socket.on("lookup", (err, address, family, host) => {
error = err;
if (typeof family === 'string') {
str = family;
} else if (typeof family === 'number') {
num = family;
}
str = host;
})
_socket = _socket.on("timeout", () => { })
/// once
_socket = _socket.once("close", had_error => {
bool = had_error;
})
_socket = _socket.once("connect", () => { })
_socket = _socket.once("data", data => {
buffer = data;
})
_socket = _socket.once("drain", () => { })
_socket = _socket.once("end", () => { })
_socket = _socket.once("error", err => {
error = err;
})
_socket = _socket.once("lookup", (err, address, family, host) => {
error = err;
if (typeof family === 'string') {
str = family;
} else if (typeof family === 'number') {
num = family;
}
str = host;
})
_socket = _socket.once("timeout", () => { })
/// prependListener
_socket = _socket.prependListener("close", had_error => {
bool = had_error;
})
_socket = _socket.prependListener("connect", () => { })
_socket = _socket.prependListener("data", data => {
buffer = data;
})
_socket = _socket.prependListener("drain", () => { })
_socket = _socket.prependListener("end", () => { })
_socket = _socket.prependListener("error", err => {
error = err;
})
_socket = _socket.prependListener("lookup", (err, address, family, host) => {
error = err;
if (typeof family === 'string') {
str = family;
} else if (typeof family === 'number') {
num = family;
}
str = host;
})
_socket = _socket.prependListener("timeout", () => { })
/// prependOnceListener
_socket = _socket.prependOnceListener("close", had_error => {
bool = had_error;
})
_socket = _socket.prependOnceListener("connect", () => { })
_socket = _socket.prependOnceListener("data", data => {
buffer = data;
})
_socket = _socket.prependOnceListener("drain", () => { })
_socket = _socket.prependOnceListener("end", () => { })
_socket = _socket.prependOnceListener("error", err => {
error = err;
})
_socket = _socket.prependOnceListener("lookup", (err, address, family, host) => {
error = err;
if (typeof family === 'string') {
str = family;
} else if (typeof family === 'number') {
num = family;
}
str = host;
})
_socket = _socket.prependOnceListener("timeout", () => { })
}
{
/**
* net.Server - events.EventEmitter
* 1. close
* 2. connection
* 3. error
* 4. listening
*/
let _server: net.Server;
let _socket: net.Socket;
let bool: boolean;
let error: Error;
/// addListener
_server = _server.addListener("close", () => { })
_server = _server.addListener("connection", socket => {
_socket = socket
})
_server = _server.addListener("error", err => {
error = err;
})
_server = _server.addListener("listening", () => { })
/// emit
bool = _server.emit("close")
bool = _server.emit("connection", _socket)
bool = _server.emit("error", error)
bool = _server.emit("listening")
/// once
_server = _server.once("close", () => { })
_server = _server.once("connection", socket => {
_socket = socket
})
_server = _server.once("error", err => {
error = err;
})
_server = _server.once("listening", () => { })
/// prependListener
_server = _server.prependListener("close", () => { })
_server = _server.prependListener("connection", socket => {
_socket = socket
})
_server = _server.prependListener("error", err => {
error = err;
})
_server = _server.prependListener("listening", () => { })
/// prependOnceListener
_server = _server.prependOnceListener("close", () => { })
_server = _server.prependOnceListener("connection", socket => {
_socket = socket
})
_server = _server.prependOnceListener("error", err => {
error = err;
})
_server = _server.prependOnceListener("listening", () => { })
}
}
/*****************************************************************************
* *
* The following tests are the modules not mentioned in document but existed *
* *
*****************************************************************************/
///////////////////////////////////////////////////////////
/// Constants Tests ///
///////////////////////////////////////////////////////////
import * as constants from 'constants';
namespace constants_tests {
var str: string;
var num: number;
num = constants.SIGHUP
num = constants.SIGINT
num = constants.SIGQUIT
num = constants.SIGILL
num = constants.SIGTRAP
num = constants.SIGABRT
num = constants.SIGIOT
num = constants.SIGBUS
num = constants.SIGFPE
num = constants.SIGKILL
num = constants.SIGUSR1
num = constants.SIGSEGV
num = constants.SIGUSR2
num = constants.SIGPIPE
num = constants.SIGALRM
num = constants.SIGTERM
num = constants.SIGCHLD
num = constants.SIGSTKFLT
num = constants.SIGCONT
num = constants.SIGSTOP
num = constants.SIGTSTP
num = constants.SIGTTIN
num = constants.SIGTTOU
num = constants.SIGURG
num = constants.SIGXCPU
num = constants.SIGXFSZ
num = constants.SIGVTALRM
num = constants.SIGPROF
num = constants.SIGWINCH
num = constants.SIGIO
num = constants.SIGPOLL
num = constants.SIGPWR
num = constants.SIGSYS
num = constants.SIGUNUSED
num = constants.O_RDONLY
num = constants.O_WRONLY
num = constants.O_RDWR
num = constants.S_IFMT
num = constants.S_IFREG
num = constants.S_IFDIR
num = constants.S_IFCHR
num = constants.S_IFBLK
num = constants.S_IFIFO
num = constants.S_IFLNK
num = constants.S_IFSOCK
num = constants.O_CREAT
num = constants.O_EXCL
num = constants.O_NOCTTY
num = constants.O_TRUNC
num = constants.O_APPEND
num = constants.O_DIRECTORY
num = constants.O_NOATIME
num = constants.O_NOFOLLOW
num = constants.O_SYNC
num = constants.O_DIRECT
num = constants.O_NONBLOCK
num = constants.S_IRWXU
num = constants.S_IRUSR
num = constants.S_IWUSR
num = constants.S_IXUSR
num = constants.S_IRWXG
num = constants.S_IRGRP
num = constants.S_IWGRP
num = constants.S_IXGRP
num = constants.S_IRWXO
num = constants.S_IROTH
num = constants.S_IWOTH
num = constants.S_IXOTH
num = constants.F_OK
num = constants.R_OK
num = constants.W_OK
num = constants.X_OK
num = constants.SSL_OP_ALL
num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE
num = constants.SSL_OP_CISCO_ANYCONNECT
num = constants.SSL_OP_COOKIE_EXCHANGE
num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG
num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
num = constants.SSL_OP_EPHEMERAL_RSA
num = constants.SSL_OP_LEGACY_SERVER_CONNECT
num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG
num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING
num = constants.SSL_OP_NETSCAPE_CA_DN_BUG
num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG
num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
num = constants.SSL_OP_NO_COMPRESSION
num = constants.SSL_OP_NO_QUERY_MTU
num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
num = constants.SSL_OP_NO_SSLv2
num = constants.SSL_OP_NO_SSLv3
num = constants.SSL_OP_NO_TICKET
num = constants.SSL_OP_NO_TLSv1
num = constants.SSL_OP_NO_TLSv1_1
num = constants.SSL_OP_NO_TLSv1_2
num = constants.SSL_OP_PKCS1_CHECK_1
num = constants.SSL_OP_PKCS1_CHECK_2
num = constants.SSL_OP_SINGLE_DH_USE
num = constants.SSL_OP_SINGLE_ECDH_USE
num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG
num = constants.SSL_OP_TLS_D5_BUG
num = constants.SSL_OP_TLS_ROLLBACK_BUG
num = constants.ENGINE_METHOD_RSA
num = constants.ENGINE_METHOD_DSA
num = constants.ENGINE_METHOD_DH
num = constants.ENGINE_METHOD_RAND
num = constants.ENGINE_METHOD_ECDH
num = constants.ENGINE_METHOD_ECDSA
num = constants.ENGINE_METHOD_CIPHERS
num = constants.ENGINE_METHOD_DIGESTS
num = constants.ENGINE_METHOD_STORE
num = constants.ENGINE_METHOD_PKEY_METHS
num = constants.ENGINE_METHOD_PKEY_ASN1_METHS
num = constants.ENGINE_METHOD_ALL
num = constants.ENGINE_METHOD_NONE
num = constants.DH_CHECK_P_NOT_SAFE_PRIME
num = constants.DH_CHECK_P_NOT_PRIME
num = constants.DH_UNABLE_TO_CHECK_GENERATOR
num = constants.DH_NOT_SUITABLE_GENERATOR
num = constants.NPN_ENABLED
num = constants.ALPN_ENABLED
num = constants.RSA_PKCS1_PADDING
num = constants.RSA_SSLV23_PADDING
num = constants.RSA_NO_PADDING
num = constants.RSA_PKCS1_OAEP_PADDING
num = constants.RSA_X931_PADDING
num = constants.RSA_PKCS1_PSS_PADDING
num = constants.POINT_CONVERSION_COMPRESSED
num = constants.POINT_CONVERSION_UNCOMPRESSED
num = constants.POINT_CONVERSION_HYBRID
str = constants.defaultCoreCipherList
str = constants.defaultCipherList
}