Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Baris Cicek 2017-02-25 15:35:19 +03:00
commit fb6eeb04d5
952 changed files with 21733 additions and 19000 deletions

View File

@ -169,10 +169,8 @@ If a `tslint.json` turns rules off, this is because that hasn't been fixed yet.
(To indicate that a lint rule truly does not apply, use `// tslint:disable:rule-name` or better, `//tslint:disable-next-line:rule-name`.)
Only `.d.ts` files are linted.
Test the linter by running `npm run lint -- package-name`. Do not use a globally installed tslint.
## FAQ
#### What exactly is the relationship between this repository and the `@types` packages on NPM?

View File

@ -9,13 +9,13 @@ const restClient = new Ably.Rest(ApiKey);
// Connection
// Successful connection:
client.connection.on('connected', function() {
client.connection.on('connected', () => {
// successful connection
});
// Failed connection:
client.connection.on('failed', function() {
client.connection.on('failed', () => {
// failed connection
});
@ -23,14 +23,14 @@ client.connection.on('failed', function() {
// Subscribing to a channel
var channel = client.channels.get('test');
channel.subscribe(function(message) {
channel.subscribe(message => {
message.name; // 'greeting'
message.data; // 'Hello World!'
});
// Only certain events:
channel.subscribe('myEvent', function(message) {
channel.subscribe('myEvent', message => {
message.name; // 'myEvent'
message.data; // 'myData'
});
@ -41,30 +41,30 @@ channel.subscribe('myEvent', function(message) {
channel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
channel.publish('greeting', 'Hello World!', function(err) {
if(err) {
channel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
})
});
// Publish several messages at once
channel.publish([{name: 'greeting', data: 'Hello World!'}], function() { });
channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { });
// Querying the History
channel.history(function(err, messagesPage) {
channel.history((err, messagesPage) => {
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) { nextPage; }); // retrieves the next page as PaginatedResult
messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards'}, function(err, messagesPage) {
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => {
console.log(messagesPage.items.length);
});
@ -72,7 +72,7 @@ channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, directio
// Presence on a channel
// Getting presence:
channel.presence.get(function(presenceSet) {
channel.presence.get(presenceSet => {
presenceSet; // array of PresenceMessages
});
@ -80,46 +80,47 @@ channel.presence.get(function(presenceSet) {
// Entering (and leaving) the presence set:
channel.presence.enter('my status', function(err) {
channel.presence.enter('my status', err => {
// now I am entered
});
channel.presence.update('new status', function(err) {
channel.presence.update('new status', err => {
// my presence data is updated
});
channel.presence.leave(null, function(err) {
channel.presence.leave(null, err => {
// I've left the presence set
});
channel.presence.enterClient('myClientId', 'status', function(err) {
channel.presence.enterClient('myClientId', 'status', err => {
});
// and similiarly, updateClient and leaveClient
// Querying the Presence History
channel.presence.history(function(err, messagesPage) { // PaginatedResult
channel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) { }); // retrieves the next page as PaginatedResult
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {});
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Symmetrical end-to-end encrypted payloads on a channel
// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key. The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key.
// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
Ably.Realtime.Crypto.generateRandomKey(function(err, key) {
var channel = client.channels.get('channelName', { cipher: { key: key } });
Ably.Realtime.Crypto.generateRandomKey((err, key) => {
var channel = client.channels.get('channelName', { cipher: { key } });
channel.subscribe(function(message) {
channel.subscribe(message => {
message.name; // 'name is not encrypted'
message.data; // 'sensitive data is encrypted'
});
@ -129,7 +130,7 @@ Ably.Realtime.Crypto.generateRandomKey(function(err, key) {
// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
channel.setOptions({cipher: {key: '<KEY>'}}, function() {
channel.setOptions({cipher: {key: '<KEY>'}}, () => {
// New encryption settings are in effect
});
@ -143,56 +144,56 @@ var restChannel = restClient.channels.get('test');
restChannel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
restChannel.publish('greeting', 'Hello World!', function(err) {
if(err) {
restChannel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
})
});
// Publish several messages at once
restChannel.publish([{name: 'greeting', data: 'Hello World!'}], function() {});
restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {});
// Querying the History
restChannel.history(function(err, messagesPage) {
restChannel.history((err, messagesPage) => {
messagesPage; // PaginatedResult
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult
messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {});
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Presence on a channel
restChannel.presence.get(function(err, presencePage) { // PaginatedResult
restChannel.presence.get((err, presencePage) => { // PaginatedResult
presencePage.items; // array of PresenceMessage
presencePage.items[0].data; // payload for first message
presencePage.items.length; // number of messages in the current page of members
presencePage.hasNext(); // true if there are further pages
presencePage.isLast(); // true if this page is the last page
presencePage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult
presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Querying the Presence History
restChannel.presence.history(function(err, messagesPage) { // PaginatedResult
restChannel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) { }); // retrieves the next page as PaginatedResult
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {});
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Generate Token and Token Request
@ -200,7 +201,7 @@ restChannel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, dire
// Requesting a token:
client.auth.requestToken(function(err, tokenDetails) {
client.auth.requestToken((err, tokenDetails) => {
// tokenDetails is instance of TokenDetails
// see https://www.ably.io/documentation/rest/authentication/#token-details for its properties
@ -211,11 +212,11 @@ client.auth.requestToken(function(err, tokenDetails) {
// requestToken can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.requestToken({}, {}, function(err, tokenDetails) { });
client.auth.requestToken({}, {}, (err, tokenDetails) => { });
// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms):
client.auth.createTokenRequest(function(err, tokenRequest) {
client.auth.createTokenRequest((err, tokenRequest) => {
// now send the tokenRequest back to the client, which will
// use it to request a token and connect to Ably
});
@ -223,22 +224,22 @@ client.auth.createTokenRequest(function(err, tokenRequest) {
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.createTokenRequest({}, {}, function(err, tokenRequest) { });
client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { });
// Fetching your application's stats
client.stats({ limit: 50 }, function(err, statsPage) { // statsPage as PaginatedResult
client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult
statsPage.items; // array of Stats
statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
statsPage.items.length; // number of stats in the current page of history
statsPage.hasNext(); // true if there are further pages
statsPage.hasNext(); // true if there are wrther pages
statsPage.isLast(); // true if this page is the last page
statsPage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult
statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult
});
// Fetching the Ably service time
client.time({}, function(err, time) {}); // time is in ms since epoch
client.time({}, (err, time) => {}); // time is in ms since epoch
// Getting decoded Message objects from JSON
var messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);

6
ably/index.d.ts vendored
View File

@ -25,7 +25,8 @@ declare namespace ablyLib {
type CLOSED = "closed";
type FAILED = "failed";
}
type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED | ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED;
type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED |
ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED;
namespace ConnectionEvent {
type INITIALIZED = "initialized";
@ -38,7 +39,8 @@ declare namespace ablyLib {
type FAILED = "failed";
type UPDATE = "update";
}
type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED | ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE;
type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED |
ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE;
namespace PresenceAction {
type ABSENT = "absent";

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1,5 +1,5 @@
amplify.request({
resourceId: "statusExample1"
}).done(function (data, status) {
}).fail(function (data, status) {
}).always(function (data, status) { });
}).done((data, status) => {
}).fail((data, status) => {
}).always((data, status) => { });

View File

@ -3,4 +3,4 @@
"rules": {
"forbidden-types": false
}
}
}

View File

@ -7,7 +7,7 @@ import amplify = require("amplify");
// Subscribe and publish with no data
amplify.subscribe("nodataexample", function () {
amplify.subscribe("nodataexample", () => {
alert("nodataexample topic published!");
});
@ -15,24 +15,24 @@ amplify.subscribe("nodataexample", function () {
amplify.publish("nodataexample");
amplify.subscribe("dataexample", function (data) {
amplify.subscribe("dataexample", data => {
alert(data.foo); // bar
});
amplify.publish("dataexample", { foo: "bar" });
amplify.subscribe("dataexample2", function (param1, param2) {
amplify.subscribe("dataexample2", (param1, param2) => {
alert(param1 + param2); // barbaz
});
//...
// ...
amplify.publish("dataexample2", "bar", "baz");
// Subscribe and publish with context and data
amplify.subscribe("datacontextexample", $("p:first"), function (data) {
amplify.subscribe("datacontextexample", $("p:first"), data => {
this.text(data.exampleText); // first p element would have "foo bar baz" as text
});
@ -40,11 +40,11 @@ amplify.publish("datacontextexample", { exampleText: "foo bar baz" });
// Subscribe to a topic with high priority
amplify.subscribe("priorityexample", function (data) {
amplify.subscribe("priorityexample", data => {
alert(data.foo);
});
amplify.subscribe("priorityexample", function (data) {
amplify.subscribe("priorityexample", data => {
if (data.foo === "oops") {
return false;
}
@ -87,7 +87,7 @@ amplify.request.define("ajaxExample1", "ajax", {
});
// later in code
amplify.request("ajaxExample1", function (data) {
amplify.request("ajaxExample1", data => {
data.foo; // bar
});
@ -101,21 +101,21 @@ amplify.request.define("ajaxExample2", "ajax", {
});
// later in code
amplify.request("ajaxExample2", function (data) {
amplify.request("ajaxExample2", data => {
data.foo; // bar
});
// a second call will result in pulling from the cache
amplify.request("ajaxExample2", function (data) {
amplify.request("ajaxExample2", data => {
data.baz; // qux
})
});
// Set up and use a RESTful request utilizing Ajax
amplify.request.define("ajaxRESTFulExample", "ajax", {
url: "/myRestFulApi/{type}/{id}",
type: "GET"
})
});
// later in code
amplify.request("ajaxRESTFulExample",
@ -123,7 +123,7 @@ amplify.request("ajaxRESTFulExample",
type: "foo",
id: "bar"
},
function (data) {
data => {
// /myRESTFulApi/foo/bar was the URL used
data.foo; // bar
}
@ -132,9 +132,9 @@ amplify.request("ajaxRESTFulExample",
// POST data with Ajax
amplify.request.define("ajaxPostExample", "ajax", {
url: "/myRestFulApi",
type: "POST"
})
url: "/myRestFulApi",
type: "POST"
});
// later in code
amplify.request("ajaxPostExample",
@ -142,7 +142,7 @@ amplify.request("ajaxPostExample",
type: "foo",
id: "bar"
},
function (data) {
data => {
data.foo; // bar
}
);
@ -165,7 +165,7 @@ amplify.request("twitter-search", { term: "amplifyjs" } );
amplify.request.define("twitter-mentions", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: function (data) {
dataMap: data => {
return {
q: "@" + data.user
};
@ -176,9 +176,9 @@ amplify.request("twitter-mentions", { user: "amplifyjs" });
// Setting up and using decoders
//Example:
// Example:
var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success, error) {
var appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
@ -188,7 +188,7 @@ var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success,
}
};
//a new decoder can be added to the amplifyDecoders interface
// a new decoder can be added to the amplifyDecoders interface
declare module "amplify" {
interface Decoders {
appEnvelope: amplify.Decoder;
@ -197,7 +197,7 @@ declare module "amplify" {
amplify.request.decoders.appEnvelope = appEnvelopeDecoder;
//but you can also just add it via an index
// but you can also just add it via an index
amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder;
@ -209,10 +209,10 @@ amplify.request.define("decoderExample", "ajax", {
amplify.request({
resourceId: "decoderExample",
success: function (data) {
success(data) {
data.foo; // bar
},
error: function (message, level) {
error(message, level) {
alert("always handle errors with alerts.");
}
});
@ -224,7 +224,7 @@ amplify.request({
amplify.request.define("decoderSingleExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: function (data, status, xhr, success, error) {
decoder(data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
@ -237,10 +237,10 @@ amplify.request.define("decoderSingleExample", "ajax", {
amplify.request({
resourceId: "decoderSingleExample",
success: function (data) {
success: data => {
data.foo; // bar
},
error: function (message, level) {
error: (message, level) => {
alert("always handle errors with alerts.");
}
});
@ -250,14 +250,14 @@ amplify.request({
// amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition.
amplify.request.define("statusExample1", "ajax", {
//...
// ...
});
amplify.request({
resourceId: "statusExample1",
success: function (data, status) {
success: (data, status) => {
},
error: function (data, status) {
error: (data, status) => {
}
});

4
amplify/index.d.ts vendored
View File

@ -162,7 +162,9 @@ declare namespace amplify {
* Publish a message.
* topic: The name of the message to publish.
* Any additional parameters will be passed to the subscriptions.
* amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked.
* amplify.publish returns a boolean indicating whether any subscriptions returned false.
* The return value is true if none of the subscriptions returned false, and false otherwise.
* Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked.
*/
publish(topic: string, ...args: any[]): boolean;

View File

@ -4,4 +4,4 @@
"forbidden-types": false,
"unified-signatures": false
}
}
}

View File

@ -31,11 +31,11 @@ var anqpAssertExchangeReplies: amqp.Replies.AssertExchange;
import amqpcb = require('amqplib/callback_api');
amqpcb.connect('amqp://localhost', (err, connection) => {
if(!err) {
if (!err) {
connection.createChannel((err, channel) => {
if (!err) {
channel.assertQueue('myQueue', {}, (err, ok) => {
if(!err) {
if (!err) {
channel.sendToQueue('myQueue', new Buffer(msg));
}
});
@ -45,11 +45,11 @@ amqpcb.connect('amqp://localhost', (err, connection) => {
});
amqpcb.connect('amqp://localhost', (err, connection) => {
if(!err) {
if (!err) {
connection.createChannel((err, channel) => {
if (!err) {
channel.assertQueue('myQueue', {}, (err, ok) => {
if(!err) {
if (!err) {
channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString()));
}
});

View File

@ -3,4 +3,4 @@
"rules": {
"no-empty-interface": false
}
}
}

View File

@ -21,7 +21,7 @@ myApp.run(["gridsterConfig", (gridsterConfig: angular.gridster.GridsterConfig) =
gridsterConfig.floating = true;
gridsterConfig.swapping = true;
gridsterConfig.draggable = { enabled: true};
gridsterConfig.resizable = { enabled: true,
gridsterConfig.resizable = { enabled: true,
handles: ["n", "s", "e", "w", "ne", "se", "sw", "nw"]};
}
]);

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -143,7 +143,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
private $state: ng.ui.IStateService
) {
$rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event));
$rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) =>
$rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) =>
this.onStateNotFound(event, unfoundState, fromState, fromParams));
}
@ -157,8 +157,8 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
// Note that we do not concern ourselves with what to do if this request fails,
// because if it fails, the web page will be redirected away to the login screen.
this.$http({ url: "/api/me", method: "GET" }).success((user: any) => {
this.currentUser = user;
this.$http({ url: "/api/me", method: "GET" }).then((response: ng.IHttpPromiseCallbackArg<any>) => {
this.currentUser = response.data;
// sync the ui-state with the location in the browser, which effectively
// restarts the state change that was stopped previously
@ -166,14 +166,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
});
}
}
private onStateNotFound(event: ng.IAngularEvent,
unfoundState: ng.ui.IUnfoundState,
fromState: ng.ui.IState,
fromParams: {}) {
var unfoundTo: string = unfoundState.to;
var unfoundToParams: {} = unfoundState.toParams;
var unfoundOptions: ng.ui.IStateOptions = unfoundState.options
var unfoundOptions: ng.ui.IStateOptions = unfoundState.options
}
private stateServiceTest() {

View File

@ -2,6 +2,7 @@
// Project: https://github.com/mgonto/angular-wizard
// Definitions by: Marko Jurisic <https://github.com/mjurisic>, Ronald Wildenberg <https://github.com/rwwilden>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import * as angular from 'angular';

View File

@ -19,19 +19,19 @@ class AuthService {
* Required by HTTP interceptor.
* Function is attached to provider to be invisible for regular users of this service.
*/
pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
pushToBuffer = (config: ng.IRequestConfig, deferred: ng.IDeferred<any>) => {
this.buffer.push({
config,
deferred
});
};
}
$get = [
'$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
let $http: ng.IHttpService; //initialized later because of circular dependency problem
'$rootScope', '$injector', ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) => {
let $http: ng.IHttpService; // initialized later because of circular dependency problem
function retry(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
$http = $http || $injector.get<ng.IHttpService>('$http');
$http(config).then(function(response) {
$http(config).then(response => {
deferred.resolve(response);
});
}
@ -49,7 +49,7 @@ class AuthService {
retryAll();
}
};
} as any
}
];
}
@ -61,13 +61,13 @@ angular.module('http-auth-interceptor', [])
* $http interceptor.
* On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
*/
.config(['$httpProvider', 'authServiceProvider', function($httpProvider: ng.IHttpProvider, authServiceProvider: any) {
.config(['$httpProvider', 'authServiceProvider', ($httpProvider: ng.IHttpProvider, authServiceProvider: any) => {
$httpProvider.defaults.headers.common = {Authorization: 'Bearer token'};
$httpProvider.defaults.headers.get['Authorization'] = 'Bearer token';
$httpProvider.defaults.headers.post['Authorization'] = function(config: ng.IRequestConfig): string { return 'Bearer token'; };
$httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => 'Bearer token';
const interceptor = ['$rootScope', '$q', function($rootScope: ng.IScope, $q: ng.IQService) {
const interceptor = ['$rootScope', '$q', ($rootScope: ng.IScope, $q: ng.IQService) => {
function success(response: ng.IHttpPromiseCallbackArg<any>) {
return response;
}
@ -83,13 +83,10 @@ angular.module('http-auth-interceptor', [])
return $q.reject(response);
}
return function(promise: ng.IHttpPromise<any>) {
return promise.then(success, error);
};
} as any];
return (promise: ng.IHttpPromise<any>) => promise.then(success, error);
}];
$httpProvider.interceptors.push(interceptor);
} as any]);
}]);
namespace HttpAndRegularPromiseTests {
interface Person {
@ -108,11 +105,6 @@ namespace HttpAndRegularPromiseTests {
}
function someController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) {
$http.get<ExpectedResponse>('http://somewhere/some/resource')
.success((data: ExpectedResponse) => {
$scope.person = data;
});
$http.get<ExpectedResponse>('http://somewhere/some/resource')
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
@ -156,21 +148,6 @@ namespace HttpAndRegularPromiseTests {
$scope.nothing = 'really nothing';
});
}
// Test that we can pass around a type-checked success/error Promise Callback
function anotherController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) {
function buildFooData(): ng.IRequestShortcutConfig {
return {};
}
function doFoo(callback: ng.IHttpPromiseCallback<ExpectedResponse>) {
$http
.get<ExpectedResponse>('/foo', buildFooData())
.success(callback);
};
doFoo((data: any) => console.log(data));
};
}
// Test for AngularJS Syntax
@ -181,8 +158,8 @@ namespace My.Namespace {
// IModule Registering Test
let mod = angular.module('tests', []);
mod.controller('name', function($scope: ng.IScope) { });
mod.controller('name', ['$scope', function($scope: ng.IScope) { }]);
mod.controller('name', ($scope: ng.IScope) => { });
mod.controller('name', ['$scope', ($scope: ng.IScope) => { }]);
mod.controller('name', class {
// Uncommenting the next line should lead to a type error because this signature isn't compatible
// with the signature of the `$onChanges` hook:
@ -190,8 +167,8 @@ mod.controller('name', class {
});
mod.controller({
MyCtrl: class{},
MyCtrl2: function() {}, // tslint:disable-line:object-literal-shorthand
MyCtrl3: ['$fooService', function($fooService: any) { }]
MyCtrl2() {},
MyCtrl3: ['$fooService', ($fooService: any) => { }]
});
mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => {
return (scope, el, attrs) => {
@ -203,7 +180,7 @@ mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => {
scope.$watch(() => foo, () => el.text(foo));
};
});
mod.directive('myDirectiveB', ['$rootScope', function($rootScope: ng.IRootScopeService) {
mod.directive('myDirectiveB', ['$rootScope', ($rootScope: ng.IRootScopeService) => {
return {
link(scope, el, attrs) {
el.click(e => {
@ -220,28 +197,28 @@ mod.directive({
template: 'my-bar-dir.tpl.html'
})]
});
mod.factory('name', function($scope: ng.IScope) { });
mod.factory('name', ['$scope', function($scope: ng.IScope) { }]);
mod.factory('name', ($scope: ng.IScope) => {});
mod.factory('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.factory({
name1: function(foo: any) { }, // tslint:disable-line:object-literal-shorthand
name2: ['foo', function(foo: any) { }]
name1(foo: any) {},
name2: ['foo', (foo: any) => {}]
});
mod.filter('name', function($scope: ng.IScope) { });
mod.filter('name', ['$scope', function($scope: ng.IScope) { }]);
mod.filter('name', ($scope: ng.IScope) => {});
mod.filter('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.filter({
name1: function(foo: any) { }, // tslint:disable-line:object-literal-shorthand
name2: ['foo', function(foo: any) { }]
name1(foo: any) {},
name2: ['foo', (foo: any) => {}]
});
mod.provider('name', function($scope: ng.IScope) { return { $get: () => { } }; });
mod.provider('name', ($scope: ng.IScope) => ({ $get: () => { } }));
mod.provider('name', TestProvider);
mod.provider('name', ['$scope', function($scope: ng.IScope) { } as any]);
mod.provider('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.provider(My.Namespace);
mod.service('name', function($scope: ng.IScope) { });
mod.service('name', ['$scope', function($scope: ng.IScope) { } as any]);
mod.service('name', ($scope: ng.IScope) => {});
mod.service('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.service({
MyCtrl: class{},
MyCtrl2: function() {}, // tslint:disable-line:object-literal-shorthand
MyCtrl3: ['$fooService', function($fooService: any) { }]
MyCtrl2: () => {}, // tslint:disable-line:object-literal-shorthand
MyCtrl3: ['$fooService', ($fooService: any) => {}]
});
mod.constant('name', 23);
mod.constant('name', '23');
@ -249,8 +226,8 @@ mod.constant(My.Namespace);
mod.value('name', 23);
mod.value('name', '23');
mod.value(My.Namespace);
mod.decorator('name', function($scope: ng.IScope) {});
mod.decorator('name', ['$scope', function($scope: ng.IScope) {} as any]);
mod.decorator('name', ($scope: ng.IScope) => {});
mod.decorator('name', ['$scope', ($scope: ng.IScope) => {}]);
class TestProvider implements ng.IServiceProvider {
constructor(private $scope: ng.IScope) {
@ -262,7 +239,7 @@ class TestProvider implements ng.IServiceProvider {
// QProvider tests
angular.module('qprovider-test', [])
.config(['$qProvider', function($qProvider: ng.IQProvider) {
.config(['$qProvider', ($qProvider: ng.IQProvider) => {
const provider: ng.IQProvider = $qProvider.errorOnUnhandledRejections(false);
const currentValue: boolean = $qProvider.errorOnUnhandledRejections();
}]);
@ -298,7 +275,7 @@ foo.then((x) => {
}).then((x) => {
// Object is inferred here
x.a = 123;
//Try a promise
// Try a promise
var y: ng.IPromise<number>;
var condition: boolean;
return condition ? y : x.a; // IPromise<T> | T, both are good for the 1st arg of .then()
@ -441,10 +418,10 @@ httpFoo.then((x) => {
x.toFixed();
});
httpFoo.success((data, status, headers, config) => {
const h = headers('test');
httpFoo.then((response: ng.IHttpPromiseCallbackArg<any>) => {
const h = response.headers('test');
h.charAt(0);
const hs = headers();
const hs = response.headers();
hs['content-type'].charAt(1);
});
@ -557,7 +534,6 @@ namespace TestPromise {
(reason) => anyOf3(reject, tresult, tresultPromise)
));
assertPromiseType<ng.IHttpPromiseCallbackArg<TResult>>(promise.then((result) => tresultHttpPromise));
assertPromiseType<TResult | TOther>(promise.then((result) => result, (any) => tother));
@ -611,10 +587,10 @@ namespace TestPromise {
function test_angular_forEach() {
const values: { [key: string]: string } = { name: 'misko', gender: 'male' };
const log: string[] = [];
angular.forEach(values, function(value, key) {
angular.forEach(values, (value, key) => {
this.push(key + ': ' + value);
}, log);
//expect(log).toEqual(['name: misko', 'gender: male']);
// expect(log).toEqual(['name: misko', 'gender: male']);
}
// angular.element() tests
@ -729,19 +705,12 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo
const defer = $q.defer();
defer.reject();
defer.resolve();
defer.promise.then(function(d) {
return d;
}).then(function(): any {
return null;
}, function(): any {
return null;
})
.catch((): any => {
return null;
})
.finally((): any => {
return null;
});
defer.promise.then(d => d)
.then(
(): any => null,
(): any => null)
.catch((): any => null)
.finally((): any => null);
let promise = new $q((resolve) => {
resolve();
});
@ -761,39 +730,39 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo
// test from https://docs.angularjs.org/guide/directive
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
.directive('myCustomer', () => {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
.directive('myCustomer', () => {
return {
templateUrl: 'my-customer.html'
};
});
angular.module('docsRestrictDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
.directive('myCustomer', () => {
return {
restrict: 'E',
templateUrl: 'my-customer.html'
@ -801,19 +770,19 @@ angular.module('docsRestrictDirective', [])
});
angular.module('docsScopeProblemExample', [])
.controller('NaomiController', ['$scope', function($scope: any) {
.controller('NaomiController', ['$scope', ($scope: any) => {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.controller('IgorController', ['$scope', function($scope: any) {
.controller('IgorController', ['$scope', ($scope: any) => {
$scope.customer = {
name: 'Igor',
address: '123 Somewhere'
};
}])
.directive('myCustomer', function() {
.directive('myCustomer', () => {
return {
restrict: 'E',
templateUrl: 'my-customer.html'
@ -821,11 +790,11 @@ angular.module('docsScopeProblemExample', [])
});
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
.directive('myCustomer', () => {
return {
restrict: 'E',
scope: {
@ -836,11 +805,11 @@ angular.module('docsIsolateScopeDirective', [])
});
angular.module('docsIsolationExample', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
}])
.directive('myCustomer', function() {
.directive('myCustomer', () => {
return {
restrict: 'E',
scope: {
@ -851,10 +820,10 @@ angular.module('docsIsolationExample', [])
});
angular.module('docsTimeDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.format = 'M/d/yy h:mm:ss a';
}])
.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) {
.directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => {
return {
link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
@ -865,17 +834,17 @@ angular.module('docsTimeDirective', [])
element.text(dateFilter(new Date(), format));
}
scope.$watch(attrs['myCurrentTime'], function(value: any) {
scope.$watch(attrs['myCurrentTime'], (value: any) => {
format = value;
updateTime();
});
element.on('$destroy', function() {
element.on('$destroy', () => {
$interval.cancel(timeoutId);
});
// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function() {
timeoutId = $interval(() => {
updateTime(); // update DOM
}, 1000);
}
@ -883,10 +852,10 @@ angular.module('docsTimeDirective', [])
}]);
angular.module('docsTransclusionDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.name = 'Tobias';
}])
.directive('myDialog', function() {
.directive('myDialog', () => {
return {
restrict: 'E',
transclude: true,
@ -895,10 +864,10 @@ angular.module('docsTransclusionDirective', [])
});
angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', function($scope: any) {
.controller('Controller', ['$scope', ($scope: any) => {
$scope.name = 'Tobias';
}])
.directive('myDialog', function() {
.directive('myDialog', () => {
return {
restrict: 'E',
transclude: true,
@ -911,16 +880,16 @@ angular.module('docsTransclusionExample', [])
});
angular.module('docsIsoFnBindExample', [])
.controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) {
.controller('Controller', ['$scope', '$timeout', ($scope: any, $timeout: any) => {
$scope.name = 'Tobias';
$scope.hideDialog = function() {
$scope.hideDialog = () => {
$scope.dialogIsHidden = true;
$timeout(function() {
$timeout(() => {
$scope.dialogIsHidden = false;
}, 2000);
};
}])
.directive('myDialog', function() {
.directive('myDialog', () => {
return {
restrict: 'E',
transclude: true,
@ -932,8 +901,8 @@ angular.module('docsIsoFnBindExample', [])
});
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document: any) {
return function(scope: any, element: any, attr: any) {
.directive('myDraggable', ['$document', ($document: any) => {
return (scope: any, element: any, attr: any) => {
let startX = 0, startY = 0, x = 0, y = 0;
element.css({
@ -943,7 +912,7 @@ angular.module('dragModule', [])
cursor: 'pointer'
});
element.on('mousedown', function(event: any) {
element.on('mousedown', (event: any) => {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
@ -969,7 +938,7 @@ angular.module('dragModule', [])
}]);
angular.module('docsTabsExample', [])
.directive('myTabs', function() {
.directive('myTabs', () => {
return {
restrict: 'E',
transclude: true,
@ -977,14 +946,14 @@ angular.module('docsTabsExample', [])
controller($scope: ng.IScope) {
const panes: any = $scope['panes'] = [];
$scope['select'] = function(pane: any) {
angular.forEach(panes, function(pane: any) {
$scope['select'] = (pane: any) => {
angular.forEach(panes, (pane: any) => {
pane.selected = false;
});
pane.selected = true;
};
this.addPane = function(pane: any) {
this.addPane = (pane: any) => {
if (panes.length === 0) {
$scope['select'](pane);
}
@ -994,7 +963,7 @@ angular.module('docsTabsExample', [])
templateUrl: 'my-tabs.html'
};
})
.directive('myPane', function() {
.directive('myPane', () => {
return {
require: '^myTabs',
restrict: 'E',
@ -1010,7 +979,7 @@ angular.module('docsTabsExample', [])
});
angular.module('multiSlotTranscludeExample', [])
.directive('dropDownMenu', function() {
.directive('dropDownMenu', () => {
return {
transclude: {
button: 'button',
@ -1068,15 +1037,15 @@ interface ICopyExampleScope {
}
angular.module('copyExample', [])
.controller('ExampleController', ['$scope', function($scope: ICopyExampleScope) {
.controller('ExampleController', ['$scope', ($scope: ICopyExampleScope) => {
$scope.master = { };
$scope.update = function(user) {
$scope.update = user => {
// Example with 1 argument
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.reset = () => {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
@ -1149,7 +1118,7 @@ function NgModelControllerTyping() {
var $q: angular.IQService;
// See https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$validators
ngModel.$validators['validCharacters'] = function(modelValue, viewValue) {
ngModel.$validators['validCharacters'] = (modelValue, viewValue) => {
const value = modelValue || viewValue;
return /[0-9]+/.test(value) &&
/[a-z]+/.test(value) &&
@ -1157,7 +1126,7 @@ function NgModelControllerTyping() {
/\W+/.test(value);
};
ngModel.$asyncValidators['uniqueUsername'] = function(modelValue, viewValue) {
ngModel.$asyncValidators['uniqueUsername'] = (modelValue, viewValue) => {
const value = modelValue || viewValue;
return $http.get('/api/users/' + value).
then(function resolved() {
@ -1271,8 +1240,8 @@ function parseWithParams() {
function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService {
if (mode === 'debug') {
return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) {
$provide.decorator('$rootScope', function($delegate: ng.IRootScopeService) {
return angular.bootstrap(element, ['main', ($provide: ng.auto.IProvideService) => {
$provide.decorator('$rootScope', ($delegate: ng.IRootScopeService) => {
$delegate['debug'] = true;
});
}, 'debug-helpers'], {
@ -1292,12 +1261,12 @@ function testIHttpParamSerializerJQLikeProvider() {
}
function anyOf2<T1, T2>(v1: T1, v2: T2) {
return Math.random() < 1/2 ? v1 : v2;
return Math.random() < 0.5 ? v1 : v2;
}
function anyOf3<T1, T2, T3>(v1: T1, v2: T2, v3: T3) {
const rnd = Math.random();
return rnd < 1/3 ? v1 : rnd < 2/3 ? v2 : v3;
return rnd < 0.33 ? v1 : rnd < 0.66 ? v2 : v3;
}
function toPromise<T>(val: T): ng.IPromise<T> {

20
angular/index.d.ts vendored
View File

@ -411,8 +411,8 @@ declare namespace angular {
$invalid: boolean;
}
//Allows tuning how model updates are done.
//https://docs.angularjs.org/api/ng/directive/ngModelOptions
// Allows tuning how model updates are done.
// https://docs.angularjs.org/api/ng/directive/ngModelOptions
interface INgModelOptions {
updateOn?: string;
debounce?: any;
@ -1192,7 +1192,7 @@ declare namespace angular {
*/
size: number;
//...: any additional properties from the options object when creating the cache.
// ...: any additional properties from the options object when creating the cache.
};
/**
@ -1505,18 +1505,6 @@ declare namespace angular {
}
interface IHttpPromise<T> extends IPromise<IHttpPromiseCallbackArg<T>> {
/**
* The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
* If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
* @deprecated
*/
success?(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
/**
* The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
* If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
* @deprecated
*/
error?(callback: IHttpPromiseCallback<any>): IHttpPromise<T>;
}
// See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228
@ -2047,7 +2035,7 @@ declare namespace angular {
declare global {
interface JQuery {
// TODO: events, how to define?
//$destroy
// $destroy
find(element: any): JQuery;
find(obj: JQuery): JQuery;

View File

@ -1,20 +1,33 @@
{
"extends": "../tslint.json",
"rules": {
"class-name": true,
"curly": true,
"no-consecutive-blank-lines": true,
"no-shadowed-variable": true,
"quotemark": [true, "single"],
"align": true,
"callable-types": false,
"forbidden-types": false,
"indent": [true, "spaces"],
"interface-name": false,
"linebreak-style": [true, "LF"],
"no-empty-interface": false,
"unified-signatures": false,
"variable-name": [true, "check-format"],
"void-return": false
}
"extends": "../tslint.json",
"rules": {
"class-name": true,
"curly": true,
"max-line-length": false,
"no-consecutive-blank-lines": true,
"no-shadowed-variable": true,
"quotemark": [
true,
"single"
],
"align": true,
"callable-types": false,
"forbidden-types": false,
"indent": [
true,
"spaces"
],
"interface-name": false,
"linebreak-style": [
true,
"LF"
],
"no-empty-interface": false,
"unified-signatures": false,
"variable-name": [
true,
"check-format"
],
"void-return": false
}
}

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -135,7 +135,8 @@ export type esriGeometryType = "esriGeometryPoint" | "esriGeometryMultipoint" |
export type Color = [number, number, number, number];
export type SimpleMarkerSymbolStyle = "esriSMSCircle" | "esriSMSCross" | "esriSMSDiamond" | "esriSMSSquare" | "esriSMSX" | "esriSMSTriangle";
export type SimpleLineSymbolStyle = "esriSLSDash" | "esriSLSDashDot" | "esriSLSDashDotDot" | "esriSLSDot" | "esriSLSNull" | "esriSLSSolid";
export type SimpleFillSymbolStyle = "esriSFSBackwardDiagonal" | "esriSFSCross" | "esriSFSDiagonalCross" | "esriSFSForwardDiagonal" | "esriSFSHorizontal" | "esriSFSNull" | "esriSFSSolid" | "esriSFSVertical";
export type SimpleFillSymbolStyle =
"esriSFSBackwardDiagonal" | "esriSFSCross" | "esriSFSDiagonalCross" | "esriSFSForwardDiagonal" | "esriSFSHorizontal" | "esriSFSNull" | "esriSFSSolid" | "esriSFSVertical";
export type SymbolType = "esriSLS" | "esriSMS" | "esriSFS" | "esriPMS" | "esriPFS" | "esriTS";
export interface Symbol {
@ -168,12 +169,12 @@ export interface SimpleFillSymbol extends Symbol {
"type": "esriSFS";
"style"?: SimpleFillSymbolStyle;
"color"?: Color;
"outline"?: SimpleLineSymbol; //if outline has been specified
"outline"?: SimpleLineSymbol; // if outline has been specified
}
export interface PictureSourced {
"url"?: string; //Relative URL for static layers and full URL for dynamic layers. Access relative URL using http://<mapservice-url>/<layerId1>/images/<imageUrl11>
"imageData"?: string; //"<base64EncodedImageData>";
"url"?: string; // Relative URL for static layers and full URL for dynamic layers. Access relative URL using http://<mapservice-url>/<layerId1>/images/<imageUrl11>
"imageData"?: string; // "<base64EncodedImageData>";
"contentType"?: string;
"width"?: number;
"height"?: number;
@ -189,14 +190,14 @@ export interface PictureMarkerSymbol extends MarkerSymbol, PictureSourced {
export interface PictureFillSymbol extends Symbol, PictureSourced {
"type": "esriPFS";
"outline"?: SimpleLineSymbol; //if outline has been specified
"outline"?: SimpleLineSymbol; // if outline has been specified
"xscale"?: number;
"yscale"?: number;
}
export interface Font {
"family"?: string; //"<fontFamily>";
"size"?: number; //<fontSize>;
"family"?: string; // "<fontFamily>";
"size"?: number; // <fontSize>;
"style"?: "italic" | "normal" | "oblique";
"weight"?: "bold" | "bolder" | "lighter" | "normal";
"decoration"?: "line-through" | "underline" | "none";
@ -215,5 +216,5 @@ export interface TextSymbol extends MarkerSymbol {
"rightToLeft"?: boolean;
"kerning"?: boolean;
"font"?: Font;
"text"?: string; //only applicable when specified as a client-side graphic.
"text"?: string; // only applicable when specified as a client-side graphic.
}

View File

@ -1,3 +1 @@
{
"extends": "../tslint.json"
}
{ "extends": "../tslint.json" }

View File

@ -1,14 +1,14 @@
import utils = require("arcgis-to-geojson-utils");
import arcgisApi = require("arcgis-rest-api");
let arcgisPoint: arcgisApi.Point = {
const arcgisPoint: arcgisApi.Point = {
x: -122.6764,
y: 45.5165,
spatialReference: {
wkid: 4326
}
};
let geojsonPoint: GeoJSON.Point = {
const geojsonPoint: GeoJSON.Point = {
type: "Point",
coordinates: [45.5165, -122.6764]
};

View File

@ -1,3 +1 @@
{
"extends": "../tslint.json"
}
{ "extends": "../tslint.json" }

View File

@ -3,6 +3,6 @@ import arrayFindIndex = require("array-find-index");
arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn');
const ctx = {foo: 'rainbow'};
arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) {
arrayFindIndex(['rainbow', 'unicorn', 'pony'], function(x) {
return x === this.foo;
}, ctx);

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1,7 +1,7 @@
import artyomjs = require('artyom.js');
// Get an unique ArtyomJS instance
let artyom = artyomjs.ArtyomBuilder.getInstance();
const artyom = artyomjs.ArtyomBuilder.getInstance();
// Add a command (not smart)
artyom.addCommands({

14
artyom.js/index.d.ts vendored
View File

@ -403,7 +403,7 @@ declare namespace Artyom {
/**
* Says a random quote and returns it's object.
* @param data
* @param data
*/
sayRandom(data: any): any;
@ -423,14 +423,14 @@ declare namespace Artyom {
artyomHey(): any;
/**
* This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some
* This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some
* values, do not make changes directly.
*/
getNativeApi(): any;
/**
* This function returns a boolean according to the SpeechRecognition status if artyom is listening, will return true.
* Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd
* Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd
* events of the SpeechRecognition
* @returns {Boolean}
*/
@ -438,14 +438,14 @@ declare namespace Artyom {
/**
* This function returns a boolean according to the speechSynthesis status if artyom is speaking, will return true.
* Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd
* Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd
* events of the speechSynthesis.
* @returns {Boolean}
*/
isSpeaking(): boolean;
/**
* The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour
* The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour
* of artyom.say. Use this method to clear all spoken SpeechSynthesisUtterance unused objects.
* @returns {Boolean}
*/
@ -487,7 +487,7 @@ declare namespace Artyom {
getVersion(): string;
/**
* Add commands like an artisan. If you use artyom for simple
* Add commands like an artisan. If you use artyom for simple
* tasks then probably you don't like to write a lot to achieve it.
* Use the artisan syntax to write less, but with the same accuracy.
* @disclaimer Not a promise-based implementation, just syntax.
@ -508,6 +508,6 @@ declare namespace Artyom {
}
//tslint:disable-next-line:export-just-namespace
// tslint:disable-next-line:export-just-namespace
export = Artyom;
export as namespace Artyom;

View File

@ -1,5 +1,5 @@
import * as assert from 'assert-plus';
let arr = ['one', 'two'];
const arr = ['one', 'two'];
assert.array(arr, '');

234
assert-plus/index.d.ts vendored
View File

@ -7,262 +7,115 @@
import {Stream} from 'stream';
/**
*
*/
export function array(arr: any[], message ?: string): void;
/**
*
*/
export function bool(bool: boolean, message ?: string): void;
/**
*
*/
export function buffer(buffer: Buffer, message ?: string): void;
/**
*
*/
export function func(func: any, message ?: string): void;
/**
*
*/
export function number(number: number, message ?: string): void;
/**
*
*/
export function finite(finite: number, message ?: string): void;
/**
*
*/
export function object(obj: any, message ?: string): void;
/**
*
*/
export function string(str: string, message ?: string): void;
/**
*
*/
export function stream(stream: Stream, message ?: string): void;
/**
*
*/
export function date(date: Date, message ?: string): void;
/**
*
*/
export function regexp(regexp: RegExp, message ?: string): void;
/**
*
*/
export function uuid(uuid: string, message ?: string): void;
/**
*
*/
export function arrayOfArray(arr: any[][], message ?: string): void;
/**
*
*/
export function arrayOfBool(arr: boolean[], message ?: string): void;
/**
*
*/
export function arrayOfBuffer(arr: Buffer[], message ?: string): void;
/**
*
*/
export function arrayOfFunc(arr: any[], message ?: string): void;
/**
*
*/
export function arrayOfNumber(arr: number[], message ?: string): void;
/**
*
*/
export function arrayOfFinite(arr: number[], message ?: string): void;
/**
*
*/
export function arrayOfObject(arr: any[], message ?: string): void;
/**
*
*/
export function arrayOfString(arr: string[], message ?: string): void;
/**
*
*/
export function arrayOfStream(arr: Stream[], message ?: string): void;
/**
*
*/
export function arrayOfDate(arr: Date[], message ?: string): void;
/**
*
*/
export function arrayOfRegexp(arr: RegExp[], message ?: string): void;
/**
*
*/
export function arrayOfUuid(arr: string[], message ?: string): void;
/**
*
*/
export function optionalArray(arr: any[] | undefined, message ?: string): void;
/**
*
*/
export function optionalBool(bool: boolean | undefined, message ?: string): void;
/**
*
*/
export function optionalBuffer(buffer: Buffer | undefined, message ?: string): void;
/**
*
*/
export function optionalFunc(options: any, message ?: string): void;
/**
*
*/
export function optionalNumber(options: number | undefined, message ?: string): void;
/**
*
*/
export function optionalFinite(options: number | undefined, message ?: string): void;
/**
*
*/
export function optionalObject(options: any, message ?: string): void;
/**
*
*/
export function optionalString(options: string | undefined, message ?: string): void;
/**
*
*/
export function optionalStream(options: Stream | undefined, message ?: string): void;
/**
*
*/
export function optionalDate(options: Date | undefined, message ?: string): void;
/**
*
*/
export function optionalRegexp(options: RegExp | undefined, message ?: string): void;
/**
*
*/
export function optionalUuid(options: string | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfArray(arr: any[][] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfBool(arr: boolean[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfBuffer(arr: Buffer[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfFunc(arr: any[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfNumber(arr: number[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfFinite(arr: number[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfObject(arr: any[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfString(arr: string[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfStream(arr: Stream[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfDate(arr: Date[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfRegexp(arr: RegExp[] | undefined, message ?: string): void;
/**
*
*/
export function optionalArrayOfUuid(arr: string[] | undefined, message ?: string): void;
/**
*
*/
export function AssertionError(options: any, message ?: string): void;
/**
* Throws an `AssertionError`. If `message` is falsy, the error message is set
* as the values of `actual` and `expected` separated by the provided `operator`.
* Otherwise, the error message is the value of `message`.
*
*
* ```js
* const assert = require('assert');
*
*
* assert.fail(1, 2, undefined, '>');
* // AssertionError: 1 > 2
*
*
* assert.fail(1, 2, 'whoops', '>');
* // AssertionError: whoops
* ```
@ -272,14 +125,14 @@ export function fail(actual: any, expected: any, message: any, operator: any): v
/**
* Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`.
*
*
* If `value` is not truthy, an `AssertionError` is thrown with a `message` property
* set equal to the value of the `message` parameter.
* If the `message` parameter is `undefined`, a default error message is assigned.
*
*
* ```js
* const assert = require('assert');
*
*
* assert.ok(true);
* // OK
* assert.ok(1);
@ -297,21 +150,21 @@ export function ok(options: any, message ?: string): void;
/**
* Tests shallow, coercive equality between the actual and expected parameters
* using the equal comparison operator ( `==` ).
*
*
* ```js
* const assert = require('assert');
*
*
* assert.equal(1, 1);
* // OK, 1 == 1
* assert.equal(1, '1');
* // OK, 1 == '1'
*
*
* assert.equal(1, 2);
* // AssertionError: 1 == 2
* assert.equal({a: {b: 1}}, {a: {b: 1}});
* //AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
* ```
*
*
* If the values are not equal, an `AssertionError` is thrown with
* a `message` property set equal to the value of the `message` parameter.
* If the `message` parameter is undefined, a default error message is assigned.
@ -320,20 +173,20 @@ export function equal(actual: any, expected: any, message ?: string): void;
/**
* Tests shallow, coercive inequality with the not equal comparison operator ( `!=` ).
*
*
* ```js
* const assert = require('assert');
*
*
* assert.notEqual(1, 2);
* // OK
*
*
* assert.notEqual(1, 1);
* // AssertionError: 1 != 1
*
*
* assert.notEqual(1, '1');
* // AssertionError: 1 != '1'
* ```
*
*
* If the values are equal, an `AssertionError` is thrown with
* a `message` property set equal to the value of the `message` parameter.
* If the `message` parameter is undefined, a default error message is assigned.
@ -343,20 +196,20 @@ export function notEqual(actual: any, expected: any, message ?: string): void;
/**
* Tests for deep equality between the `actual` and `expected` parameters.
* Primitive values are compared with the equal comparison operator ( `==` ).
*
*
* Only enumerable "own" properties are considered.
* The `deepEqual()` implementation does not test object prototypes, attached symbols,
* or non-enumerable properties. This can lead to some potentially surprising results.
* For example, the following example does not throw an `AssertionError` because
* the properties on the Error object are non-enumerable:
*
*
* ```js
* // WARNING: This does not throw an AssertionError!
* assert.deepEqual(Error('a'), Error('b'));
* ```
*
*
* "Deep" equality means that the enumerable "own" properties of child objects are evaluated also.
*
*
* If the values are not equal, an `AssertionError` is thrown with a `message` property
* set equal to the value of the `message` parameter. If the `message` parameter is undefined,
* a default error message is assigned.
@ -365,28 +218,28 @@ export function deepEqual<T>(actual: T, expected: T, message ?: string): void;
/**
* Tests for any deep inequality. Opposite of `assert.deepEqual()`.
*
*
* ```js
* const assert = require('assert');
*
*
* const obj1 = { a : { b : 1 } };
* const obj2 = { a : { b : 2 } };
* const obj3 = { a : { b : 1 } };
* const obj4 = Object.create(obj1);
*
*
* assert.notDeepEqual(obj1, obj1);
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
*
*
* assert.notDeepEqual(obj1, obj2);
* // OK, obj1 and obj2 are not deeply equal
*
*
* assert.notDeepEqual(obj1, obj3);
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
*
*
* assert.notDeepEqual(obj1, obj4);
* // OK, obj1 and obj2 are not deeply equal
* ```
*
*
* If the values are deeply equal, an `AssertionError` is thrown with
* a `message` property set equal to the value of the `message` parameter.
* If the `message` parameter is undefined, a default error message is assigned.
@ -395,20 +248,20 @@ export function notDeepEqual(actual: any, expected: any, message ?: string): voi
/**
* Tests strict equality as determined by the strict equality operator ( `===` ).
*
*
* ```js
* const assert = require('assert');
*
*
* assert.strictEqual(1, 2);
* // AssertionError: 1 === 2
*
*
* assert.strictEqual(1, 1);
* // OK
*
*
* assert.strictEqual(1, '1');
* // AssertionError: 1 === '1'
* ```
*
*
* If the values are not strictly equal, an `AssertionError` is thrown with
* a `message` property set equal to the value of the `message` parameter.
* If the `message` parameter is undefined, a default error message is assigned.
@ -417,40 +270,37 @@ export function strictEqual<T>(actual: T, expected: T, message ?: string): void;
/**
* Tests strict inequality as determined by the strict not equal operator ( `!==` ).
*
*
* ```js
* const assert = require('assert');
*
*
* assert.notStrictEqual(1, 2);
* // OK
*
*
* assert.notStrictEqual(1, 1);
* // AssertionError: 1 !== 1
*
*
* assert.notStrictEqual(1, '1');
* // OK
* ```
*
*
* If the values are strictly equal, an `AssertionError` is thrown with a `message` property
* set equal to the value of the `message` parameter. If the `message` parameter is undefined,
* a default error message is assigned.
*/
export function notStrictEqual(actual: any, expected: any, message ?: string): void;
/**
*
*/
export function throws(block: any, error ?: any, message ?: string): void;
/**
* Asserts that the function `block` does not throw an error. See `assert.throws()` for more details.
*
*
* When `assert.doesNotThrow()` is called, it will immediately call the `block` function.
*
*
* If an error is thrown and it is the same type as that specified by the `error` parameter,
* then an `AssertionError` is thrown. If the error is of a different type,
* or if the `error` parameter is undefined, the error is propagated back to the caller.
*
*
* The following, for instance, will throw the TypeError because there is no matching error type in the assertion:
* ```js
* assert.doesNotThrow(
@ -460,7 +310,7 @@ export function throws(block: any, error ?: any, message ?: string): void;
* SyntaxError
* );
* ```
*
*
* However, the following will result in an `AssertionError` with the message 'Got unwanted exception (TypeError)..':
* ```js
* assert.doesNotThrow(
@ -470,7 +320,7 @@ export function throws(block: any, error ?: any, message ?: string): void;
* TypeError
* );
* ```
*
*
* If an `AssertionError` is thrown and a value is provided for the `message` parameter,
* the value of `message` will be appended to the `AssertionError` message:
* ```js
@ -490,7 +340,7 @@ export function doesNotThrow(block: any, error ?: any, message ?: string): void;
* Throws `value` if `value` is truthy. This is useful when testing the `error` argument in callbacks.
* ```js
* const assert = require('assert');
*
*
* assert.ifError(0);
* // OK
* assert.ifError(1);

363
auth0/index.d.ts vendored
View File

@ -1,6 +1,6 @@
// Type definitions for auth0 v2.3.1
// Type definitions for auth0 2.4
// Project: https://github.com/auth0/node-auth0
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions by: Wilson Hobbs <https://github.com/wbhob>, Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as Promise from 'bluebird';
@ -10,8 +10,8 @@ export interface ManagementClientOptions {
domain?: string;
}
export type UserMetadata = {};
export type AppMetadata = {};
export interface UserMetadata { }
export interface AppMetadata { }
export interface UserData {
connection: string;
@ -71,34 +71,353 @@ export interface UpdateUserParameters {
id: string;
}
export class ManagementClient {
constructor(options: ManagementClientOptions);
getUsers(params?: GetUsersData): Promise<User[]>;
getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void;
createUser(data: UserData): Promise<User>;
createUser(data: UserData, cb: (err: Error, data: User) => void): void;
updateUser(params: UpdateUserParameters, data: User): Promise<User>;
updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise<User>;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise<User>;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void
}
export interface AuthenticationClientOptions {
clientId?: string;
domain: string;
}
export interface RequestChangePasswordEmailData {
interface Environment {
name: string;
version: string;
}
export interface ClientInfo {
name: string;
version: string;
dependencies: any[];
environment: Environment[];
}
export interface RequestEmailOptions {
email: string;
authParams: {};
}
export interface RequestSMSOptions {
phone_number: string;
}
export interface VerifyOptions {
username: string;
password: string;
}
export interface DelegationTokenOptions {
id_token: string;
api_type: string;
scope: string;
target: string;
grant_type: string;
}
export interface ResetPasswordOptions {
connection: string;
email: string;
password: string;
}
export interface ResetPasswordEmailOptions {
email: string;
connection: string;
}
export interface ObjectWithId {
id: string;
}
export interface Data {
name?: string;
[propName: string]: any;
}
export interface ClientParams {
client_id: string;
}
export interface DeleteMultifactorParams {
id: string;
provider: string;
}
export interface LinkAccountsParams {
id: string;
provider: string;
user_id: string;
}
export interface LinkAccountsData {
user_id: string;
connection_id: string;
}
export interface Token {
aud: string;
jti: string;
}
export interface StatsParams {
from: string;
to: string;
}
export interface ImportUsersOptions {
connection_id: string;
users: string;
}
export interface UserIdParams {
user_id: string;
}
export interface PasswordChangeTicketParams {
result_url: string;
user_id: string;
email: string;
new_password: string;
}
export interface EmailVerificationTicketOptions {
user_id: string;
result_url: string;
}
export class AuthenticationClient {
constructor(options: AuthenticationClientOptions);
getClientInfo(): ClientInfo;
requestMagicLink(data: RequestEmailOptions): Promise<any>;
requestMagicLink(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void;
requestEmailCode(data: RequestEmailOptions): Promise<any>;
requestEmailCode(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void;
requestSMSCode(data: RequestSMSOptions): Promise<any>;
requestSMSCode(data: RequestSMSOptions, cb: (err: Error, message: string) => void): void;
verifyEmailCode(data: VerifyOptions): Promise<any>;
verifyEmailCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void;
verifySMSCode(data: VerifyOptions): Promise<any>;
verifySMSCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void;
getDelegationToken(data: DelegationTokenOptions): Promise<any>;
getDelegationToken(data: DelegationTokenOptions, cb: (err: Error, message: string) => void): void;
changePassword(data: ResetPasswordOptions): Promise<any>;
changePassword(data: ResetPasswordOptions, cb: (err: Error, message: string) => void): void;
requestChangePasswordEmail(data: ResetPasswordEmailOptions): Promise<any>;
requestChangePasswordEmail(data: ResetPasswordEmailOptions, cb: (err: Error, message: string) => void): void;
getProfile(accessToken: string): Promise<any>;
getProfile(accessToken: string, cb: (err: Error, message: string) => void): void;
getCredentialsGrant(scope: string): Promise<any>;
getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void;
}
export class ManagementClient {
constructor(options: ManagementClientOptions);
getClientInfo(): ClientInfo;
// Connections
getConnections(): Promise<User>;
getConnections(cb: (err: Error, data: any) => void): void;
createConnection(data: ObjectWithId): Promise<User>;
createConnection(data: ObjectWithId, cb: (err: Error, data: any) => void): void;
getConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
getConnection(params: ObjectWithId): Promise<User>;
deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
deleteConnection(params: ObjectWithId): Promise<User>;
deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
deleteConnection(params: ObjectWithId): Promise<User>;
updateConnection(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
updateConnection(params: ObjectWithId, data: Data): Promise<User>;
// Clients
getClients(): Promise<User>;
getClients(cb: (err: Error, data: any) => void): void;
getClient(params: ClientParams): Promise<User>;
getClient(params: ClientParams, cb: (err: Error, data: any) => void): void;
createClient(data: Data): Promise<User>;
createClient(data: Data, cb: (err: Error, data: any) => void): void;
updateClient(params: ClientParams, data: Data): Promise<User>;
updateClient(params: ClientParams, data: Data, cb: (err: Error, data: any) => void): void;
deleteClient(params: ClientParams): Promise<User>;
deleteClient(params: ClientParams, cb: (err: Error, data: any) => void): void;
// Client Grants
getClientGrants(): Promise<User>;
getClientGrants(cb: (err: Error, data: any) => void): void;
createClientGrant(data: Data): Promise<User>;
createClientGrant(data: Data, cb: (err: Error, data: any) => void): void;
updateClientGrant(params: ObjectWithId, data: Data): Promise<User>;
updateClientGrant(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
deleteClientGrant(params: ObjectWithId): Promise<User>;
deleteClientGrant(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
// Device Keys
getDeviceCredentials(): Promise<User>;
getDeviceCredentials(cb: (err: Error, data: any) => void): void;
createDevicePublicKey(data: Data): Promise<User>;
createDevicePublicKey(data: Data, cb: (err: Error, data: any) => void): void;
deleteDeviceCredential(params: ClientParams): Promise<User>;
deleteDeviceCredential(params: ClientParams, cb: (err: Error, data: any) => void): void;
// Rules
getRules(): Promise<User>;
getRules(cb: (err: Error, data: any) => void): void;
getRule(params: ClientParams): Promise<User>;
getRule(params: ClientParams, cb: (err: Error, data: any) => void): void;
createRules(data: Data): Promise<User>;
createRules(data: Data, cb: (err: Error, data: any) => void): void;
updateRule(params: ObjectWithId, data: Data): Promise<User>;
updateRule(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
deleteRule(params: ObjectWithId): Promise<User>;
deleteRule(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
// Users
getUsers(params?: GetUsersData): Promise<User[]>;
getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void;
getUser(params?: ObjectWithId): Promise<User[]>;
getUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void;
createUser(data: UserData): Promise<User>;
createUser(data: UserData, cb: (err: Error, data: User) => void): void;
updateUser(params: UpdateUserParameters, data: User): Promise<User>;
updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise<User>;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void;
deleteAllUsers(): Promise<User>;
deleteAllUsers(cb: (err: Error, data: any) => void): void;
deleteUser(params?: ObjectWithId): Promise<any>;
deleteUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise<User>;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void;
deleteUserMultifactor(params: DeleteMultifactorParams): Promise<any>;
deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error, data: any) => void): void;
unlinkUsers(params: LinkAccountsParams): Promise<any>;
unlinkUsers(params: LinkAccountsParams, cb: (err: Error, data: any) => void): void;
linkUsers(params: ObjectWithId, data: LinkAccountsData): Promise<any>;
linkUsers(params: ObjectWithId, data: LinkAccountsData, cb: (err: Error, data: any) => void): void;
// Tokens
getBlacklistedTokens(): Promise<any>;
getBlacklistedTokens(cb?: (err: Error, data: any) => void): void;
blacklistToken(token: Token): Promise<any>;
blacklistToken(token: Token, cb: (err: Error, data: any) => void): void;
// Providers
getEmailProvider(): Promise<any>;
getEmailProvider(cb?: (err: Error, data: any) => void): void;
configureEmailProvider(data: Data): Promise<any>;
configureEmailProvider(data: Data, cb: (err: Error, data: any) => void): void;
deleteEmailProvider(): Promise<any>;
deleteEmailProvider(cb?: (err: Error, data: any) => void): void;
updateEmailProvider(data: Data): Promise<any>;
updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void;
// Statistics
getActiveUsersCount(): Promise<any>;
getActiveUsersCount(cb?: (err: Error, data: any) => void): void;
getDailyStats(data: StatsParams): Promise<any>;
getDailyStats(data: StatsParams, cb: (err: Error, data: any) => void): void;
// Tenant
getTenantSettings(): Promise<any>;
getTenantSettings(cb?: (err: Error, data: any) => void): void;
updateTenantSettings(data: Data): Promise<any>;
updateTenantSettings(data: Data, cb?: (err: Error, data: any) => void): void;
// Jobs
getJob(params: ObjectWithId): Promise<any>;
getJob(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
importUsers(data: ImportUsersOptions): Promise<any>;
importUsers(data: ImportUsersOptions, cb?: (err: Error, data: any) => void): void;
sendEmailVerification(data: UserIdParams): Promise<any>;
sendEmailVerification(data: UserIdParams, cb?: (err: Error, data: any) => void): void;
// Tickets
createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise<any>;
createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: any) => void): void;
createEmailVerificationTicket(data: EmailVerificationTicketOptions): Promise<any>;
createEmailVerificationTicket(data: EmailVerificationTicketOptions, cb?: (err: Error, data: any) => void): void;
// Logs
getLog(params: ObjectWithId): Promise<any>;
getLog(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
getLogs(): Promise<any>;
getLogs(cb?: (err: Error, data: any) => void): void;
// Resource Server
createResourceServer(data: Data): Promise<any>;
createResourceServer(data: Data, cb?: (err: Error, data: any) => void): void;
getResourceServers(): Promise<any>;
getResourceServers(cb?: (err: Error, data: any) => void): void;
getResourceServer(data: ObjectWithId): Promise<any>;
getResourceServer(data: ObjectWithId, cb?: (err: Error, data: any) => void): void;
deleteResourceServer(params: ObjectWithId): Promise<any>;
deleteResourceServer(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
updateResourceServer(params: ObjectWithId, data: Data): Promise<any>;
updateResourceServer(params: ObjectWithId, data: Data, cb?: (err: Error, data: any) => void): void;
requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise<string>;
requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void;
}

View File

@ -1,3 +1 @@
{
"extends": "../tslint.json"
}
{ "extends": "../tslint.json" }

18
backlog-js/index.d.ts vendored
View File

@ -23,9 +23,9 @@ declare class Request {
method: string;
path: string;
params?: Params | FormData;
}): Promise<ResponseInterface>;
checkStatus(response: ResponseInterface): Promise<ResponseInterface>;
parseJSON<T>(response: ResponseInterface): Promise<T>;
}): Promise<Response>;
checkStatus(response: Response): Promise<Response>;
parseJSON<T>(response: Response): Promise<T>;
private toFormData(params);
private toQueryString(params);
webAppBaseURL: string;
@ -49,7 +49,7 @@ export class Backlog extends Request {
putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise<any>;
getSpaceDiskUsage(): Promise<any>;
getSpaceIcon(): Promise<Entity.File.FileData>;
postSpaceAttachment(form: FormData): Promise<ResponseInterface>;
postSpaceAttachment(form: FormData): Promise<Response>;
getUsers(): Promise<any>;
getUser(userId: number): Promise<any>;
postUser(params: Option.User.PostUserParams): Promise<any>;
@ -656,7 +656,7 @@ export namespace Error {
private _status;
private _body;
private _response;
constructor(name: BacklogErrorNameType, response: ResponseInterface, body?: {
constructor(name: BacklogErrorNameType, response: Response, body?: {
errors: BacklogErrorMessage[];
});
name: BacklogErrorNameType;
@ -665,20 +665,20 @@ export namespace Error {
body: {
errors: BacklogErrorMessage[];
};
response: ResponseInterface;
response: Response;
}
export class BacklogApiError extends BacklogError {
constructor(response: ResponseInterface, body?: {
constructor(response: Response, body?: {
errors: BacklogErrorMessage[];
});
}
export class BacklogAuthError extends BacklogError {
constructor(response: ResponseInterface, body?: {
constructor(response: Response, body?: {
errors: BacklogErrorMessage[];
});
}
export class UnexpectedError extends BacklogError {
constructor(response: ResponseInterface);
constructor(response: Response);
}
export interface BacklogErrorMessage {
message: string;

View File

@ -1,13 +1,13 @@
import * as base64 from 'base-64';
import * as utf8 from 'utf8';
let text = 'foo © bar 𝌆 baz';
let bytes = utf8.encode(text);
let encoded = base64.encode(bytes);
// → 'Zm9vIMKpIGJhciDwnYyGIGJheg=='
// → 'Zm9vIMKpIGJhciDwnYyGIGJheg=='
encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg==';
bytes = base64.decode(encoded);
text = utf8.decode(bytes);
let version = base64.version;
const version = base64.version;

16
base-64/index.d.ts vendored
View File

@ -6,19 +6,19 @@
export const version: string;
/**
* This function takes a byte string (the input parameter) and encodes it according to base64.
* The input data must be in the form of a string containing only characters
* in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF.
* The base64.encode() function is designed to be fully compatible
* This function takes a byte string (the input parameter) and encodes it according to base64.
* The input data must be in the form of a string containing only characters
* in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF.
* The base64.encode() function is designed to be fully compatible
* with btoa() as described in the HTML Standard.
* see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-btoa
*/
export function encode(input: string): string;
/**
* This function takes a base64-encoded string (the input parameter) and decodes it.
* The return value is in the form of a string containing only characters in
* the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF.
* The base64.decode() function is designed to be fully compatible
* This function takes a base64-encoded string (the input parameter) and decodes it.
* The return value is in the form of a string containing only characters in
* the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF.
* The base64.decode() function is designed to be fully compatible
* with atob() as described in the HTML Standard.
* see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-atob
*/

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1,9 +1,9 @@
import BigInteger = require('bigi')
import BigInteger = require('bigi');
var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012")
var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811")
var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012");
var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
var b3 = b1.multiply(b2)
var b3 = b1.multiply(b2);
console.log(b3.toHex())
console.log(b3.toHex());
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132

View File

@ -1,63 +1,64 @@
/// <reference types="node" />
import bigi = require('bigi')
import bigi = require('bigi');
import bitcoin = require('bitcoinjs-lib');
declare var it: any;
declare var describe: any;
declare var assert: any;
describe('bitcoinjs-lib (basic)', function () {
it('can generate a random bitcoin address', function () {
describe('bitcoinjs-lib (basic)', () => {
it('can generate a random bitcoin address', () => {
// for testing only
function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') }
function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); }
// generate random keyPair
var keyPair = bitcoin.ECPair.makeRandom({ rng: rng })
var address = keyPair.getAddress()
var keyPair = bitcoin.ECPair.makeRandom({ rng });
var address = keyPair.getAddress();
assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64')
})
assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64');
});
it('can generate an address from a SHA256 hash', function () {
var hash = bitcoin.crypto.sha256('correct horse battery staple')
var d = bigi.fromBuffer(hash)
it('can generate an address from a SHA256 hash', () => {
var hash = bitcoin.crypto.sha256('correct horse battery staple');
var d = bigi.fromBuffer(hash);
var keyPair = new bitcoin.ECPair(d)
var address = keyPair.getAddress()
var keyPair = new bitcoin.ECPair(d);
var address = keyPair.getAddress();
assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
})
assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8');
});
it('can generate a random keypair for alternative networks', function () {
it('can generate a random keypair for alternative networks', () => {
// for testing only
function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') }
function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); }
var litecoin = bitcoin.networks.litecoin
var litecoin = bitcoin.networks.litecoin;
var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng })
var wif = keyPair.toWIF()
var address = keyPair.getAddress()
var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng });
var wif = keyPair.toWIF();
var address = keyPair.getAddress();
assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn')
assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS')
})
assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn');
assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS');
});
it('can import an address via WIF', function () {
var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct')
var address = keyPair.getAddress()
it('can import an address via WIF', () => {
var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct');
var address = keyPair.getAddress();
assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31')
})
assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31');
});
it('can create a Transaction', function () {
var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy')
var tx = new bitcoin.TransactionBuilder()
it('can create a Transaction', () => {
var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy');
var tx = new bitcoin.TransactionBuilder();
tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0)
tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000)
tx.sign(0, keyPair)
tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0);
tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000);
tx.sign(0, keyPair);
assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000')
})
})
// tslint:disable-next-line:max-line-length
assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000');
});
});

View File

@ -1,20 +1,20 @@
import * as Protocol from 'bittorrent-protocol';
import * as net from 'net';
net.createServer(function(socket) {
net.createServer(socket => {
var wire = new Protocol();
// pipe to and from the protocol
socket.pipe(wire).pipe(socket);
wire.on('handshake', function(infoHash, peerId) {
wire.on('handshake', (infoHash, peerId) => {
// receive a handshake (infoHash and peerId are hex strings)
// lets emit a handshake of our own as well
wire.handshake('my info hash (hex)', 'my peer id (hex)');
});
wire.on('unchoke', function() {
wire.on('unchoke', () => {
console.log('peer is no longer choking us: ' + wire.peerChoking);
});
}).listen(6881);

View File

@ -1,6 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"no-misused-new": false
}
"extends": "../tslint.json",
"rules": {
"no-misused-new": false
}
}

View File

@ -1,13 +1,13 @@
var someInput = { a: 1, b: 2, c: 3 }
var someInput = { a: 1, b: 2, c: 3 };
import blacklist = require('blacklist')
import blacklist = require('blacklist');
blacklist(someInput, 'b', 'c')
blacklist(someInput, 'b', 'c');
// => { a: 1 }
blacklist(someInput, {
a: true, // a will not be in the result
b: false, // b will be in the result
c: 1 > 2 // false, therefore c will be in the result
})
});
// => { b: 2, c: 3 }

View File

@ -1,9 +1,10 @@
{
"extends": "../tslint.json",
"rules": {
"no-empty-interface": false,
"array-type": false,
"unified-signatures": false,
"forbidden-types": false
}
"extends": "../tslint.json",
"rules": {
"max-line-length": false,
"no-empty-interface": false,
"array-type": false,
"unified-signatures": false,
"forbidden-types": false
}
}

View File

@ -1,6 +1,6 @@
// Type definitions for body-parser
// Project: http://expressjs.com
// Definitions by: Santi Albo <https://github.com/santialbo/>, VILIC VANE <https://vilic.info>, Jonathan Häberle <https://github.com/dreampulse/>
// Definitions by: Santi Albo <https://github.com/santialbo/>, VILIC VANE <https://vilic.info>, Jonathan Häberle <https://github.com/dreampulse/>, Gevik Babakhani <https://github.com/blendsdk/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -41,7 +41,14 @@ declare function bodyParser(options?: {
}): express.RequestHandler;
declare namespace bodyParser {
export function json(options?: {
/**
* Interface for defining the options for the json() middleware
*
* @export
* @interface JsonOptions
*/
export interface JsonOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@ -66,9 +73,15 @@ declare namespace bodyParser {
* passed to JSON.parse().
*/
reviver?: (key: string, value: any) => any;
}): express.RequestHandler;
}
export function raw(options?: {
/**
* Interface for defining the options the raw() middleware
*
* @export
* @interface RawOptions
*/
export interface RawOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@ -85,9 +98,15 @@ declare namespace bodyParser {
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
}): express.RequestHandler;
}
export function text(options?: {
/**
* Interface for defining the options for the text() middleware
*
* @export
* @interface TextOptions
*/
export interface TextOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@ -108,9 +127,15 @@ declare namespace bodyParser {
* the default charset to parse as, if not specified in content-type. (default: 'utf-8')
*/
defaultCharset?: string;
}): express.RequestHandler;
}
export function urlencoded(options: {
/**
* Interface for defining the options for the urlencoded() middleware
*
* @export
* @interface UrlEncodedOptions
*/
export interface UrlEncodedOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@ -131,7 +156,47 @@ declare namespace bodyParser {
* parse extended syntax with the qs module.
*/
extended: boolean;
}): express.RequestHandler;
}
/**
* Returns middleware that only parses json. This parser accepts any Unicode encoding
* of the body and supports automatic inflation of gzip and deflate encodings.
*
* @export
* @param {JsonOptions} [options]
* @returns {express.RequestHandler}
*/
export function json(options?: JsonOptions): express.RequestHandler;
/**
* Returns middleware that parses all bodies as a Buffer. This parser supports automatic
* inflation of gzip and deflate encodings.
*
* @export
* @param {RawOptions} [options]
* @returns {express.RequestHandler}
*/
export function raw(options?: RawOptions): express.RequestHandler;
/**
* Returns middleware that parses all bodies as a string. This parser supports
* automatic inflation of gzip and deflate encodings.
*
* @export
* @param {TextOptions} [options]
* @returns {express.RequestHandler}
*/
export function text(options?: TextOptions): express.RequestHandler;
/**
* Returns middleware that only parses urlencoded bodies. This parser accepts only
* UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
*
* @export
* @param {UrlEncodedOptions} [options]
* @returns {express.RequestHandler}
*/
export function urlencoded(options?: UrlEncodedOptions): express.RequestHandler;
}
export = bodyParser;

View File

@ -4,5 +4,5 @@ var log = bunyan.createLogger({
name: 'play',
serializers: bunyan.stdSerializers
});
log.debug({foo: 'bar'}, 'hi at debug')
log.trace('hi at trace')
log.debug({foo: 'bar'}, 'hi at debug');
log.trace('hi at trace');

View File

@ -1,13 +1,13 @@
import BufferStream = require('bufferstream')
import BufferStream = require('bufferstream');
var stream = new BufferStream({encoding:'utf8', size:'flexible'});
var stream = new BufferStream({encoding: 'utf8', size: 'flexible'});
stream.enable();
stream.disable();
stream.split('//', ':');
stream.on('split', (chunk: any, token: any) => {
console.log("got '%s' by '%s'", chunk.toString(), token.toString())
console.log("got '%s' by '%s'", chunk.toString(), token.toString());
});
stream.write("buffer:stream//23");
console.log(stream.toString());

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1,10 +1,10 @@
import camelcaseKeys = require('camelcase-keys');
camelcaseKeys({'foo-bar': true});
//=> {fooBar: true}
// => {fooBar: true}
camelcaseKeys({'foo-bar': true, nested: {unicorn_rainbow: true}}, {deep: true});
//=> {fooBar: true, nested: {unicornRainbow: true}}
camelcaseKeys({'foo-bar': true, 'nested': {unicorn_rainbow: true}}, {deep: true});
// => {fooBar: true, nested: {unicornRainbow: true}}
camelcaseKeys({_: [], 'foo-bar': true});
//=> {_: [], fooBar: true}
camelcaseKeys({'_': [], 'foo-bar': true});
// => {_: [], fooBar: true}

View File

@ -1,5 +1,3 @@
/// <reference path="index.d.ts" />
import { expect } from 'chai';
import { assert } from 'chai';
@ -44,14 +42,14 @@ const fruitSchema = {
}
};
//bdd style
// bdd style
expect(goodApple).to.be.jsonSchema(fruitSchema);
expect(badApple).to.not.be.jsonSchema(fruitSchema);
goodApple.should.be.jsonSchema(fruitSchema);
badApple.should.not.be.jsonSchema(fruitSchema);
//tdd style
// tdd style
assert.jsonSchema(goodApple, fruitSchema);
assert.notJsonSchema(badApple, fruitSchema);

View File

@ -1,6 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"no-single-declare-module": false
}
"extends": "../tslint.json",
"rules": {
"no-single-declare-module": false
}
}

View File

@ -8,7 +8,7 @@ var expect = chai.expect;
var assert = chai.assert;
function test_containSubset() {
var obj: Object = {
var obj = {
a: 'b',
c: 'd',
e: {
@ -34,7 +34,7 @@ function test_containSubset() {
}
function test_notContainSubset() {
var obj: Object = {
var obj = {
a: 'b',
c: 'd',
e: {
@ -50,16 +50,16 @@ function test_notContainSubset() {
}
function test_arrayContainSubset() {
var list: Array<Object> = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
expect(list).to.containSubset([{a:'a', b: 'b'}]);
list.should.containSubset([{a:'a', b: 'b'}]);
assert.containSubset(list, [{a:'a', b: 'b'}]);
expect(list).to.containSubset([{a: 'a', b: 'b'}]);
list.should.containSubset([{a: 'a', b: 'b'}]);
assert.containSubset(list, [{a: 'a', b: 'b'}]);
}
function test_arrayNotContainSubset() {
var list: Array<Object> = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
expect(list).not.to.containSubset([{a:'a', b: 'bd'}]);
list.should.not.containSubset([{a:'a', b: 'bd'}]);
expect(list).not.to.containSubset([{a: 'a', b: 'bd'}]);
list.should.not.containSubset([{a: 'a', b: 'bd'}]);
}

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -2,10 +2,10 @@ import * as chai from 'chai';
import chaiXml = require('chai-xml');
chai.use(chaiXml);
let expect = chai.expect;
const expect = chai.expect;
function test_chaiXml() {
let testXml = '<a:test attribute1="1" xmlns:a="test"><a:h1><a:h2>test</a:h2></a:h1></a:test>';
const testXml = '<a:test attribute1="1" xmlns:a="test"><a:h1><a:h2>test</a:h2></a:h1></a:test>';
expect('nope').xml.not.to.be.valid();
expect(testXml).xml.to.be.valid();
expect(testXml).xml.to.equal('<a:test attribute1="1" xmlns:a="test">\n<a:h1><a:h2>test</a:h2></a:h1></a:test>\n');

1
chai/index.d.ts vendored
View File

@ -358,6 +358,7 @@ declare namespace Chai {
sameMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
includeDeepMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;

View File

@ -7,7 +7,7 @@ var colors: getCharm.CharmColor[] = [ 'red', 'cyan', 'yellow', 'green', 'blue' ]
var text = 'Always after me lucky charms.';
var offset = 0;
var iv = setInterval(function () {
var iv = setInterval(() => {
var y = 0, dy = 1;
for (var i = 0; i < 40; i++) {
var color = colors[(i + offset) % colors.length];

1
chart.js/index.d.ts vendored
View File

@ -103,6 +103,7 @@ declare namespace Chart {
animation?: ChartAnimationOptions;
elements?: ChartElementsOptions;
scales?: ChartScales;
cutoutPercentage?: number;
}
export interface ChartFontOptions {

View File

@ -1,11 +1,11 @@
// Chunker
let chunker = new Chunker(1337, Uint8Array.of(1,2,3), 2);
for (let chunk of chunker) {
let chunker = new Chunker(1337, Uint8Array.of(1, 2, 3), 2);
for (const chunk of chunker) {
// Do smoething with chunk
}
while (chunker.hasNext) {
let chunk = chunker.next().value;
const chunk = chunker.next().value;
}
// Unchunker
@ -14,6 +14,6 @@ let unchunker = new Unchunker();
unchunker.onMessage = (message: Uint8Array, context: any[]) => {
// Do something with the received message
};
let chunk = Uint8Array.of(1,2).buffer;
let chunk = Uint8Array.of(1, 2).buffer;
unchunker.add(chunk);
unchunker.gc(1024);

10
chunked-dc/index.d.ts vendored
View File

@ -1,4 +1,4 @@
// Type definitions for chunked-dc v0.1.2
// Type definitions for chunked-dc 0.1
// Project: https://github.com/saltyrtc/chunked-dc-js
// Definitions by: Danilo Bargen <https://github.com/dbrgn/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -21,7 +21,7 @@ declare namespace chunkedDc {
}
interface ChunkerStatic {
new(id: number, message: Uint8Array, chunkSize: number): Chunker
new(id: number, message: Uint8Array, chunkSize: number): Chunker;
}
/** unchunker.ts **/
@ -35,14 +35,14 @@ declare namespace chunkedDc {
}
interface UnchunkerStatic {
new(): Unchunker
new(): Unchunker;
}
/** main.ts **/
interface Standalone {
Chunker: ChunkerStatic,
Unchunker: UnchunkerStatic,
Chunker: ChunkerStatic;
Unchunker: UnchunkerStatic;
}
}

View File

@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],

1
chunked-dc/tslint.json Normal file
View File

@ -0,0 +1 @@
{ "extends": "../tslint.json" }

View File

@ -17,12 +17,12 @@ var cb5 = new Clipboard('.btn', {
cb1.destroy();
cb2.on('success', function(e) {
cb2.on('success', e => {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
e.clearSelection();
});
cb2.on('error', function(e) { });
cb2.on('error', e => { });

View File

@ -1,6 +1,6 @@
import * as Clndr from 'clndr';
let options: Clndr.ClndrOptions = {
const options: Clndr.ClndrOptions = {
template: '',
startWithMonth: "YYYY-MM-DD",
weekOffset: 0,
@ -25,21 +25,21 @@ let options: Clndr.ClndrOptions = {
adjacentMonth: "adjacent-month",
},
clickEvents: {
click: function (target) { },
today: function (month) { },
nextMonth: function (month) { },
previousMonth: function (month) { },
onMonthChange: function (month) { },
nextYear: function (month) { },
previousYear: function (month) { },
onYearChange: function (month) { },
nextInterval: function (start, end) { },
previousInterval: function (start, end) { },
onIntervalChange: function (start, end) { }
click(target) { },
today(month) { },
nextMonth(month) { },
previousMonth(month) { },
onMonthChange(month) { },
nextYear(month) { },
previousYear(month) { },
onYearChange(month) { },
nextInterval(start, end) { },
previousInterval(start, end) { },
onIntervalChange(start, end) { }
},
useTouchEvents: false,
ready: function () { },
doneRendering: function () { },
ready() { },
doneRendering() { },
events: [],
dateParameter: 'date',
multiDayEvents: {
@ -59,7 +59,7 @@ let options: Clndr.ClndrOptions = {
interval: 1
},
extras: { },
render: function (data) {
render(data) {
return '<div class="html data as a string"></div>';
},
constraints: {
@ -69,7 +69,13 @@ let options: Clndr.ClndrOptions = {
moment: null
};
let myCalendar = $('.parent-element').clndr(options);
const myCalendar = $('.parent-element').clndr(options);
myCalendar.options.constraints = {
startDate: '2017-12-22',
endDate: '2018-01-09'
};
myCalendar.render();
myCalendar
.forward()
@ -82,5 +88,5 @@ myCalendar
.today()
.setEvents([])
.addEvents([])
.removeEvents(event => { return event.id === 'idToRemove'; })
.removeEvents(event => event.id === 'idToRemove')
.destroy();

8
clndr/index.d.ts vendored
View File

@ -13,6 +13,10 @@ export as namespace Clndr;
* The clndr instance
*/
export interface ClndrInstance {
/**
* Get clndr options
*/
options: ClndrOptions;
/**
* Go to the next month
*/
@ -55,6 +59,10 @@ export interface ClndrInstance {
* calendar.
*/
removeEvents(filter: (event: any) => boolean): this;
/**
* Re-render of the calendar.
*/
render(): void;
/**
* Destroy the clndr instance. This will empty the DOM node containing the
* calendar.

View File

@ -1,6 +1,3 @@
/// <reference types="node" />
/// <reference types="co-views" />
import * as views from 'co-views';
const render = views('views', {
@ -15,7 +12,6 @@ const locals = {}; // template locals data
async function test() {
const html = await render(fileName, locals);
console.log(html);
}
// or use generator

36
co-views/index.d.ts vendored
View File

@ -1,50 +1,44 @@
// Type definitions for co-views v2.1
// Type definitions for co-views 2.1
// Project: https://github.com/tj/co-views/
// Definitions by: devlee <https://github.com/devlee/>, Joshua DeVinney <https://github.com/geoffreak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace CoViews {
/**
* Pass views `dir` and `opts` to return a render function.
*/
export interface Views {
(dir?: string, opts?: CoViewsOptions): { (view: string, locals?: Object): any }
}
export interface CoViewsOptions {
export interface Options {
/**
* default extname
*/
ext?: string;
/**
* default extname
*/
ext?: string,
/**
* default extname
*/
default?: string,
default?: string;
/**
* engine map
*/
map?: Object,
map?: Object;
/**
* proxy partials
*/
partials?: Object,
partials?: Object;
/**
* cache compiled templates
*/
cache?: boolean,
cache?: boolean;
/**
* common locals data
*/
locals?: Object
locals?: Object;
}
}
declare var CoViews: CoViews.Views;
/**
* Pass views `dir` and `opts` to return a render function.
*/
declare function CoViews(dir?: string, opts?: CoViews.Options): (view: string, locals?: Object) => any;
export = CoViews;

View File

@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],

6
co-views/tslint.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
}
}

View File

@ -16,7 +16,7 @@ expect([1, 2, 3]).to.part.include([1, 4]);
expect(10, "Age").to.be.above(5);
const func = function () { return arguments; };
const func = function() { return arguments; };
expect(func()).to.be.arguments();
expect([1, 2]).to.be.an.array();
@ -136,8 +136,7 @@ class CustomError extends Error {
call: (message: string) => Error;
}
const throws = function () {
const throws = () => {
throw new CustomError("Oh no!");
};

View File

@ -1,3 +1 @@
{
"extends": "../tslint.json"
}
{ "extends": "../tslint.json" }

View File

@ -1,6 +1,3 @@
/// <reference path="index.d.ts" />
/// <reference types="node" />
let requirePeer = codependency.register(module), package: any;
requirePeer = codependency.register(module, {index: ["dependencies", "devDependencies"]});
requirePeer = codependency.get("some-middleware");

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1,69 +1,69 @@
/// <reference types= "node" />
import cs = require('coinstring')
import cs = require('coinstring');
var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"
var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex')
var version = 0x80; //Bitcoin private key
var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd";
var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex');
var version = 0x80; // Bitcoin private key
console.log(cs.encode(privateKeyHexBuf, version))
console.log(cs.encode(privateKeyHexBuf, version));
// => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD
var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed
var hash160Buf = new Buffer(hash160, 'hex')
var version = 0x00; //Bitcoin public address
var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed
var hash160Buf = new Buffer(hash160, 'hex');
var version = 0x00; // Bitcoin public address
console.log(cs.encode(hash160Buf, version));
// => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS
var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"
var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd";
//for compressed, append "01"
privateKeyHex += '01'
// for compressed, append "01"
privateKeyHex += '01';
var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex')
var version = 0x80 //Bitcoin private key
var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex');
var version = 0x80; // Bitcoin private key
console.log(cs.encode(privateKeyHexBuf, version))
console.log(cs.encode(privateKeyHexBuf, version));
// => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5auC2qc3
var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed
var hash160Buf = new Buffer(hash160, 'hex')
var version = 0x1E //Dogecoin public address
var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed
var hash160Buf = new Buffer(hash160, 'hex');
var version = 0x1E; // Dogecoin public address
console.log(cs.encode(hash160Buf, version))
console.log(cs.encode(hash160Buf, version));
// => DAcq9oJpZZAjr56RmF7Y5zmWboZWQ4HAsW
var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"
var buffer = new Buffer(data, 'hex')
var versionBuffer = new Buffer('0488ade4', 'hex') //0488ade4 is a consant listed in the aforementioned bip32 wiki.
var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35";
var buffer = new Buffer(data, 'hex');
var versionBuffer = new Buffer('0488ade4', 'hex'); // 0488ade4 is a consant listed in the aforementioned bip32 wiki.
console.log(cs.encode(buffer, versionBuffer))
console.log(cs.encode(buffer, versionBuffer));
// => xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi
var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd";
var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex')
var version = 0x80 //Bitcoin private key
var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex');
var version = 0x80; // Bitcoin private key
var toBtcWif = cs.createEncoder(version)
var toBtcWif = cs.createEncoder(version);
//later in your program
console.log(toBtcWif(privateKeyHexBuf))
// later in your program
console.log(toBtcWif(privateKeyHexBuf));
// => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD
var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD"
var version = 0x80 //Bitcoin private key
var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD";
var version = 0x80; // Bitcoin private key
var fromBtcWif = cs.createDecoder(version)
var fromBtcWif = cs.createDecoder(version);
var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed
var hash160Buf = new Buffer(hash160, 'hex')
var version = 0x6F //Bitcoin Testnet Address
var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed
var hash160Buf = new Buffer(hash160, 'hex');
var version = 0x6F; // Bitcoin Testnet Address
var testnetAddressValidator = cs.createValidator(version)
console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")) // => true
var testnetAddressValidator = cs.createValidator(version);
console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")); // => true

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -1,4 +1,4 @@
import concat = require("concat-stream")
import concat = require("concat-stream");
import { Readable } from "stream";
@ -14,7 +14,7 @@ class MyReadable extends Readable {
}
}
let myReadable = new MyReadable();
const myReadable = new MyReadable();
myReadable.pipe(concat((buf) => console.log(buf.toString())));
myReadable.pipe(concat({}, (buf) => console.log(buf.toString())));

View File

@ -5,6 +5,7 @@
"es6",
"dom"
],
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,

View File

@ -6,7 +6,7 @@ var value: any;
var key: string;
var num: number;
var bool: any;
var object:Object;
var object: any;
cs.set(key, value);
value = cs.get(key);

View File

@ -1,3 +1 @@
{
"extends": "../tslint.json"
}
{ "extends": "../tslint.json" }

View File

@ -1,3 +1 @@
{
"extends": "../tslint.json"
}
{ "extends": "../tslint.json" }

View File

@ -1,6 +1,7 @@
import convert = require("convert-source-map");
// tslint:disable:max-line-length
var json = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -7,29 +7,29 @@ const server = http.createServer((req, res) => {
const cookies = new Cookies(req, res);
let unsigned: string,
signed: string,
tampered: string
tampered: string;
if (req.url == "/set") {
if (req.url === "/set") {
cookies
// set a regular cookie
.set("unsigned", "foo", { httpOnly: false })
// set a signed cookie
.set("signed", "bar", { signed: true })
// mimic a signed cookie, but with a bogus signature
.set("tampered", "baz")
.set("tampered.sig", "bogus")
res.writeHead(302, { "Location": "/" })
return res.end("Now let's check.")
// set a signed cookie
.set("signed", "bar", { signed: true })
// mimic a signed cookie, but with a bogus signature
.set("tampered", "baz")
.set("tampered.sig", "bogus");
res.writeHead(302, { Location: "/" });
return res.end("Now let's check.");
}
unsigned = cookies.get("unsigned")
signed = cookies.get("signed", { signed: true })
tampered = cookies.get("tampered", { signed: true })
unsigned = cookies.get("unsigned");
signed = cookies.get("signed", { signed: true });
tampered = cookies.get("tampered", { signed: true });
res.writeHead(200, { "Content-Type": "text/plain" })
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(
"unsigned expected: foo\n\n" +
"unsigned actual: " + unsigned + "\n\n" +
@ -37,5 +37,5 @@ const server = http.createServer((req, res) => {
"signed actual: " + signed + "\n\n" +
"tampered expected: undefined\n\n" +
"tampered: " + tampered + "\n\n"
)
})
);
});

View File

@ -1,5 +1,3 @@
///<reference path="index.d.ts"/>
// examples taken from https://github.com/litehelpers/Cordova-sqlite-storage
function echoTestFunction() {
function successCallback(value: string) {
@ -33,26 +31,26 @@ function openingDatabase() {
}
function openingDatabase2() {
window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, function(db) {
db.transaction(function(tx) {
window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, db => {
db.transaction(tx => {
// ...
}, function(err) {
}, err => {
console.log('Open database ERROR: ' + JSON.stringify(err));
});
});
}
function singleStatementTransactions(db: SQLitePlugin.Database) {
db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function (resultSet) {
db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], resultSet => {
console.log('resultSet.insertId: ' + resultSet.insertId);
console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
}, function(error) {
}, error => {
console.log('SELECT error: ' + error.message);
});
db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (resultSet) {
db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], resultSet => {
console.log('got stringlength: ' + resultSet.rows.item(0).stringlength);
}, function(error) {
}, error => {
console.log('SELECT error: ' + error.message);
});
}
@ -62,40 +60,40 @@ function sqlBatchTransactions(db: SQLitePlugin.Database) {
'DROP TABLE IF EXISTS MyTable',
'CREATE TABLE MyTable (SampleColumn)',
[ 'INSERT INTO MyTable VALUES (?)', ['test-value'] ],
], function() {
db.executeSql('SELECT * FROM MyTable', [], function (resultSet) {
], () => {
db.executeSql('SELECT * FROM MyTable', [], resultSet => {
console.log('Sample column value: ' + resultSet.rows.item(0).SampleColumn);
});
}, function(error) {
}, error => {
console.log('Populate table error: ' + error.message);
});
}
function asynchronousTransaction(db: SQLitePlugin.Database) {
db.transaction(function(tx) {
db.transaction(tx => {
tx.executeSql('DROP TABLE IF EXISTS MyTable');
tx.executeSql('CREATE TABLE MyTable (SampleColumn)');
tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function(tx, resultSet) {
tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], (tx, resultSet) => {
console.log('resultSet.insertId: ' + resultSet.insertId);
console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
}, function(tx, error) {
}, (tx, error) => {
console.log('INSERT error: ' + error.message);
});
}, function(error) {
}, error => {
console.log('transaction error: ' + error.message);
}, function() {
}, () => {
console.log('transaction ok');
});
db.readTransaction(function(tx) {
tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], function(tx, resultSet) {
db.readTransaction(tx => {
tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], (tx, resultSet) => {
console.log("resultSet.rows.item(0).uppertext: " + resultSet.rows.item(0).uppertext);
}, function(tx, error) {
}, (tx, error) => {
console.log('SELECT error: ' + error.message);
});
}, function(error) {
}, error => {
console.log('transaction error: ' + error.message);
}, function() {
}, () => {
console.log('transaction ok');
});
}
@ -108,28 +106,28 @@ function sampleWithPRAGMA() {
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
db.transaction(function(tx) {
db.transaction(tx => {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
// demonstrate PRAGMA:
db.executeSql("pragma table_info (test_table);", [], function(res) {
db.executeSql("pragma table_info (test_table);", [], res => {
console.log("PRAGMA res: " + JSON.stringify(res));
});
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
db.transaction(function(tx) {
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
db.transaction(tx => {
tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
});
// }, function(e) { // probably example in https://github.com/litehelpers/Cordova-sqlite-storage is broken
}, function(_tx, e) {
}, (_tx, e) => {
console.log("ERROR: " + e.message);
});
});
@ -145,20 +143,20 @@ function sampleWithTransactionLevelNesting() {
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
db.transaction(function(tx) {
db.transaction(tx => {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(tx, e) {
}, (tx, e) => {
console.log("ERROR: " + e.message);
});
});
@ -177,18 +175,18 @@ function dbClose(db: SQLitePlugin.Database) {
db.close(successcb, errorcb);
db.transaction(function (tx) {
tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (tx, res) {
db.transaction(tx => {
tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], (tx, res) => {
console.log('got stringlength: ' + res.rows.item(0).stringlength);
});
}, function (error) {
}, error => {
// OK to close here:
console.log('transaction error: ' + error.message);
db.close();
}, function () {
}, () => {
// OK to close here:
console.log('transaction ok');
db.close(function () {
db.close(() => {
console.log('database is closed ok');
});
});
@ -207,11 +205,11 @@ function deleteDatabase() {
function quickInstallationTest() {
window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, function (db) {
db.executeSql("select length('tenletters') as stringlength", [], function (res) {
window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, db => {
db.executeSql("select length('tenletters') as stringlength", [], res => {
var stringlength = res.rows.item(0).stringlength;
console.log('got stringlength: ' + stringlength);
//document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength;
// document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength;
});
});
}

View File

@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "../tslint.json" }

View File

@ -17,8 +17,8 @@ class Person {
}
}
let person = new Person();
let { getPerson, getPersonAgain } = person;
const person = new Person();
const { getPerson, getPersonAgain } = person;
getPerson() === person;
@ -81,7 +81,7 @@ class Person2 {
facepalmHarder() {}
}
let person2 = new Person2();
const person2 = new Person2();
person2.facepalm();
// DEPRECATION Person#facepalm: This function will be removed in future versions.
@ -144,7 +144,7 @@ class Person3 {
}
}
let person3 = new Person3();
const person3 = new Person3();
person3.facepalmWithoutWarning();
// no warning is logged
@ -242,7 +242,7 @@ editor.hugeBuffer;
// already initialized and equals our buffer, so
// createHugeBuffer() is not called again
//TODO: For @mixin, I don't know how we can make it work for TypeScript...
// TODO: For @mixin, I don't know how we can make it work for TypeScript...
//
// @mixin (alias: @mixins)
//
@ -265,7 +265,7 @@ const FlyMixin = {
@mixin(SingerMixin, FlyMixin)
class Bird {
singMatingCall() {
//TODO: For @mixin, I don't know how we can make it work for TypeScript...
// TODO: For @mixin, I don't know how we can make it work for TypeScript...
// this.sing('tweet tweet');
}
}
@ -280,10 +280,10 @@ bird.singMatingCall();
import { time } from 'core-decorators';
let myConsole = {
time: function(label: string) { /* custom time() method */ },
timeEnd: function(label: string) { /* custom timeEnd method */ },
log: function(str: any) { /* custom log method */ }
const myConsole = {
time(label: string) { /* custom time() method */ },
timeEnd(label: string) { /* custom timeEnd method */ },
log(str: any) { /* custom log method */ }
};
class Bird2 {

View File

@ -1,8 +1,8 @@
// Type definitions for core-decorators.js v0.10
// Type definitions for core-decorators.js 0.10
// Project: https://github.com/jayphelps/core-decorators.js
// Definitions by: Qubo <https://github.com/tkqubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export interface ClassDecorator {
<TFunction extends Function>(target: TFunction): TFunction | void;

View File

@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6",
"dom"

View File

@ -0,0 +1,7 @@
{
"extends": "../tslint.json",
"rules": {
"callable-types": false,
"forbidden-types": false
}
}

View File

@ -1,5 +1,5 @@
import * as crc from "crc"
import * as fs from "fs"
import * as crc from "crc";
import * as fs from "fs";
// tests move from the readme of the module

View File

@ -31,7 +31,7 @@ YUI.add('algo-sha1-test', function (Y) {
Y.Assert.areEqual('761c457bf73b14d27e9e9265c46f4b4dda11f940', C.SHA1('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789').toString());
},
testVector7: function () {
testVector7() {
Y.Assert.areEqual('50abf5706a150990a08b2c5ea40fa0e585554732', C.SHA1('12345678901234567890123456789012345678901234567890123456789012345678901234567890').toString());
},

View File

@ -19,6 +19,6 @@ stream = stringify({ delimiter: "," });
stream.write(["1", "2", "3"]);
let transform: NodeJS.ReadWriteStream = stream;
const transform: NodeJS.ReadWriteStream = stream;
stream = stringify();

View File

@ -8,7 +8,9 @@
declare namespace stringify {
interface StringifyOpts {
/**
* List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line.
* List of fields, applied when transform returns an object.
* Order matters, read the transformer documentation for additionnal information,
* columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line.
*/
columns?: string[];
/**
@ -28,7 +30,8 @@ declare namespace stringify {
*/
header?: boolean;
/**
* String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
* String used to delimit record rows or a special value;
* special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
lineBreaks?: string;
/**
@ -48,7 +51,8 @@ declare namespace stringify {
*/
quotedString?: boolean;
/**
* String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
* String used to delimit record rows or a special value;
* special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
rowDelimiter?: string;

2
cucumber/index.d.ts vendored
View File

@ -208,7 +208,7 @@ declare namespace cucumber {
}
export interface SupportCodeConsumer {
(stepDefinitions:StepDefinitions | Hooks):void;
(stepDefinitions:StepDefinitions & Hooks):void;
}
export function defineSupportCode(consumer:SupportCodeConsumer): void;

View File

@ -15,23 +15,22 @@ import { timeYear } from 'd3-time';
// -----------------------------------------------------------------------------
class NumCoercible {
public a: number;
a: number;
constructor(a: number) {
this.a = a;
}
public valueOf() {
valueOf() {
return this.a;
}
}
class MixedObject {
public num: number;
public str: string;
public numeric: NumCoercible;
public date: Date;
num: number;
str: string;
numeric: NumCoercible;
date: Date;
constructor(a: number, date: Date) {
this.num = a;
@ -40,29 +39,58 @@ class MixedObject {
this.date = date;
}
}
let num: number;
let str: string;
let numeric: NumCoercible;
let date: Date;
let extentNum: [number, number];
let extentStr: [string, string];
let extentNumeric: [NumCoercible, NumCoercible];
let extentDateMixed: [d3Array.Primitive, d3Array.Primitive];
let extentMixed: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible];
let extentDate: [Date, Date];
let numOrUndefined: number | undefined;
let strOrUndefined: string | undefined;
let numericOrUndefined: NumCoercible | undefined;
let dateOrUndefined: Date | undefined;
let numOrUndefinedExtent: [number, number] | [undefined, undefined];
let strOrUndefinedExtent: [string, string] | [undefined, undefined];
let numericOrUndefinedExtent: [NumCoercible, NumCoercible] | [undefined, undefined];
let dateMixedOrUndefined: [Date , Date] | [undefined, undefined];
let mixedOrUndefinedExtent: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible] | [undefined, undefined];
let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined];
let numbersArray = [10, 20, 30, 40, 50];
let stringyNumbersArray = ['10', '20', '30', '40', '50'];
let numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)];
let dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)];
let mixedObjectArray = [
const numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50];
const stringyNumbersArray = ['10', '20', '30', '40', '50'];
const numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)];
const dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)];
const mixedObjectArray = [
new MixedObject(10, new Date(2016, 6, 1)),
new MixedObject(20, new Date(2016, 7, 30)),
new MixedObject(30, new Date(2015, 3, 15)),
new MixedObject(40, new Date(2014, 3, 15)),
new MixedObject(50, new Date(2017, 4, 15))
];
const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined];
function accessorMixedObjectToNum(datum: MixedObject, index: number, array: MixedObject[]): number {
return datum.num;
}
function accessorMixedObjectToStr(datum: MixedObject, index: number, array: MixedObject[]): string {
return datum.str;
}
function accessorMixedObjectToNumeric(datum: MixedObject, index: number, array: MixedObject[]): NumCoercible {
return datum.numeric;
}
function accessorMixedObjectToDate(datum: MixedObject, index: number, array: MixedObject[]): Date {
return datum.date;
}
function accessorMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: Array<MixedObject | undefined>): number | undefined | null {
return datum ? datum.num : undefined;
}
function accessorMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: MixedObject[]): string | undefined | null {
return datum ? datum.str : undefined;
}
// -----------------------------------------------------------------------------
// Test Statistics
@ -72,186 +100,109 @@ let mixedObjectArray = [
// without accessors
num = d3Array.max(numbersArray);
str = d3Array.max(stringyNumbersArray);
numeric = d3Array.max(numericArray);
date = d3Array.max(dateArray);
numOrUndefined = d3Array.max(numbersArray);
strOrUndefined = d3Array.max(stringyNumbersArray);
numericOrUndefined = d3Array.max(numericArray);
dateOrUndefined = d3Array.max(dateArray);
// with accessors
num = d3Array.max(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
str = d3Array.max(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.str;
});
numeric = d3Array.max(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.numeric;
});
date = d3Array.max(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.date;
});
numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNum);
strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStr);
numericOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumeric);
dateOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToDate);
numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumOrUndefined);
strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStrOrUndefined);
// min() -----------------------------------------------------------------------
// without accessors
num = d3Array.min(numbersArray);
str = d3Array.min(stringyNumbersArray);
numeric = d3Array.min(numericArray);
date = d3Array.min(dateArray);
numOrUndefined = d3Array.min(numbersArray);
strOrUndefined = d3Array.min(stringyNumbersArray);
numericOrUndefined = d3Array.min(numericArray);
dateOrUndefined = d3Array.min(dateArray);
// with accessors
num = d3Array.min(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
str = d3Array.min(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.str;
});
numeric = d3Array.min(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.numeric;
});
date = d3Array.min(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.date;
});
numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNum);
strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStr);
numericOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumeric);
dateOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToDate);
numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumOrUndefined);
strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStrOrUndefined);
// extent() --------------------------------------------------------------------
// without accessors
extentNum = d3Array.extent(numbersArray);
extentStr = d3Array.extent(stringyNumbersArray);
extentNumeric = d3Array.extent(numericArray);
extentDate = d3Array.extent(dateArray);
extentMixed = d3Array.extent<NumCoercible>([new NumCoercible(10), 13, '12', true]);
numOrUndefinedExtent = d3Array.extent(numbersArray);
strOrUndefinedExtent = d3Array.extent(stringyNumbersArray);
numericOrUndefinedExtent = d3Array.extent(numericArray);
dateOrUndefinedExtent = d3Array.extent(dateArray);
// with accessors
extentNum = d3Array.extent(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
extentStr = d3Array.extent(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.str;
});
extentMixed = d3Array.extent(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.numeric;
});
extentDateMixed = d3Array.extent(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.date;
});
numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNum);
strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStr);
mixedOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumeric);
dateMixedOrUndefined = d3Array.extent(mixedObjectArray, accessorMixedObjectToDate);
numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumOrUndefined);
strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStrOrUndefined);
// mean() ----------------------------------------------------------------------
num = d3Array.mean(numbersArray);
numOrUndefined = d3Array.mean(numbersArray);
numOrUndefined = d3Array.mean(numericArray);
numOrUndefined = d3Array.mean(numbersOrUndefinedArray);
num = d3Array.mean(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
numOrUndefined = d3Array.mean(mixedObjectArray, accessorMixedObjectToNum);
numOrUndefined = d3Array.mean(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined);
// median() --------------------------------------------------------------------
num = d3Array.median(numbersArray);
numOrUndefined = d3Array.median(numbersArray);
numOrUndefined = d3Array.median(numericArray);
numOrUndefined = d3Array.median(numbersOrUndefinedArray);
num = d3Array.median(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
numOrUndefined = d3Array.median(mixedObjectArray, accessorMixedObjectToNum);
numOrUndefined = d3Array.median(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined);
// quantile() ------------------------------------------------------------------
num = d3Array.quantile(numbersArray, 0.5);
numOrUndefined = d3Array.quantile(numbersArray, 0.5);
numOrUndefined = d3Array.quantile(numericArray, 0.5);
numOrUndefined = d3Array.quantile(numbersOrUndefinedArray, 0.5);
num = d3Array.quantile(mixedObjectArray, 0.5, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
numOrUndefined = d3Array.quantile(mixedObjectArray, 0.5, accessorMixedObjectToNum);
numOrUndefined = d3Array.quantile(mixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined);
// sum() -----------------------------------------------------------------------
numOrUndefined = d3Array.sum(numbersArray);
numOrUndefined = d3Array.sum(numericArray);
numOrUndefined = d3Array.sum(numbersOrUndefinedArray);
num = d3Array.sum(numbersArray);
num = d3Array.sum(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
numOrUndefined = d3Array.sum(mixedObjectArray, accessorMixedObjectToNum);
numOrUndefined = d3Array.sum(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined);
// deviation() -----------------------------------------------------------------
num = d3Array.deviation(numbersArray);
numOrUndefined = d3Array.deviation(numbersArray);
numOrUndefined = d3Array.deviation(numericArray);
numOrUndefined = d3Array.deviation(numbersOrUndefinedArray);
num = d3Array.deviation(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
numOrUndefined = d3Array.deviation(mixedObjectArray, accessorMixedObjectToNum);
numOrUndefined = d3Array.deviation(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined);
// variance() ------------------------------------------------------------------
num = d3Array.variance(numbersArray);
numOrUndefined = d3Array.variance(numbersArray);
numOrUndefined = d3Array.variance(numericArray);
numOrUndefined = d3Array.variance(numbersOrUndefinedArray);
num = d3Array.variance(mixedObjectArray, function (datum, index, array) {
let d: MixedObject = datum;
let i: number = index;
let arr: Array<MixedObject> = array;
return datum.num;
});
numOrUndefined = d3Array.variance(mixedObjectArray, accessorMixedObjectToNum);
numOrUndefined = d3Array.variance(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined);
// -----------------------------------------------------------------------------
// Test Searching Arrays
@ -259,8 +210,18 @@ num = d3Array.variance(mixedObjectArray, function (datum, index, array) {
// scan() ----------------------------------------------------------------------
num = d3Array.scan(mixedObjectArray, function (a, b) {
return a.num - b.num; // a and b are of type MixedObject
numOrUndefined = d3Array.scan(numbersArray);
numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => {
const aElem: MixedObject = a;
const bElem: MixedObject = b;
return a.num - b.num;
});
numOrUndefined = d3Array.scan(mixedObjectOrUndefinedArray, (a, b) => {
const aElem: MixedObject | undefined = a;
const bElem: MixedObject | undefined = b;
return a && b ? a.num - b.num : NaN;
});
// bisectLeft() ----------------------------------------------------------------
@ -307,19 +268,16 @@ num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012,
// bisector() ------------------------------------------------------------------
mixedObjectArray.sort(function (a, b) { return a.date.valueOf() - b.date.valueOf(); });
mixedObjectArray.sort((a, b) => a.date.valueOf() - b.date.valueOf());
let mixedObjectDateBisectorObject: d3Array.Bisector<MixedObject, Date>;
// define using accessor
mixedObjectDateBisectorObject = d3Array.bisector<MixedObject, Date>(function (el) {
return el.date;
});
mixedObjectDateBisectorObject = d3Array.bisector<MixedObject, Date>(el => el.date);
// define using comparator
mixedObjectDateBisectorObject = d3Array.bisector<MixedObject, Date>(function (el, x) {
return el.date.valueOf() - x.valueOf();
});
mixedObjectDateBisectorObject = d3Array.bisector<MixedObject, Date>((el, x) =>
el.date.valueOf() - x.valueOf());
// bisect left
num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14));
@ -334,12 +292,14 @@ num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14
// ascending() -----------------------------------------------------------------
num = d3Array.ascending(undefined, 20);
num = d3Array.ascending(10, 20);
num = d3Array.ascending('10', '20');
num = d3Array.ascending(new Date(2016, 6, 13), new Date(2016, 6, 14));
// descending() ----------------------------------------------------------------
num = d3Array.descending(undefined, 20);
num = d3Array.descending(10, 20);
num = d3Array.descending('10', '20');
num = d3Array.descending(new Date(2016, 6, 13), new Date(2016, 6, 14));
@ -364,12 +324,11 @@ let testArrays: MixedObject[][] = [
]
];
let mergedArray: MixedObject[];
mergedArray = d3Array.merge(testArrays); // inferred type
mergedArray = d3Array.merge<MixedObject>(testArrays); // explicit type
// mergedArray = d3.merge<MixedObject>([[10, 40, 30], [15, 30]]); // fails, type mismatch
// mergedArray = d3Array.merge<MixedObject>([[10, 40, 30], [15, 30]]); // fails, type mismatch
// pairs() ---------------------------------------------------------------------
@ -384,14 +343,14 @@ mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]);
// Getting an ordered array with object properties
let testObject = {
const testObject = {
val: 10,
name: 'Test',
when: new Date(),
more: [10, 30, 40]
};
let x: Array<number | string | Date | number[]> = d3Array.permute(testObject, ['name', 'val', 'when', 'more']);
const x: Array<number | string | Date | number[]> = d3Array.permute(testObject, ['name', 'val', 'when', 'more']);
// range() ---------------------------------------------------------------------
@ -450,7 +409,7 @@ testArrays = d3Array.zip(
// Test Histogram
// -----------------------------------------------------------------------------
let tScale = scaleTime();
const tScale = scaleTime();
// Create histogram generator ==================================================
@ -464,10 +423,10 @@ testHistogram = d3Array.histogram<MixedObject, Date>();
// value(...) ------------------------------------------------------------------
testHistogram = testHistogram.value(function (d, i, data) {
let datum: MixedObject = d; // d is of type MixedObject
let index: number = i; // i is number
let array: MixedObject[] = data; // data is of type MixedObject[]
testHistogram = testHistogram.value((d, i, data) => {
const datum: MixedObject = d; // d is of type MixedObject
const index: number = i; // i is number
const array: MixedObject[] = data; // data is of type MixedObject[]
return datum.date;
});
@ -480,16 +439,14 @@ valueAccessorFn = testHistogram.value();
testHistogram = testHistogram.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]);
// usage with scale domain:
let domain = tScale.domain();
const domain = tScale.domain();
testHistogram = testHistogram.domain([domain[0], domain[domain.length]]);
// testHistogram = testHistogram.domain(tScale.domain()); // fails, as scale domain is an array with possibly more than the two elements expected by histogram
// use with accessor function
testHistogram = testHistogram.domain(function (values) {
return [values[0], values[values.length]];
});
testHistogram = testHistogram.domain(values => [values[0], values[values.length]]);
// get current domain accessor function
let domainAccessorFn: (values: Date[]) => [Date, Date];
@ -508,7 +465,7 @@ defaultHistogram = defaultHistogram.thresholds(d3Array.thresholdScott);
testHistogram = testHistogram.thresholds([new Date(2015, 11, 15), new Date(2016, 6, 1), new Date(2016, 8, 30)]);
// with thresholds value array accessors
testHistogram = testHistogram.thresholds(function (values: Date[], min: Date, max: Date) {
testHistogram = testHistogram.thresholds((values: Date[], min: Date, max: Date) => {
let thresholds: Date[];
thresholds = [values[0], values[2], values[4]];
return thresholds;
@ -536,7 +493,7 @@ let testBin: d3Array.Bin<MixedObject, Date>;
testBin = testBins[0];
num = testBin.length; // defaultBin is array
let mixedObject: MixedObject = testBin[0]; // with element type MixedObject
const mixedObject: MixedObject = testBin[0]; // with element type MixedObject
date = testBin.x0; // bin lower bound is Date
date = testBin.x1; // bin upper bound is Date

86
d3-array/index.d.ts vendored
View File

@ -1,8 +1,10 @@
// Type definitions for D3JS d3-array module v1.0.1
// Type definitions for D3JS d3-array module 1.0
// Project: https://github.com/d3/d3-array
// Definitions by: Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>, Tom Wanzek <https://github.com/tomwanzek>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Last module patch version validated against: 1.0.2
// --------------------------------------------------------------------------
// Shared Types and Interfaces
// --------------------------------------------------------------------------
@ -20,17 +22,11 @@ interface Numeric {
valueOf(): number;
}
// --------------------------------------------------------------------------------------
// Descriptive Statistics
// --------------------------------------------------------------------------------------
/**
* Return the maximum value in the array of numbers using natural order.
*/
export function max(array: number[]): number | undefined;
/**
* Return the maximum value in the array of strings using natural order.
*/
@ -41,25 +37,15 @@ export function max(array: string[]): string | undefined;
*/
export function max<T extends Numeric>(array: T[]): T | undefined;
/**
* Return the maximum value in the array using natural order and a projection function to map values to numbers.
*/
export function max<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined;
/**
* Return the maximum value in the array using natural order and a projection function to map values to strings.
*/
export function max<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => string): string | undefined;
export function max<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined;
/**
* Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values.
*/
export function max<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number, array: T[]) => U): U | undefined;
/**
* Return the minimum value in the array using natural order.
*/
export function min(array: number[]): number | undefined;
export function max<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined;
/**
* Return the minimum value in the array using natural order.
@ -74,25 +60,15 @@ export function min<T extends Numeric>(array: T[]): T | undefined;
/**
* Return the minimum value in the array using natural order.
*/
export function min<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined;
export function min<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined;
/**
* Return the minimum value in the array using natural order.
*/
export function min<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => string): string | undefined;
/**
* Return the minimum value in the array using natural order.
*/
export function min<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number, array: T[]) => U): U | undefined;
export function min<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined;
/**
* Return the min and max simultaneously.
*/
export function extent(array: number[]): [number, number] | [undefined, undefined];
/**
* Return the min and max simultaneously.
*/
@ -106,79 +82,70 @@ export function extent<T extends Numeric>(array: T[]): [T, T] | [undefined, unde
/**
* Return the min and max simultaneously.
*/
export function extent<T extends Numeric>(array: Array<T | Primitive>): [T | Primitive, T | Primitive] | [undefined, undefined];
export function extent<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): [string, string] | [undefined, undefined];
/**
* Return the min and max simultaneously.
*/
export function extent<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): [number, number] | [undefined, undefined];
/**
* Return the min and max simultaneously.
*/
export function extent<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => string): [string, string] | [undefined, undefined];
/**
* Return the min and max simultaneously.
*/
export function extent<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number, array: T[]) => U): [U, U ] | [undefined, undefined];
export function extent<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): [U, U] | [undefined, undefined];
/**
* Return the mean of an array of numbers
*/
export function mean(array: number[]): number | undefined;
export function mean<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined;
export function mean<T extends Numeric>(array: Array<T | undefined | null>): number | undefined;
export function mean<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined;
/**
* Return the median of an array of numbers
*/
export function median(array: number[]): number | undefined;
export function median<T>(array: T[], accessor: (element: T, i: number, array: T[]) => number): number | undefined;
export function median<T extends Numeric>(array: Array<T | undefined | null>): number | undefined;
export function median<T>(array: T[], accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined;
/**
* Returns the p-quantile of an array of numbers
*/
export function quantile(array: number[], p: number): number | undefined;
export function quantile<T>(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number): number | undefined;
export function quantile<T extends Numeric>(array: Array<T | undefined | null>, p: number): number | undefined;
export function quantile<T>(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined;
/**
* Compute the sum of an array of numbers.
*/
export function sum(array: number[]): number;
export function sum<T extends Numeric>(array: Array<T | undefined | null>): number;
/**
* Compute the sum of an array, using the given accessor to convert values to numbers.
*/
export function sum<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number;
export function sum<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number;
/**
* Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers.
*/
export function deviation(array: number[]): number | undefined;
export function deviation<T extends Numeric>(array: Array<T | undefined | null>): number | undefined;
/**
* Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array,
* using the given accessor to convert values to numbers.
*/
export function deviation<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined;
export function deviation<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined;
/**
* Compute an unbiased estimator of the population variance of the given array of numbers.
*/
export function variance(array: number[]): number | undefined;
export function variance<T extends Numeric>(array: Array<T | undefined | null>): number | undefined;
/**
* Compute an unbiased estimator of the population variance of the given array,
* using the given accessor to convert values to numbers.
*/
export function variance<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined;
export function variance<T>(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined;
// --------------------------------------------------------------------------------------
// Searching Arrays
// --------------------------------------------------------------------------------------
export function scan<T>(array: T[], comparator: (a: T, b: T) => number): number;
export function scan(array: number[], comparator?: (a: number, b: number) => number): number | undefined;
export function scan<T>(array: T[], comparator: (a: T, b: T) => number): number | undefined;
export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number;
export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number;
@ -202,16 +169,16 @@ export function bisector<T, U>(accessor: (x: T) => U): Bisector<T, U>;
/**
* Compares two primitive values for sorting (in ascending order).
*/
export function ascending(a: Primitive, b: Primitive): number;
export function ascending(a: Primitive | undefined, b: Primitive | undefined): number;
// NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances.
/**
* Compares two primitive values for sorting (in ascending order).
*/
export function descending(a: Primitive, b: Primitive): number;
export function descending(a: Primitive | undefined, b: Primitive | undefined): number;
// --------------------------------------------------------------------------------------
// Transforming Arrays
// Transforming Arrays
// --------------------------------------------------------------------------------------
@ -236,7 +203,6 @@ export function permute<T>(array: { [key: number]: T }, keys: number[]): T[];
*/
export function permute<T>(object: { [key: string]: T }, keys: string[]): T[];
/**
* Generates a 0-based numeric sequence. The output range does not include 'stop'.
*/

View File

@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"

6
d3-array/tslint.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"unified-signatures": false
}
}

View File

@ -54,9 +54,9 @@ axisScaleString = scalePoint();
// --------------------------------------------------------------------------
let containerElement: d3Axis.AxisContainerElement;
const svg: SVGSVGElement = select<SVGSVGElement, any>('svg').node() !; //mock
const g: SVGGElement = select<SVGGElement, any>('g').node() !; //mock
const canvas: HTMLCanvasElement = select<HTMLCanvasElement, any>('canvas').node() !; //mock
const svg: SVGSVGElement = select<SVGSVGElement, any>('svg').node() !; // mock
const g: SVGGElement = select<SVGGElement, any>('g').node() !; // mock
const canvas: HTMLCanvasElement = select<HTMLCanvasElement, any>('canvas').node() !; // mock
containerElement = svg;
containerElement = g;
@ -78,7 +78,7 @@ let leftAxis: d3Axis.Axis<number | { valueOf(): number }> = d3Axis.axisLeft(scal
// scale(...) ----------------------------------------------------------------
leftAxis = leftAxis.scale(scalePow());
let powerScale: ScalePower<number, number> = leftAxis.scale<ScalePower<number, number>>();
const powerScale: ScalePower<number, number> = leftAxis.scale<ScalePower<number, number>>();
// powerScale = leftAxis.scale(); // fails, without casting as AxisScale is purposely generic
@ -86,8 +86,8 @@ let powerScale: ScalePower<number, number> = leftAxis.scale<ScalePower<number, n
bottomAxis = bottomAxis.scale(scaleOrdinal<number>());
// bottomAxis = bottomAxis.scale(scalePow()) // fails, domain of scale incompatible with domain of axis
let axisScale: d3Axis.AxisScale<string> = bottomAxis.scale();
let ordinalScale: ScaleOrdinal<string, number> = bottomAxis.scale<ScaleOrdinal<string, number>>();
const axisScale: d3Axis.AxisScale<string> = bottomAxis.scale();
const ordinalScale: ScaleOrdinal<string, number> = bottomAxis.scale<ScaleOrdinal<string, number>>();
// ordinalScale = bottomAxis.scale(); // fails, without casting as AxisScale is purposely generic
// ticks(...) ----------------------------------------------------------------
@ -102,7 +102,7 @@ topAxis = topAxis.tickArguments([20, 's']);
rightAxis = rightAxis.tickArguments([timeMinute.every(5)]);
let tickArguments: any[] = leftAxis.tickArguments();
const tickArguments: any[] = leftAxis.tickArguments();
// tickValues(...) ----------------------------------------------------------------
@ -112,17 +112,17 @@ bottomAxis = bottomAxis.tickValues(['strongly negative', 'strongly positive']);
leftAxis = leftAxis.tickValues(null);
let tickValues: Date[] | null = rightAxis.tickValues();
const tickValues: Date[] | null = rightAxis.tickValues();
// tickFormat(...) ----------------------------------------------------------------
topAxis = topAxis.tickFormat(format(',.0f'));
topAxis = topAxis.tickFormat(null);
let formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat();
const formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat();
bottomAxis.tickFormat(function (d, i) { return '#' + i; });
bottomAxis.tickFormat(function (d) { return d + '!'; });
bottomAxis.tickFormat((d, i) => '#' + i);
bottomAxis.tickFormat(d => d + '!');
// tickSize(...) ----------------------------------------------------------------
rightAxis = rightAxis.tickSize(5);
@ -147,20 +147,20 @@ num = rightAxis.tickPadding();
// Test Apply Axis
// --------------------------------------------------------------------------
let gSelection: Selection<SVGGElement, any, any, any> = select<SVGGElement, any>('g');
let gTransition = gSelection.transition();
const gSelection: Selection<SVGGElement, any, any, any> = select<SVGGElement, any>('g');
const gTransition = gSelection.transition();
gSelection.call(topAxis);
gTransition.call(topAxis);
let svgSelection: Selection<SVGSVGElement, any, any, any> = select<SVGSVGElement, any>('g');
let svgTransition = svgSelection.transition();
const svgSelection: Selection<SVGSVGElement, any, any, any> = select<SVGSVGElement, any>('g');
const svgTransition = svgSelection.transition();
svgSelection.call(leftAxis);
svgTransition.call(leftAxis);
let canvasSelection: Selection<HTMLCanvasElement, any, any, any> = select<HTMLCanvasElement, any>('canvas');
let canvasTransition = canvasSelection.transition();
const canvasSelection: Selection<HTMLCanvasElement, any, any, any> = select<HTMLCanvasElement, any>('canvas');
const canvasTransition = canvasSelection.transition();
// canvasSelection.call(rightAxis); // fails, incompatible context container element
// canvasTransition.call(rightAxis); // fails, incompatible context container element

View File

@ -26,9 +26,9 @@ interface BrushDatum {
let brush: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brush<BrushDatum>();
let brushX: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushX<BrushDatum>();
const brushX: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushX<BrushDatum>();
let brushY: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushY<BrushDatum>();
const brushY: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushY<BrushDatum>();
// extent() ----------------------------------------------------------------------
@ -39,7 +39,7 @@ extent = brush.extent();
brush = brush.extent([[0, 0], [300, 200]]);
// chainable with function
brush = brush.extent(function (d, i, group) {
brush = brush.extent(function(d, i, group) {
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
return d.extent; // datum of type BrushDatum
});
@ -47,10 +47,10 @@ brush = brush.extent(function (d, i, group) {
// filter() ----------------------------------------------------------------
// chainable
brush = brush.filter(function (d, i, group) {
brush = brush.filter(function(d, i, group) {
// Cast d3 event to D3ZoomEvent to be used in filter logic
let e = <d3Brush.D3BrushEvent<BrushDatum>> event;
const e = <d3Brush.D3BrushEvent<BrushDatum>> event;
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached)
@ -63,17 +63,17 @@ filterFn = brush.filter();
// chainable
brush = brush.handleSize(7);
let handleSize: number = brush.handleSize();
const handleSize: number = brush.handleSize();
// on() ------------------------------------------------------------------------
let brushed: ((this: SVGGElement, datum: BrushDatum, index: number, group: SVGGElement[] | ArrayLike<SVGGElement>) => void) | undefined;
brushed = function (d, i, group) {
brushed = (d, i, group) => {
// do anything
};
let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike<SVGSVGElement>) => void;
let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike<SVGGElement>) => void;
// let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike<SVGSVGElement>) => void;
// let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike<SVGGElement>) => void;
// chainable
brush = brush.on('end', brushed);
@ -87,11 +87,11 @@ brushed = brush.on('end');
brush = brush.on('end', null);
// re-apply
brush.on('end', function (d, i, g) {
let that: SVGGElement = this;
let datum: BrushDatum = d;
let index: number = i;
let group: SVGGElement[] | ArrayLike<SVGGElement> = g;
brush.on('end', function(d, i, g) {
const that: SVGGElement = this;
const datum: BrushDatum = d;
const index: number = i;
const group: SVGGElement[] | ArrayLike<SVGGElement> = g;
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
console.log('Extent as per data: ', d.extent); // datum of type BrushDatum
// do anything
@ -103,7 +103,7 @@ brush.on('end', function (d, i, g) {
// Test Attach Brush Behavior
// -----------------------------------------------------------------------------
let g = select<SVGSVGElement, any>('svg')
const g = select<SVGSVGElement, any>('svg')
.append<SVGGElement>('g')
.classed('brush', true)
.datum<BrushDatum>({
@ -113,7 +113,7 @@ let g = select<SVGSVGElement, any>('svg')
g.call(brush);
let gX = select<SVGSVGElement, any>('svg')
const gX = select<SVGSVGElement, any>('svg')
.append<SVGGElement>('g')
.classed('brush', true)
.datum<BrushDatum>({
@ -129,13 +129,13 @@ gX.call(brushX);
// Test Use Brush Behavior
// -----------------------------------------------------------------------------
let gTransition = g.transition();
const gTransition = g.transition();
// 2d brush move with Selection
brush.move(g, [[10, 10], [50, 50]]); // two-dimensional brush
brush.move(g, function (d, i, group) {
brush.move(g, function(d, i, group) {
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]];
const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]];
selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum
selection[0][1] = d.extent[0][1] + 10;
selection[1][0] = d.extent[0][0] + 40;
@ -145,9 +145,9 @@ brush.move(g, function (d, i, group) {
// 2d brush move with Transition
brush.move(gTransition, [[10, 10], [50, 50]]); // two-dimensional brush
brush.move(gTransition, function (d, i, group) {
brush.move(gTransition, function(d, i, group) {
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]];
const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]];
selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum
selection[0][1] = d.extent[0][1] + 10;
selection[1][0] = d.extent[0][0] + 40;
@ -156,13 +156,13 @@ brush.move(gTransition, function (d, i, group) {
});
let gXTransition = gX.transition();
const gXTransition = gX.transition();
// 1d brush move with Selection
brush.move(gX, [10, 40]); // two-dimensional brush
brush.move(gX, function (d, i, group) {
brush.move(gX, function(d, i, group) {
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
let selection: [number, number] = [0, 0];
const selection: [number, number] = [0, 0];
selection[0] = d.extent[0][0] + 10; // datum type is brushDatum
selection[1] = d.extent[0][0] + 40;
return selection;
@ -170,9 +170,9 @@ brush.move(gX, function (d, i, group) {
// 1d brush move with Transition
brush.move(gXTransition, [10, 40]); // two-dimensional brush
brush.move(gXTransition, function (d, i, group) {
brush.move(gXTransition, function(d, i, group) {
console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement
let selection: [number, number] = [0, 0];
const selection: [number, number] = [0, 0];
selection[0] = d.extent[0][0] + 10; // datum type is brushDatum
selection[1] = d.extent[0][0] + 40;
return selection;
@ -184,10 +184,10 @@ brush.move(gXTransition, function (d, i, group) {
// -----------------------------------------------------------------------------
let e: d3Brush.D3BrushEvent<BrushDatum> = event;
const e: d3Brush.D3BrushEvent<BrushDatum> = event;
let target: d3Brush.BrushBehavior<BrushDatum> = e.target;
let type: 'start' | 'brush' | 'end' | string = e.type;
let brushSelection: d3Brush.BrushSelection = e.selection;
let sourceEvent: any = e.sourceEvent;
const target: d3Brush.BrushBehavior<BrushDatum> = e.target;
const type: 'start' | 'brush' | 'end' | string = e.type;
const brushSelection: d3Brush.BrushSelection = e.selection;
const sourceEvent: any = e.sourceEvent;

View File

@ -15,7 +15,7 @@ import { ascending } from 'd3-array';
// Preparatory Steps
// ---------------------------------------------------------------------
let context: CanvasRenderingContext2D | null= document.querySelector('canvas')!.getContext('2d');
let context: CanvasRenderingContext2D | null = document.querySelector('canvas')!.getContext('2d');
let chords: d3Chord.Chords;
let chordGroups: d3Chord.ChordGroup[];
@ -23,7 +23,7 @@ let chord: d3Chord.Chord;
let chordSubgroup: d3Chord.ChordSubgroup;
let num: number;
let matrix: number[][] = [
const matrix: number[][] = [
[11975, 5871, 8916, 2868],
[1951, 10048, 2060, 6171],
[8010, 16145, 8090, 8045],
@ -79,7 +79,7 @@ chords = chordLayout(matrix);
// Test supporting interfaces ==========================================
let length: number = chords.length;
const length: number = chords.length;
chordGroups = chords.groups;
@ -126,7 +126,7 @@ svgRibbon = svgRibbon.context(null);
// source() -----------------------------------------------------------
svgRibbon = svgRibbon.source(function (d) {
svgRibbon = svgRibbon.source(d => {
return d.source; // datum is of type Chord
});
@ -134,7 +134,7 @@ subgroupAccessor = svgRibbon.source();
// target() -----------------------------------------------------------
svgRibbon = svgRibbon.target(function (d) {
svgRibbon = svgRibbon.target(d => {
return d.target; // datum is of type Chord
});
@ -145,7 +145,7 @@ subgroupAccessor = svgRibbon.target();
canvasRibbon = canvasRibbon.radius(30);
svgRibbon = svgRibbon.radius(function (d) {
svgRibbon = svgRibbon.radius(function(d) {
console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement
console.log('Subgroup startAngle', d.startAngle); // datum is of type Chord
return 30;
@ -157,7 +157,7 @@ numAccessor = svgRibbon.radius();
canvasRibbon = canvasRibbon.startAngle(0);
svgRibbon = svgRibbon.startAngle(function (d) {
svgRibbon = svgRibbon.startAngle(function(d) {
console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement
return d.startAngle; // datum is of type ChordSubgroup
});
@ -168,7 +168,7 @@ numAccessor = svgRibbon.startAngle();
canvasRibbon = canvasRibbon.endAngle(Math.PI);
svgRibbon = svgRibbon.endAngle(function (d) {
svgRibbon = svgRibbon.endAngle(function(d) {
console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement
return d.endAngle; // datum is of type ChordSubgroup
});
@ -178,7 +178,7 @@ numAccessor = svgRibbon.endAngle();
// Use RibbonGenerator =================================================
// use canvas
let ribbon: d3Chord.Ribbon = {
const ribbon: d3Chord.Ribbon = {
source: {startAngle: 0.7524114, endAngle: 1.1212972, radius: 240},
target: {startAngle: 1.8617078, endAngle: 1.9842927, radius: 240}
};
@ -199,6 +199,6 @@ let ribbonPaths: Selection<SVGPathElement, d3Chord.Chord, SVGGElement, d3Chord.C
ribbonPaths = select<SVGGElement, any>('g')
.datum(chords)
.selectAll()
.data(function (chords) { return chords; })
.data(chords => chords)
.enter().append<SVGPathElement>('path')
.attr('d', svgRibbon);

15
d3-chord/index.d.ts vendored
View File

@ -306,8 +306,9 @@ export interface RibbonGenerator<This, RibbonDatum, RibbonSubgroupDatum> {
* Sets the radius accessor to the specified function and returns this ribbon generator.
*
* @param radius An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and
* receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed
* into the generator, with the exception of the first element representing the chord datum itself. The function returns the radius value.
* receives as the first argument the source or target object returned by the respective source or target accessor function of the generator.
* It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself.
* The function returns the radius value.
*/
radius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this;
@ -326,8 +327,9 @@ export interface RibbonGenerator<This, RibbonDatum, RibbonSubgroupDatum> {
* Sets the start angle accessor to the specified function and returns this ribbon generator.
*
* @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and
* receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed
* into the generator, with the exception of the first element representing the chord datum itself. The function returns the start angle in radians.
* receives as the first argument the source or target object returned by the respective source or target accessor function of the generator.
* It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself.
* The function returns the start angle in radians.
*/
startAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this;
@ -346,8 +348,9 @@ export interface RibbonGenerator<This, RibbonDatum, RibbonSubgroupDatum> {
* Sets the end angle accessor to the specified function and returns this ribbon generator.
*
* @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and
* receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed
* into the generator, with the exception of the first element representing the chord datum itself. The function returns the end angle in radians.
* receives as the first argument the source or target object returned by the respective source or target accessor function of the generator.
* It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself.
* The function returns the end angle in radians.
*/
endAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this;

Some files were not shown because too many files have changed in this diff Show More