Merge remote-tracking branch 'upstream/types-2.0' into types-2.0

This commit is contained in:
Morgan Benton
2016-11-15 12:55:38 -05:00
348 changed files with 105428 additions and 7416 deletions
+1 -1
View File
@@ -35,5 +35,5 @@ node_modules
.sublimets
.settings/launch.json
.vscode
yarn.lock
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- 4
- 6.9.1
sudo: false
+2 -1
View File
@@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped)
* [:link:](ejson/ejson.d.ts) [ejson](https://www.npmjs.com/package/ejson) by [Shantanu Bhadoria](https://github.com/shantanubhadoria)
* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak)
@@ -1189,7 +1190,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](ng-stomp/ng-stomp.d.ts) [ngStomp](https://github.com/beevelop/ng-stomp) by [Lukasz Potapczuk](https://github.com/lpotapczuk)
* [:link:](ngstorage/ngstorage.d.ts) [ngstorage](https://github.com/gsklee/ngStorage) by [Jakub Pistek](https://github.com/kubiq)
* [:link:](nightmare/nightmare.d.ts) [Nightmare](https://github.com/segmentio/nightmare) by [horiuchi](https://github.com/horiuchi)
* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider)
* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider), [Shantanu Bhadoria](https://github.com/shantanubhadoria)
* [:link:](nock/nock.d.ts) [nock](https://github.com/pgte/nock) by [bonnici](https://github.com/bonnici)
* [:link:](node-imap/imap.d.ts) [node imap](https://github.com/mscdex/node-imap) by [Steve Fenton](https://github.com/Steve-Fenton)
* [:link:](oauth2-server/oauth2-server.d.ts) [Node OAuth2 Server](https://github.com/thomseddon/node-oauth2-server) by [Robbie Van Gorkom](https://github.com/vangorra)
+15 -7
View File
@@ -1,8 +1,16 @@
case 1. Add a new type definition.
- [ ] checked compilation succeeds with `--target es6` and `--noImplicitAny` options.
- [ ] has correct [naming convention](http://definitelytyped.org/guides/contributing.html#naming-the-file)
- [ ] has a [test file](http://definitelytyped.org/guides/contributing.html#tests) with the suffix of `-tests.ts` or `-tests.tsx`.
Please fill in this template.
case 2. Improvement to existing type definition.
- documentation or source code reference which provides context for the suggested changes. url http://api.jquery.com/html .
- it has been reviewed by a DefinitelyTyped member.
- [ ] Prefer to make your PR against the `types-2.0` branch.
- [ ] The package does not provide its own types, and you can not add them.
- [ ] Test the change in your own code.
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes).
If adding a new definition:
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Run `tsc` without errors.
- [ ] Include the required [files](https://github.com/DefinitelyTyped/DefinitelyTyped#create-a-new-package) and header.
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] Increase the version number in the header if appropriate.
+11 -3
View File
@@ -128,7 +128,7 @@ The `Project` link does not have to be to GitHub, but prefer linking to a source
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -149,14 +149,18 @@ and you may also add the `"jsx"` compiler option if your library needs it.
DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/base64-js).
#### Common mistakes
* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Either use all tabs, or always use 4 spaces. Also, always use semicolons, and use egyptian braces.
* `interface X {}`: An empty interface is essentially the `{}` type: it places no constraints on an object.
* `interface Foo { new(): Foo }`:
* `interface IFoo {}`: Don't add `I` to the front of an interface name.
* `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }
* `const Class: { new(): IClass; }`:
Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant.
* `namespace foo {}`:
Do not add a namespace just so that the `import * as foo` syntax will work.
If it is commonJs module with a single export, you should use the `import foo = require("foo")` syntax.
@@ -194,7 +198,7 @@ Changes to the `master` branch are also manually merged into the `types-2.0` bra
#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?
If the module you're referencing is an written as an external module (uses `export`), use an import.
If the module you're referencing is an external module (uses `export`), use an import.
If the module you're referenceing is an ambient module (uses `declare module`, or just declares globals), use `<reference types="" />`.
#### What do I do about older versions of typings?
@@ -209,6 +213,10 @@ A `package.json` may be included for the sake of specifying dependencies. Here's
We do not allow other fields, such as `"description"`, to be defined manually.
Also, if you need to reference an older version of typings, you must do that by adding `"dependencies": { "@types/foo": "x.y.z" }` to the package.json.
#### I notice some `tsconfig.json` are missing `"noImplicitAny": true` or `"strictNullChecks": true`.
Then they are wrong. You can help by submitting a pull request to fix them.
#### Definitions in types-2.0 seem written differently than in master.
If you're targeting types-2.0, write it like the types-2.0 definitions.
+1 -1
View File
@@ -81,7 +81,7 @@ declare namespace Ajv {
passContext?: boolean;
loopRequired?: number;
ownProperties?: boolean;
multipleOfPrecision?: boolean;
multipleOfPrecision?: boolean | number;
errorDataPath?: string,
messages?: boolean;
beautify?: boolean;
+219
View File
@@ -0,0 +1,219 @@
// Type definitions for amqplib 0.3.x
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
/// <reference types="node" />
declare module "amqplib/properties" {
namespace Replies {
interface Empty {
}
interface AssertQueue {
queue: string;
messageCount: number;
consumerCount: number;
}
interface PurgeQueue {
messageCount: number;
}
interface DeleteQueue {
messageCount: number;
}
interface AssertExchange {
exchange: string;
}
interface Consume {
consumerTag: string;
}
}
namespace Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
deadLetterRoutingKey?: string;
maxLength?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
ifEmpty?: boolean;
}
interface AssertExchange {
durable?: boolean;
internal?: boolean;
autoDelete?: boolean;
alternateExchange?: string;
arguments?: any;
}
interface DeleteExchange {
ifUnused?: boolean;
}
interface Publish {
expiration?: string;
userId?: string;
CC?: string | string[];
mandatory?: boolean;
persistent?: boolean;
deliveryMode?: boolean | number;
BCC?: string | string[];
contentType?: string;
contentEncoding?: string;
headers?: any;
priority?: number;
correlationId?: string;
replyTo?: string;
messageId?: string;
timestamp?: number;
type?: string;
appId?: string;
}
interface Consume {
consumerTag?: string;
noLocal?: boolean;
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: any;
}
interface Get {
noAck?: boolean;
}
}
interface Message {
content: Buffer;
fields: any;
properties: any;
}
}
declare module "amqplib" {
import events = require("events");
import when = require("when");
import shared = require("amqplib/properties")
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(): when.Promise<void>;
createChannel(): when.Promise<Channel>;
createConfirmChannel(): when.Promise<Channel>;
}
interface Channel extends events.EventEmitter {
close(): when.Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): when.Promise<Replies.AssertQueue>;
checkQueue(queue: string): when.Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): when.Promise<Replies.PurgeQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise<Replies.AssertExchange>;
checkExchange(exchange: string): when.Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise<Replies.Consume>;
cancel(consumerTag: string): when.Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): when.Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): when.Promise<Replies.Empty>;
recover(): when.Promise<Replies.Empty>;
}
function connect(url: string, socketOptions?: any): when.Promise<Connection>;
}
declare module "amqplib/callback_api" {
import events = require("events");
import shared = require("amqplib/properties")
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(callback?: (err: any) => void): void;
createChannel(callback: (err: any, channel: Channel) => void): void;
createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void;
}
interface Channel extends events.EventEmitter {
close(callback: (err: any) => void): void;
assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void;
checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void;
purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void;
bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void;
checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void;
deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void;
bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void;
cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void;
get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): void;
recover(callback?: (err: any, ok: Replies.Empty) => void): void;
}
interface ConfirmChannel extends Channel {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
waitForConfirms(callback?: (err: any) => void): void;
}
function connect(callback: (err: any, connection: Connection) => void): void;
function connect(url: string, callback: (err: any, connection: Connection) => void): void;
function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void;
}
+20 -22
View File
@@ -1,44 +1,42 @@
// promise api tests
import amqp = require("amqplib");
import amqp = require('amqplib');
var msg = "Hello World";
var msg = 'Hello World';
// test promise api
amqp.connect("amqp://localhost")
amqp.connect('amqp://localhost')
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.sendToQueue("myQueue", new Buffer(msg)))
.ensure(() => connection.close());
.tap(channel => channel.checkQueue('myQueue'))
.then(channel => channel.sendToQueue('myQueue', new Buffer(msg)))
.finally(() => connection.close());
});
amqp.connect("amqp://localhost")
amqp.connect('amqp://localhost')
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString())))
.ensure(() => connection.close());
.tap(channel => channel.checkQueue('myQueue'))
.then(channel => channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())))
.finally(() => connection.close());
});
// test promise api properties
var amqpMessage: amqp.Message;
amqpMessage.properties.contentType = "application/json";
amqpMessage.properties.contentType = 'application/json';
var amqpAssertExchangeOptions: amqp.Options.AssertExchange;
var anqpAssertExchangeReplies: amqp.Replies.AssertExchange;
// callback api tests
import amqpcb = require("amqplib/callback_api");
import amqpcb = require('amqplib/callback_api');
amqpcb.connect("amqp://localhost", (err, connection) => {
amqpcb.connect('amqp://localhost', (err, connection) => {
if(!err) {
connection.createChannel((err, channel) => {
if (!err) {
channel.assertQueue("myQueue", {}, (err, ok) => {
channel.assertQueue('myQueue', {}, (err, ok) => {
if(!err) {
channel.sendToQueue("myQueue", new Buffer(msg));
channel.sendToQueue('myQueue', new Buffer(msg));
}
});
}
@@ -46,13 +44,13 @@ amqpcb.connect("amqp://localhost", (err, connection) => {
}
});
amqpcb.connect("amqp://localhost", (err, connection) => {
amqpcb.connect('amqp://localhost', (err, connection) => {
if(!err) {
connection.createChannel((err, channel) => {
if (!err) {
channel.assertQueue("myQueue", {}, (err, ok) => {
channel.assertQueue('myQueue', {}, (err, ok) => {
if(!err) {
channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString()));
channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString()));
}
});
}
@@ -62,6 +60,6 @@ amqpcb.connect("amqp://localhost", (err, connection) => {
// test callback api properties
var amqpcbMessage: amqpcb.Message;
amqpcbMessage.properties.contentType = "application/json";
amqpcbMessage.properties.contentType = 'application/json';
var amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange;
var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange;
var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange;
+84 -77
View File
@@ -1,13 +1,76 @@
// Type definitions for amqplib 0.3.x
// Type definitions for amqplib 0.5.x
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>, Nicolás Fantone <https://github.com/nfantone>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
/// <reference types="node" />
declare module "amqplib/properties" {
namespace Replies {
declare module 'amqplib' {
import * as Promise from 'bluebird';
import * as events from 'events';
import shared = require('amqplib/properties');
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
export interface Connection extends events.EventEmitter {
close(): Promise<void>;
createChannel(): Promise<Channel>;
createConfirmChannel(): Promise<ConfirmChannel>;
}
export interface Channel extends events.EventEmitter {
close(): Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): Promise<Replies.AssertQueue>;
checkQueue(queue: string): Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): Promise<Replies.PurgeQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): Promise<Replies.AssertExchange>;
checkExchange(exchange: string): Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise<Replies.Consume>;
cancel(consumerTag: string): Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): Promise<Replies.Empty>;
recover(): Promise<Replies.Empty>;
}
export interface ConfirmChannel extends Channel {
publish(exchange:string, routingKey:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean;
sendToQueue(queue:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean;
waitForConfirms(): Promise<void>;
}
export function connect(url: string, socketOptions?: any): Promise<Connection>;
}
declare module 'amqplib/properties' {
export namespace Replies {
interface Empty {
}
interface AssertQueue {
@@ -29,7 +92,7 @@ declare module "amqplib/properties" {
}
}
namespace Options {
export namespace Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
@@ -40,6 +103,7 @@ declare module "amqplib/properties" {
deadLetterExchange?: string;
deadLetterRoutingKey?: string;
maxLength?: number;
maxPriority?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
@@ -56,7 +120,7 @@ declare module "amqplib/properties" {
ifUnused?: boolean;
}
interface Publish {
expiration?: string;
expiration?: string | number;
userId?: string;
CC?: string | string[];
@@ -89,92 +153,35 @@ declare module "amqplib/properties" {
}
}
interface Message {
export interface Message {
content: Buffer;
fields: any;
properties: any;
}
}
declare module "amqplib" {
declare module 'amqplib/callback_api' {
import events = require('events');
import shared = require('amqplib/properties')
import events = require("events");
import when = require("when");
import shared = require("amqplib/properties")
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(): when.Promise<void>;
createChannel(): when.Promise<Channel>;
createConfirmChannel(): when.Promise<Channel>;
}
interface Channel extends events.EventEmitter {
close(): when.Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): when.Promise<Replies.AssertQueue>;
checkQueue(queue: string): when.Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): when.Promise<Replies.PurgeQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise<Replies.AssertExchange>;
checkExchange(exchange: string): when.Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise<Replies.Consume>;
cancel(consumerTag: string): when.Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): when.Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): when.Promise<Replies.Empty>;
recover(): when.Promise<Replies.Empty>;
}
function connect(url: string, socketOptions?: any): when.Promise<Connection>;
}
declare module "amqplib/callback_api" {
import events = require("events");
import shared = require("amqplib/properties")
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
export interface Connection extends events.EventEmitter {
close(callback?: (err: any) => void): void;
createChannel(callback: (err: any, channel: Channel) => void): void;
createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void;
}
interface Channel extends events.EventEmitter {
export interface Channel extends events.EventEmitter {
close(callback: (err: any) => void): void;
assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void;
assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void;
purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void;
deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err: any, ok: Replies.DeleteQueue) => void): void;
purgeQueue(queue: string, callback?: (err: any, ok: Replies.PurgeQueue) => void): void;
bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
@@ -206,14 +213,14 @@ declare module "amqplib/callback_api" {
recover(callback?: (err: any, ok: Replies.Empty) => void): void;
}
interface ConfirmChannel extends Channel {
export interface ConfirmChannel extends Channel {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
waitForConfirms(callback?: (err: any) => void): void;
}
function connect(callback: (err: any, connection: Connection) => void): void;
function connect(url: string, callback: (err: any, connection: Connection) => void): void;
function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void;
export function connect(callback: (err: any, connection: Connection) => void): void;
export function connect(url: string, callback: (err: any, connection: Connection) => void): void;
export function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void;
}
@@ -0,0 +1,14 @@
/// <reference path="./index.d.ts" />
/// <reference path="../angular/index.d.ts" />
import * as angular from "angular";
import {ClipboardService} from "angular-clipboard";
const app = angular.module('testModule', ['angular-clipboard']);
app.controller('TestController', ($scope: ng.IScope, clipboard: ClipboardService) => {
$scope['testCopy'] = () => {
if (clipboard.supported) {
clipboard.copyText('hiiiiiii');
}
};
});
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for angular-clipboard v1.5
// Project: https://github.com/omichelsen/angular-clipboard
// Definitions by: Bradford Wagner <https://github.com/bradfordwagner/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Definition of the Clipboard Service
*/
export interface ClipboardService {
/**
* tells us whether or not angular-clipboard is supported
*/
supported: boolean;
/**
* copies text to a clipboard
* @param text the text to be copied to the clipboard
*/
copyText(text: string): void;
}
+19
View File
@@ -0,0 +1,19 @@
{
"files": [
"index.d.ts",
"angular-clipboard-tests.ts"
],
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}
+59 -53
View File
@@ -1,73 +1,79 @@
// Type definitions for angular-gettext v2.1.0
// Type definitions for angular-gettext v2.1.0
// Project: https://angular-gettext.rocketeer.be/
// Definitions by: Ákos Lukács <https://github.com/AkosLukacs>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="angular" />
declare namespace angular.gettext {
interface gettextCatalog {
//////////////
/// Fields ///
//////////////
/** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */
debug: boolean;
/** (default: [MISSING]:): Custom prefix for untranslated strings. */
debugPrefix: string;
/** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */
showTranslatedMarkers: boolean;
/** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */
translatedMarkerPrefix: string;
/** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */
translatedMarkerSuffix: string;
/** An object of loaded translation strings.Shouldn't be used directly. */
strings: {};
/** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated
* @deprecreated
*/
baseLanguage: string;
import * as angular from 'angular';
///////////////
/// Methods ///
///////////////
declare module 'angular' {
export namespace gettext {
interface gettextCatalog {
/** Sets the current language and makes sure that all translations get updated correctly. */
setCurrentLanguage(lang: string): void;
//////////////
/// Fields ///
//////////////
/** Returns the current language. */
getCurrentLanguage(): string;
/** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */
debug: boolean;
/** (default: [MISSING]:): Custom prefix for untranslated strings. */
debugPrefix: string;
/** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */
showTranslatedMarkers: boolean;
/** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */
translatedMarkerPrefix: string;
/** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */
translatedMarkerSuffix: string;
/** An object of loaded translation strings.Shouldn't be used directly. */
strings: {};
/** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated
* @deprecreated
*/
baseLanguage: string;
/** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/
* @param language A language code.
* @param strings A dictionary of strings. The format of this dictionary is:
* - Keys: Singular English strings (as defined in the source files)
* - Values: Either a single string for signular-only strings or an array of plural forms.
*/
setStrings(language: string, strings: { [key: string]: string|string[] }): void;
/** Get the correct pluralized (but untranslated) string for the value of n. */
getStringForm(string: string, n: number): string;
///////////////
/// Methods ///
///////////////
/** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect:
* var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" });
* // var hello will be "Hallo Ruben!" in Dutch.
* The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster.
*/
getString(string: string, scope?: any, context?: string): string;
/** Sets the current language and makes sure that all translations get updated correctly. */
setCurrentLanguage(lang: string): void;
/** Translate a plural string with the given context. */
getPlural(n: number, string: string, stringPlural: string, context?: any): string;
/** Returns the current language. */
getCurrentLanguage(): string;
/** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */
loadRemote(url: string): ng.IHttpPromise<any>;
}
/** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/
* @param language A language code.
* @param strings A dictionary of strings. The format of this dictionary is:
* - Keys: Singular English strings (as defined in the source files)
* - Values: Either a single string for signular-only strings or an array of plural forms.
*/
setStrings(language: string, strings: { [key: string]: string|string[] }): void;
/** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */
interface gettextFunction {
(dummyString: string): string;
/** Get the correct pluralized (but untranslated) string for the value of n. */
getStringForm(string: string, n: number): string;
/** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect:
* var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" });
* // var hello will be "Hallo Ruben!" in Dutch.
* The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster.
*/
getString(string: string, scope?: any, context?: string): string;
/** Translate a plural string with the given context. */
getPlural(n: number, string: string, stringPlural: string, context?: any): string;
/** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */
loadRemote(url: string): ng.IHttpPromise<any>;
}
/** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */
interface gettextFunction {
(dummyString: string): string;
}
}
}
+11
View File
@@ -336,6 +336,7 @@ declare module 'angular' {
onRemoving?: Function;
onDomRemoved?: Function;
origin?: string | JQuery | Element;
onCloseSuccess?: ((panel: IPanelRef, closeReason: string) => any);
}
interface IPanelRef {
@@ -408,6 +409,16 @@ declare module 'angular' {
interceptorTypes: {
CLOSE: string,
};
closeReasons: {
CLICK_OUTSIDE: string,
ESCAPE: string,
};
absPosition: {
TOP: string,
RIGHT: string,
BOTTOM: string,
LEFT: string,
};
}
}
}
@@ -66,7 +66,7 @@ angular
PermissionStore.removePermissionDefinition('user');
let permissions: Array<permissionNamespace.Permission> = PermissionStore.getStore();
let permissions = PermissionStore.getStore();
});
@@ -90,5 +90,5 @@ angular
RoleStore.removeRoleDefinition('user');
let roles: Array<permissionNamespace.Role> = RoleStore.getStore();
let roles = RoleStore.getStore();
});
+38 -19
View File
@@ -30,8 +30,8 @@ declare module 'angular' {
* @param validationFunction {Function} Function used to validate if permission is valid
*/
definePermission(
name: string,
validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise<any>
permissionName: string,
validationFunction: PermissionValidationFunction
): void;
/**
@@ -43,10 +43,14 @@ declare module 'angular' {
* @param validationFunction {Function} Function used to validate if permission is valid
*/
defineManyPermissions(
permissions: string[],
validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise<any>
permissionNames: string[],
validationFunction: PermissionValidationFunction
): void;
/**
* Removes all permissions
* @method
*/
clearStore(): void;
/**
@@ -55,7 +59,7 @@ declare module 'angular' {
*
* @param permissionName {String} Name of defined permission
*/
removePermissionDefinition(permission: string): void;
removePermissionDefinition(permissionName: string): void;
/**
* Checks if permission exists
@@ -66,13 +70,21 @@ declare module 'angular' {
*/
hasPermissionDefinition(permissionName: string): boolean;
/**
* Returns permission by it's name
* @method
*
* @returns {permission.Permission} Permissions definition object
*/
getPermissionDefinition(permissionName: string): Permission;
/**
* Returns all permissions
* @method
*
* @returns {Object} Permissions collection
*/
getStore(): Permission[];
getStore(): { [permissionName: string]: Permission };
}
export interface RoleStore {
@@ -85,8 +97,8 @@ declare module 'angular' {
* @param [validationFunction] {Function} Function used to validate if permissions in role are valid
*/
defineRole(
role: string,
permissions: Array<string>,
roleName: string,
permissions: string[],
validationFunction: RoleValidationFunction
): void;
@@ -97,7 +109,10 @@ declare module 'angular' {
* @param roleName {String} Name of defined role
* @param permissions {Array} Set of permission names
*/
defineRole(role: string, permissions: Array<string>): void;
defineRole(
roleName: string,
permissions: string[]
): void;
/**
* Checks if role is defined in store
@@ -106,7 +121,7 @@ declare module 'angular' {
* @param roleName {String} Name of role
* @returns {Boolean}
*/
hasRoleDefinition(role: string): boolean;
hasRoleDefinition(roleName: string): boolean;
/**
* Returns role definition object by it's name
@@ -136,27 +151,31 @@ declare module 'angular' {
*
* @returns {Object} Defined roles collection
*/
getStore(): Role[];
getStore(): { [roleName: string]: Role };
}
export interface Role {
roleName: string;
permissionNames: string[];
validationFunction?: RoleValidationFunction;
validateRole: () => angular.IPromise<any>;
}
export interface Permission {
permissionName: string;
validationFunction?: PermissionValidationFunction;
validatePermission: () => angular.IPromise<any>;
}
interface RoleValidationFunction {
(permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise<any>;
}
export type RoleValidationFunction = (
roleName?: string,
transitionProperties?: TransitionProperties
) => boolean | angular.IPromise<any>;
interface PermissionValidationFunction {
(permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise<any>;
}
export type PermissionValidationFunction = (
permissionName?: string,
transitionProperties?: TransitionProperties
) => boolean | angular.IPromise<any>;
export interface IPermissionState extends angular.ui.IState {
data?: any | DataWithPermissions;
@@ -164,8 +183,8 @@ declare module 'angular' {
export interface DataWithPermissions {
permissions?: {
only?: (() => void) | Array<string> | angular.IPromise<any>;
except?: (() => void) | Array<string> | angular.IPromise<any>;
only?: (() => void) | string | string[] | angular.IPromise<any>;
except?: (() => void) | string | string[] | angular.IPromise<any>;
redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | { [index: string]: PermissionRedirectConfigation }
};
}
@@ -0,0 +1,20 @@
angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker',
($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => {
const trackerWithoutOptions = promiseTracker();
const options = {
activationDelay: 10,
minDuration: 500
} as angular.promisetracker.PromiseTrackerOptions;
const trackerWithOptions = promiseTracker(options);
const isActive: boolean = trackerWithOptions.active();
const tracking: boolean = trackerWithOptions.tracking();
const trackingCount: number = trackerWithOptions.trackingCount();
trackerWithOptions.cancel();
const createdPromise: angular.IDeferred<void> = trackerWithOptions.createPromise();
const promiseToAdd = $q.defer().promise;
const addedPromise: angular.IDeferred<void> = trackerWithOptions.addPromise(promiseToAdd);
}]);
+30
View File
@@ -0,0 +1,30 @@
// Type definitions for angular-promise-tracker 2.2.2
// Project: https://github.com/ajoslin/angular-promise-tracker
// Definitions by: Rufus Linke <https://github.com/rufusl/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="angular" />
import * as angular from 'angular';
declare module 'angular' {
export namespace promisetracker {
interface PromiseTrackerOptions {
activationDelay: number;
minDuration: number;
}
interface PromiseTracker {
active(): boolean;
tracking(): boolean;
trackingCount(): number;
addPromise<T>(promise: angular.IPromise<T>): angular.IDeferred<void>;
createPromise(): angular.IDeferred<void>;
cancel(): void;
}
interface PromiseTrackerService {
(options?: PromiseTrackerOptions): PromiseTracker;
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"angular-promise-tracker-tests.ts"
]
}
@@ -1,10 +1,11 @@
/// <reference path="./angular-ui-router-default.d.ts" />
import * as angular from "angular";
import { ui } from "angular";
angular.module("test", [
"ui.router",
"ui.router.default"
])
.config(function($stateProvider: angular.ui.IStateProvider) {
.config(function($stateProvider: ui.IStateProvider) {
$stateProvider
.state('concrete', {
// no abstract or default
@@ -1,17 +0,0 @@
// Type definitions for angular-ui-router-default 0.5+
// Project: https://github.com/nonplus/angular-ui-router-default
// Definitions by: Stepan Riha <https://github.com/nonplus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angular-ui-router/angular-ui-router.d.ts" />
declare namespace angular.ui {
export type StateDefaultSpecifier = string
| ((...args: any[]) => string)
| ((...args: any[]) => ng.IPromise<string>)
| (string | ((...args: any[]) => string))[]
| (string | ((...args: any[]) => ng.IPromise<string>))[];
interface IState {
default?: StateDefaultSpecifier
}
}
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for angular-ui-router-default 0.5+
// Project: https://github.com/nonplus/angular-ui-router-default
// Definitions by: Stepan Riha <https://github.com/nonplus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as aur from "angular-ui-router";
declare module "angular" {
namespace ui {
export type StateDefaultSpecifier = string
| ((...args: any[]) => string)
| ((...args: any[]) => ng.IPromise<string>)
| (string | ((...args: any[]) => string))[]
| (string | ((...args: any[]) => ng.IPromise<string>))[];
interface IState {
default?: StateDefaultSpecifier
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"angular-ui-router-default-tests.ts"
]
}
@@ -1,5 +1,3 @@
/// <reference path="./angular-ui-router-uib-modal.d.ts" />
angular.module("test", [
"ui.bootstrap",
"ui.router",
@@ -3,10 +3,12 @@
// Definitions by: Stepan Riha <https://github.com/nonplus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angular-ui-router/angular-ui-router.d.ts" />
import * as auir from "angular-ui-router";
declare namespace angular.ui {
interface IState {
modal?: boolean | string[];
declare module "angular" {
namespace ui {
interface IState {
modal?: boolean | string[];
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"angular-ui-router-uib-modal-tests.ts"
]
}
+19 -2
View File
@@ -191,8 +191,25 @@ mod.controller({
MyCtrl2: function() {},
MyCtrl3: ['$fooService', function($fooService: any) { }]
});
mod.directive('name', <any>function ($scope: ng.IScope) { })
mod.directive('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => {
return (scope, el, attrs) => {
let foo = 'none';
el.click(e => {
foo = e.type;
$rootScope.$apply();
});
scope.$watch(() => foo, () => el.text(foo));
};
});
mod.directive('myDirectiveB', ['$rootScope', function ($rootScope: ng.IRootScopeService) {
return {
link(scope, el, attrs) {
el.click(e => {
el.hide();
});
}
};
}]);
mod.directive({
myFooDir: () => ({
template: 'my-foo-dir.tpl.html'
+3 -4
View File
@@ -1775,7 +1775,7 @@ declare namespace angular {
///////////////////////////////////////////////////////////////////////////
interface IDirectiveFactory {
(...args: any[]): IDirective;
(...args: any[]): IDirective | IDirectiveLinkFn;
}
interface IDirectiveLinkFn {
@@ -1783,8 +1783,8 @@ declare namespace angular {
scope: IScope,
instanceElement: JQuery,
instanceAttributes: IAttributes,
controller: {},
transclude: ITranscludeFunction
controller?: IController | IController[] | {[key: string]: IController},
transclude?: ITranscludeFunction
): void;
}
@@ -1812,7 +1812,6 @@ declare namespace angular {
controller?: string | Injectable<IControllerConstructor>;
controllerAs?: string;
/**
* @deprecated
* Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before
* the controller constructor is called, this use is now deprecated. Please place initialization code that
* relies upon bindings inside a $onInit method on the controller, instead.
+17 -14
View File
@@ -18,29 +18,32 @@
import * as FS from 'fs';
import * as STREAM from 'stream';
interface nameInterface {
name?: string;
}
interface Archiver extends STREAM.Transform {
pipe(writeStream: FS.WriteStream): void;
declare function archiver(format: string, options?: archiver.Options): archiver.Archiver;
declare namespace archiver {
export function create(format: string, options?: Options): Archiver;
export interface nameInterface {
name?: string;
}
export interface Archiver extends STREAM.Transform {
pipe(writeStream: FS.WriteStream): void;
append(source: FS.ReadStream | Buffer | string, name: nameInterface): void;
directory(dirpath: string, destpath: nameInterface | string): void;
directory(dirpath: string, destpath: nameInterface | string, data: any | Function): void;
bulk(mappings: any): void;
finalize(): void;
}
finalize(): void;
}
interface Options {
export interface Options {
}
declare function archiver(format: string, options?: Options): Archiver;
declare namespace archiver {
function create(format: string, options?: Options): Archiver;
}
}
export = archiver;
+39
View File
@@ -0,0 +1,39 @@
import arrayForEach = require('array-foreach');
const array: Array<number> = [1, 2, 3, 4];
const result: Array<number> = [];
arrayForEach(array, (i: number) => {
result.push(i);
});
arrayForEach(array, (i: number, index: number) => {
result.push(i + index);
});
arrayForEach(array, (i: number, index: number, array: Array<number>) => {
result.push(array[i]);
});
const resultThis: Array<{i: number, that: string}> = [];
arrayForEach(array, (i: number) => {
resultThis.push({
i: i,
that: this.that
});
}, { that: 'jeff' });
arrayForEach(array, (i: number, index: number) => {
resultThis.push({
i: i + index,
that: this.that
});
}, { that: 'jeff' });
arrayForEach(array, (i: number, index: number, array: Array<number>) => {
resultThis.push({
i: array[i],
that: this.that
});
}, { that: 'jeff' });
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for array-foreach
// Project: https://www.npmjs.com/package/array-foreach
// Definitions by: Steve Jenkins <https://github.com/skysteve>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Performs the specified action for each element in an array.
* @param arr Array of items to iterate over
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
declare function forEach<T>(arr: Array<T>, callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => void, thisArg?: any): void;
/**
* Performs the specified action for each element in an array.
* @param arr Nodelist of items to iterate over
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
declare function forEach<T extends Node>(arr: NodeListOf<T>, callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => void, thisArg?: any): void;
export = forEach;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"array-foreach-tests.ts"
]
}
+399 -45
View File
@@ -1,9 +1,10 @@
/// <reference types="node" />
import fs = require("fs");
import process = require("process");
var path: {
exists: (path: string, callback?: (err: string, exists: boolean) => any) => void;
declare var path: {
exists: (path: string, callback?: (err: Error, exists: boolean) => any) => void;
};
function callback() { }
@@ -33,8 +34,8 @@ async.series([
function () { }
]);
var data = [];
function asyncProcess(item, callback) { }
var data: any[] = [];
function asyncProcess(item: any, callback: (err: Error, result: any) => void) { }
async.map(data, asyncProcess, function (err, results) {
console.log(results);
});
@@ -49,11 +50,11 @@ var saveFile = function () { }
async.each(openFiles, saveFile, function (err) { });
async.eachSeries(openFiles, saveFile, function (err) { });
var documents, requestApi;
var documents: any, requestApi: any;
async.eachLimit(documents, 20, requestApi, function (err) { });
// forEachOf* functions. May accept array or object.
function forEachOfIterator(item, key, forEachOfIteratorCallback) {
function forEachOfIterator(item: string, key: string, forEachOfIteratorCallback: any) {
console.log("ForEach: item=" + item + ", key=" + key);
forEachOfIteratorCallback();
}
@@ -64,9 +65,8 @@ async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { });
var process;
var numArray = [1, 2, 3];
function reducer(memo, item, callback) {
function reducer(memo: any, item: any, callback: any) {
process.nextTick(function () {
callback(null, memo + item)
});
@@ -103,20 +103,20 @@ async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) {
async.series([
function (callback) {
callback(null, 'one');
callback(undefined, 'one');
},
function (callback) {
callback(null, 'two');
callback(undefined, 'two');
},
],
function (err, results) { });
async.series<string>([
function (callback) {
callback(null, 'one');
callback(undefined, 'one');
},
function (callback) {
callback(null, 'two');
callback(undefined, 'two');
},
],
function (err, results) { });
@@ -124,12 +124,12 @@ function (err, results) { });
async.series({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
callback(undefined, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
callback(undefined, 2);
}, 100);
},
},
@@ -138,25 +138,25 @@ function (err, results) { });
async.series<number>({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
callback(undefined, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
callback(undefined, 2);
}, 100);
},
},
function (err, results) { });
async.times(5, function(n, next) {
next(null, n)
next(undefined as any, n)
}, function(err, results) {
console.log(results)
})
async.timesSeries(5, function(n, next) {
next(null, n)
next(undefined as any, n)
}, function(err, results) {
console.log(results)
})
@@ -164,12 +164,12 @@ async.timesSeries(5, function(n, next) {
async.parallel([
function (callback) {
setTimeout(function () {
callback(null, 'one');
callback(undefined, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(null, 'two');
callback(undefined, 'two');
}, 100);
},
],
@@ -178,12 +178,12 @@ function (err, results) { });
async.parallel<string>([
function (callback) {
setTimeout(function () {
callback(null, 'one');
callback(undefined, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(null, 'two');
callback(undefined, 'two');
}, 100);
},
],
@@ -193,12 +193,12 @@ function (err, results) { });
async.parallel({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
callback(undefined, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
callback(undefined, 2);
}, 100);
},
},
@@ -207,12 +207,12 @@ function (err, results) { });
async.parallel<number>({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
callback(undefined, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
callback(undefined, 2);
}, 100);
},
},
@@ -221,12 +221,12 @@ async.parallel<number>({
async.parallelLimit({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
callback(undefined, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
callback(undefined, 2);
}, 100);
},
},
@@ -235,7 +235,7 @@ async.parallelLimit({
);
function whileFn(callback) {
function whileFn(callback: any) {
count++;
setTimeout(callback, 1000);
}
@@ -258,19 +258,19 @@ async.forever(function (errBack) {
);
async.waterfall([
function (callback) {
function (callback: any) {
callback(null, 'one', 'two');
},
function (arg1, arg2, callback) {
function (arg1: any, arg2: any, callback: any) {
callback(null, 'three');
},
function (arg1, callback) {
function (arg1: any, callback: any) {
callback(null, 'done');
}
], function (err, result) { });
var q = async.queue<any>(function (task: any, callback) {
var q = async.queue<any>(function (task: any, callback: any) {
console.log('hello ' + task.name);
callback();
}, 2);
@@ -323,7 +323,7 @@ q.resume();
q.kill();
// tests for strongly typed tasks
var q2 = async.queue<string>(function (task: string, callback) {
var q2 = async.queue<string>(function (task: string, callback: any) {
console.log('Task: ' + task);
callback();
}, 1);
@@ -358,26 +358,26 @@ var cargo = async.cargo(function (tasks, callback) {
// add some items
cargo.push({ name: 'foo' }, function (err) {
cargo.push({ name: 'foo' }, function (err: Error) {
console.log('finished processing foo');
});
cargo.push({ name: 'bar' }, function (err) {
cargo.push({ name: 'bar' }, function (err: Error) {
console.log('finished processing bar');
});
cargo.push({ name: 'baz' }, function (err) {
cargo.push({ name: 'baz' }, function (err: Error) {
console.log('finished processing baz');
});
var filename = '';
async.auto({
get_data: function (callback) { },
make_folder: function (callback) { },
get_data: function (callback: any) { },
make_folder: function (callback: any) { },
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback) {
write_file: ['get_data', 'make_folder', <any>function (callback: any) {
callback(null, filename);
}],
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback, results) { }]
email_link: ['write_file', <any>function (callback: any, results: any) { }]
});
async.retry(3, function (callback, results) { }, function (err, result) { });
@@ -411,13 +411,13 @@ async.parallel([
},
]);
var call_order = [];
var call_order: string[] = [];
async.nextTick(function () {
call_order.push('two');
});
call_order.push('one');
var slow_fn = function (name, callback) {
var slow_fn = function (name: string, callback: any) {
callback(null, 123);
};
var fn = async.memoize(slow_fn);
@@ -427,15 +427,369 @@ async.ensureAsync(function () { });
async.constant(42);
async.asyncify(function () { });
async.log(function (name, callback) {
async.log(function (name: any, callback: any) {
setTimeout(function () {
callback(null, 'hello ' + name);
}, 0);
}, "world"
);
async.dir(function (name, callback) {
async.dir(function (name: string, callback: any) {
setTimeout(function () {
callback(null, { hello: name });
}, 1000);
}, "world");
// each
async.each<number>({
"a": 1,
"b": 2
}, function(val: number, next: ErrorCallback): void {
setTimeout(function(): void {
console.log(`async.each: ${val}`);
next();
}, 500);
}, function(err?: Error): void {
console.log("async.each: done.");
});
async.eachSeries<number>({
"a": 1,
"b": 2
}, function(val: number, next: ErrorCallback): void {
setTimeout(function(): void {
console.log(`async.eachSeries: ${val}`);
next();
}, 500);
}, function(err?: Error): void {
console.log("async.eachSeries: done.");
});
async.eachLimit<number>({
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
}, 2, function(val: number, next: ErrorCallback): void {
setTimeout(function(): void {
console.log(`async.eachLimit: ${val}`);
next();
}, 500);
}, function(err?: Error): void {
console.log("async.eachLimit: done.");
});
// forEachOf/eachOf
async.eachOf<number>({
"a": 1,
"b": 2
}, function(val: number, key: string, next: ErrorCallback): void {
setTimeout(function(): void {
console.log(`async.forEachOf/eachOf: ${key} = ${val}`);
next();
}, 500);
}, function(err?: Error): void {
console.log("async.forEachOf/eachOf: done.");
});
async.forEachOfSeries<number>({
"a": 1,
"b": 2
}, function(val: number, key: string, next: ErrorCallback): void {
setTimeout(function(): void {
console.log(`async.forEachOfSeries: ${key} = ${val}`);
next();
}, 500);
}, function(err?: Error): void {
console.log("async.forEachOfSeries: done.");
});
async.forEachOfLimit<number>({
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
}, 2, function(val: number, key: string, next: ErrorCallback): void {
setTimeout(function(): void {
console.log(`async.forEachOfLimit: ${key} = ${val}`);
next();
}, 500);
}, function(err?: Error): void {
console.log("async.forEachOfLimit: done.");
});
// map
async.map<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
console.log(`async.map: ${val}`);
next(undefined as any, val.toString());
}, 500);
}, function(err: Error, results: string[]): void {
console.log("async.map: done with results", results);
});
async.mapSeries<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
console.log(`async.mapSeries: ${val}`);
next(undefined as any, val.toString());
}, 500);
}, function(err: Error, results: string[]): void {
console.log("async.mapSeries: done with results", results);
});
async.mapLimit<number, string>({
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
}, 2, function(val: number, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
console.log(`async.mapLimit: ${val}`);
next(undefined as any, val.toString());
}, 500);
}, function(err: Error, results: string[]): void {
console.log("async.mapLimit: done with results", results);
});
// mapValues
async.mapValues<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, key: string, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
console.log(`async.mapValues: ${key} = ${val}`);
next(undefined as any, val.toString());
}, 500);
}, function(err: Error, results: string[]): void {
console.log("async.mapValues: done with results", results);
});
async.mapValuesSeries<number, string>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, key: string, next: AsyncResultCallback<string>): void {
setTimeout(function(): void {
console.log(`async.mapValuesSeries: ${key} = ${val}`);
next(undefined as any, val.toString());
}, 500);
}, function(err: Error, results: string[]): void {
console.log("async.mapValuesSeries: done with results", results);
});
// filter/select/reject
async.filter<number>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncBooleanResultCallback): void {
setTimeout(function(): void {
console.log(`async.filter/select: ${val}`);
next(undefined as any, val % 2 === 0);
}, 500);
}, function(err: Error, results: number[]): void {
console.log("async.filter/select: done with results", results);
});
async.reject<number>({
"a": 1,
"b": 2,
"c": 3
}, function(val: number, next: AsyncBooleanResultCallback): void {
setTimeout(function(): void {
console.log(`async.reject: ${val}`);
next(undefined as any, val % 2 === 0);
}, 500);
}, function(err: Error, results: number[]): void {
console.log("async.reject: done with results", results);
});
// concat
async.concat<string, string>({
"a": "1",
"b": "2",
"c": "3"
}, function(item: string, next: AsyncResultCallback<string[]>): void {
console.log(`async.concat: ${item}`);
next(undefined as any, [item, item, item]);
}, function(err: Error, results: string[]) {
console.log("async.concat: done with results", results);
});
// detect/find
async.detect<number>({
"a": 1,
"b": 2,
"c": 3
}, function(item: number, next: AsyncBooleanResultCallback): void {
console.log(`async.detect/find: ${item}`);
next(undefined as any, item > 1);
}, function(err: Error, result: number) {
if (err) {
console.log(err);
} else {
console.log("async.detect/find: done with result", result);
}
});
// every/all
async.every<number>({
"a": 1,
"b": 2,
"c": 3
}, function(item: number, next: AsyncBooleanResultCallback): void {
console.log(`async.every/all: ${item}`);
next(undefined as any, item > 0);
}, function(err: Error, result: boolean) {
console.log("async.every/all: done with result", result);
});
// some/any
async.some<number>({
"a": 1,
"b": 2,
"c": 3
}, function(item: number, next: AsyncBooleanResultCallback): void {
console.log(`async.some/any: ${item}`);
next(undefined as any, item > 2);
}, function(err: Error, result: boolean) {
console.log("async.some/any: done with result", result);
});
+77 -57
View File
@@ -1,11 +1,13 @@
// Type definitions for Async 2.0.1
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>, Angus Fenying <https://github.com/fenying>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncWaterfallCallback { (err: Error, ...args: any[]): void; }
interface AsyncBooleanResultCallback { (err: Error, truthValue: boolean): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
@@ -15,7 +17,7 @@ interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number|string, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (err: string, truthValue: boolean) => void): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: AsyncBooleanResultCallback): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
@@ -89,52 +91,74 @@ interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
each<T>(arr: Dictionary<T>, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachSeries: typeof async.each;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
eachLimit<T>(arr: Dictionary<T>, limit: number, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
forEach: typeof async.each;
forEachSeries: typeof async.each;
forEachLimit: typeof async.eachLimit;
forEachOf<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfSeries<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOf<T>(obj: Dictionary<T>, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfSeries: typeof async.forEachOf;
forEachOfLimit<T>(obj: T[], limit: number, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapValuesLimit<T, R>(obj: {[name: string]: T}, limit: number, iteratee: (value: string, key: T, callback: AsyncResultCallback<R>) => void, callback: AsyncResultCallback<R[]>): void;
mapValues<T, R>(obj: {[name: string]: T}, iteratee: (value: string, key: T, callback: AsyncResultCallback<R>) => void, callback: AsyncResultCallback<R[]>): void;
forEachOfLimit<T>(obj: Dictionary<T>, limit: number, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
eachOf: typeof async.forEachOf;
eachOfSeries: typeof async.forEachOf;
eachOfLimit: typeof async.forEachOfLimit;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): void;
map<T, R>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): void;
mapSeries: typeof async.map;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): void;
mapLimit<T, R>(arr: Dictionary<T>, limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): void;
mapValuesLimit<T, R>(obj: Dictionary<T>, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback<R>) => void, callback: AsyncResultCallback<R[]>): void;
mapValues<T, R>(obj: Dictionary<T>, iteratee: (value: T, key: string, callback: AsyncResultCallback<R>) => void, callback: AsyncResultCallback<R[]>): void;
mapValuesSeries: typeof async.mapValues;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): void;
filter<T>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): void;
filterSeries: typeof async.filter;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): void;
filterLimit<T>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): void;
select: typeof async.filter;
selectSeries: typeof async.filter;
selectLimit: typeof async.filterLimit;
reject: typeof async.filter;
rejectSeries: typeof async.filter;
rejectLimit: typeof async.filterLimit;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): void;
inject: typeof async.reduce;
foldl: typeof async.reduce;
reduceRight: typeof async.reduce;
foldr: typeof async.reduce;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): void;
detect<T>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): void;
detectSeries: typeof async.detect;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): void;
detectLimit<T>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): void;
find: typeof async.detect;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
findSeries: typeof async.detectSeries;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
findSeries: typeof async.detect;
findLimit: typeof async.detectLimit;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
anyLimit: typeof async.someLimit;
someSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): void;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
some<T>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
someSeries: typeof async.some;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
someLimit<T>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
any: typeof async.some;
anySeries: typeof async.someSeries;
any<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
anyLimit: typeof async.someLimit;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
every<T>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
everySeries: typeof async.every;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
everyLimit<T>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncBooleanResultCallback): void;
all: typeof async.every;
allSeries: typeof async.every;
allLimit: typeof async.everyLimit;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): void;
concat<T, R>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): void;
concatSeries: typeof async.concat;
// Control Flow
series<T>(tasks: AsyncFunction<T>[], callback?: AsyncResultArrayCallback<T>): void;
@@ -143,14 +167,14 @@ interface Async {
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void;
forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void;
waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void;
during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void;
doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void;
forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void;
waterfall<T>(tasks: Function[], callback?: AsyncResultCallback<T>): void;
compose(...fns: Function[]): Function;
seq(...fns: Function[]): Function;
applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
@@ -158,19 +182,15 @@ interface Async {
queue<T>(worker: AsyncWorker<T>, concurrency?: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo;
auto(tasks: any, concurrency?: number, callback?: (error: Error, results: any) => void): void;
autoInject(tasks: any, callback?: (error: Error, results: any) => void): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: (error: Error, results: any) => void): void;
retry<T>(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
auto(tasks: any, concurrency?: number, callback?: AsyncResultCallback<any>): void;
autoInject(tasks: any, callback?: AsyncResultCallback<any>): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: AsyncResultCallback<any>): void;
retry<T>(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: AsyncResultCallback<any>): void;
retryable<T>(opts: number | {times: number, interval: number}, task: AsyncFunction<T>): AsyncFunction<T>;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function, ...args: any[]): void;
setImmediate: typeof async.nextTick;
allLimit<T>(arr: T[], limit: number, iteratee: AsyncBooleanIterator<T>, cb?: (result: boolean) => any) : any;
everySeries<T>(arr: T[], iteratee: AsyncBooleanIterator<T>, cb?: (result: boolean) => any) : any
allSeries: typeof async.everySeries;
reflect<T>(fn: AsyncFunction<T>) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void;
reflectAll<T>(tasks: AsyncFunction<T>[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[];
+2 -2
View File
@@ -2,8 +2,8 @@
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
+39
View File
@@ -381,3 +381,42 @@ dynamoDBDocClient.query(
else console.log(data); // successful response
}
);
var kinesis = new AWS.Kinesis();
var putRecordParam = {
Data: new Buffer('...') || 'STRING_VALUE', /* required */
PartitionKey: 'STRING_VALUE', /* required */
StreamName: 'STRING_VALUE', /* required */
ExplicitHashKey: 'STRING_VALUE',
SequenceNumberForOrdering: 'STRING_VALUE'
};
kinesis.putRecord(putRecordParam, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
var putRecordParams = {
Records: [ /* required */
{
Data: new Buffer('...') || 'STRING_VALUE', /* required */
PartitionKey: 'STRING_VALUE', /* required */
ExplicitHashKey: 'STRING_VALUE'
},
/* more items */
],
StreamName: 'STRING_VALUE' /* required */
};
kinesis.putRecords(putRecordParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
var increaseStreamRetentionPeriodParams = {
RetentionPeriodHours: 0, /* required */
StreamName: 'STRING_VALUE' /* required */
};
kinesis.increaseStreamRetentionPeriod(increaseStreamRetentionPeriodParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
+87 -2
View File
@@ -1,6 +1,6 @@
// Type definitions for aws-sdk
// Project: https://github.com/aws/aws-sdk-js
// Definitions by: midknight41 <https://github.com/midknight41>
// Definitions by: midknight41 <https://github.com/midknight41>, Casper Skydt <https://github.com/CasperSkydt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts
@@ -335,6 +335,56 @@ export declare class SNS {
publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void;
}
export class Kinesis {
constructor(options?: any);
endpoint: Endpoint;
putRecord(params: KINESIS.PutRecordParams, callback: (error: Error, data: KINESIS.PutRecordResult) => void): void;
putRecords(params: KINESIS.PutRecordsParams, callback: (error: Error, data: KINESIS.PutRecordsResult) => void): void;
increaseStreamRetentionPeriod(params: KINESIS.IncreaseStreamRetentionPeriodParams, callback: (error: Error, data: any) => void): void;
}
export module KINESIS {
export interface Record {
Data: Buffer | string | Blob;
PartitionKey: string;
ExplicitHashKey?: string;
}
export interface RecordResult {
SequenceNumber: string;
ShardId: string;
ErrorCode: string;
ErrorMessage: string;
}
export interface PutRecordParams extends Record {
StreamName: string;
SequenceNumberForOrdering?: string;
}
export interface PutRecordResult {
ShardId: string;
SequenceNumber: string;
}
export interface PutRecordsParams {
StreamName: string;
Records: Record[];
}
export interface PutRecordsResult {
FailedRecordCount: number;
Records: RecordResult[]
}
export interface IncreaseStreamRetentionPeriodParams {
RetentionPeriodHours: number;
StreamName: string;
}
}
export declare class SWF {
constructor(options?: any);
endpoint: Endpoint;
@@ -378,7 +428,8 @@ export declare class S3 {
endpoint: Endpoint;
getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any;
putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void;
putObject(params: s3.PutObjectRequest, callback?: (err: Error, data: any) => void): any;
copyObject(params: s3.CopyObjectRequest, callback?: (err: Error, data: any) => void): any;
deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void;
headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
getSignedUrl(operation: string, params: any): string;
@@ -2253,6 +2304,40 @@ export declare module s3 {
WebsiteRedirectLocation?: string;
}
export interface CopyObjectRequest {
Bucket: string;
CopySource: string;
Key: string;
ACL?: string;
CacheControl?: string;
ContentDisposition?: string;
ContentEncoding?: string;
ContentLanguage?: string;
ContentType?: string;
CopySourceIfMatch?: string;
CopySourceIfModifiedSince?: any;
CopySourceIfNoneMatch?: string;
CopySourceIfUnmodifiedSince?: any;
CopySourceSSECustomerAlgorithm?: string;
CopySourceSSECustomerKey?: any;
CopySourceSSECustomerKeyMD5?: string;
Expires?: any;
GrantFullControl?: string;
GrantRead?: string;
GrantReadACP?: string;
GrantWriteACP?: string;
Metadata?: { [key: string]: string; };
MetadataDirective?: string;
RequestPayer?: string;
SSECustomerAlgorithm?: string;
SSECustomerKey?: any;
SSECustomerKeyMD5?: string;
SSEKMSKeyId?: string;
ServerSideEncryption?: string;
StorageClass?: string;
WebsiteRedirectLocation?: string;
}
export interface GetObjectRequest {
Bucket: string;
IfMatch?: string;
+24
View File
@@ -0,0 +1,24 @@
/// <reference path="./index.d.ts" />
import * as aws4 from ".";
let requestSigner = new aws4.RequestSigner({}, {});
requestSigner.matchHost("");
requestSigner.isSingleRegion();
requestSigner.createHost();
requestSigner.prepareRequest();
requestSigner.sign();
requestSigner.getDateTime();
requestSigner.getDate();
requestSigner.authHeader();
requestSigner.signature();
requestSigner.stringToSign();
requestSigner.canonicalString();
requestSigner.canonicalHeaders();
requestSigner.signedHeaders();
requestSigner.credentialString();
requestSigner.defaultCredentials();
requestSigner.parsePath();
requestSigner.formatPath();
aws4.sign({}, {});
+33
View File
@@ -0,0 +1,33 @@
// Type definitions for aws4 1.5.0
// Project: https://github.com/mhart/aws4
// Definitions by: Andrew Crites <https://github.com/ajcrites>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class RequestSigner {
constructor(request?: any, credentials?: any);
request: any;
credentials: any;
service: any;
region: any;
isCodeCommitGit: any;
matchHost(host?: string): string;
isSingleRegion(): boolean;
createHost(): string;
prepareRequest(): void;
sign(): any;
getDateTime(): string;
getDate(): string;
authHeader(): string;
signature(): string;
stringToSign(): string;
canonicalString(): string;
canonicalHeaders(): string;
signedHeaders(): string;
credentialString(): string;
defaultCredentials(): any;
parsePath(): any;
formatPath(): string;
}
export function sign(options?: any, credentials?: any): RequestSigner;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"aws4-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
import ponyBind = require('bind-ponyfill');
let boundFn: Function;
boundFn = ponyBind(() => { console.log(this); }, 'Hello world!');
boundFn = ponyBind((...args: Array<string>) => { console.log(this, ...args); }, 'Hello world!', 'arg1');
boundFn = ponyBind((...args: Array<string>) => { console.log(this, ...args); }, 'Hello world!', 'arg1', 'arg2');
boundFn = ponyBind((arg1: string, arg2: number) => { console.log(this, arg1, arg2); }, 'Hello world!', 'arg1', 2);
+7
View File
@@ -0,0 +1,7 @@
// Type definitions for bind-ponyfill 0.1.0
// Project: https://www.npmjs.com/package/bind-ponyfill
// Definitions by: Steve Jenkins <https://github.com/skysteve>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function ponyBind(fn: Function, that: any, ...args: Array<any>): Function;
export = ponyBind;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bind-ponyfill-tests.ts"
]
}
+6 -1
View File
@@ -12,7 +12,7 @@
* “w” (week), “m” (month), and “y” (year).
*
* See online docs for more info:
* http://bootstrap-datepicker.readthedocs.org/en/release/options.html
* https://bootstrap-datepicker.readthedocs.io/en/latest/options.html
*/
interface DatepickerOptions {
format?: string | DatepickerCustomFormatOptions;
@@ -37,6 +37,11 @@ interface DatepickerOptions {
orientation?: string;
assumeNearbyYear?: any;
viewMode?: string;
templates?: any;
zIndexOffset?: number;
showOnFocus?: boolean;
immediateUpdates?: boolean;
title?: string;
}
interface DatepickerCustomFormatOptions {
@@ -0,0 +1,40 @@
/// <reference types="jquery"/>
$(".selectpicker").selectpicker({
actionsBox: true,
container: "body",
countSelectedText: "counts > #",
deselectAllText: "test",
dropdownAlignRight: true,
dropupAuto: true,
header: "test",
hideDisabled: true,
iconBase: "fa",
liveSearch: true,
liveSearchNormalize: true,
liveSearchPlaceholder: "test",
liveSearchStyle: "contains",
maxOptions: 10,
maxOptionsText: "test",
mobile: true,
multipleSeparator: ", ",
noneSelectedText: "test",
selectAllText: "test",
selectedTextFormat: "values",
selectOnTab: true,
showContent: true,
showIcon: true,
showSubtext: true,
showTick: true,
size: "auto",
style: "test",
tickIcon: "test",
title: "test",
width: "auto"
})
$(".selectpicker").selectpicker("val", "foo")
$(".selectpicker").selectpicker("val", ["foo", "bar"])
$(".selectpicker").selectpicker("selectAll")
$(".selectpicker").selectpicker("setStyle", "btn-large", "add")
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for bootstrap-select v1.11.2
// Project: https://silviomoreto.github.io/bootstrap-select/
// Definitions by: Karol Janyst <https://github.com/LKay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery"/>
interface BootstrapSelectOptions {
actionsBox?: boolean
container?: string | boolean
countSelectedText?: string | Function
deselectAllText?: string
dropdownAlignRight?: string | boolean
dropupAuto?: boolean
header?: string
hideDisabled?: boolean
iconBase?: string
liveSearch?: boolean
liveSearchNormalize?: boolean
liveSearchPlaceholder?: string
liveSearchStyle?: string
maxOptions?: number | boolean
maxOptionsText?: string | Array<any> | Function
mobile?: boolean
multipleSeparator?: string
noneSelectedText?: string
selectAllText?: string
selectedTextFormat?: string
selectOnTab?: boolean
showContent?: boolean
showIcon?: boolean
showSubtext?: boolean
showTick?: boolean
size?: string | number | boolean
style?: string
tickIcon?: string
title?: string
width?: string | boolean
}
interface JQuery {
selectpicker(opts?: BootstrapSelectOptions): void
selectpicker(method: string, ...args: Array<string | Array<string>>): void
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bootstrap-select-tests.ts"
]
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": false,
"baseUrl": "../",
+1
View File
@@ -26,6 +26,7 @@ level = bunyan.resolveLevel(bunyan.FATAL);
var options:bunyan.LoggerOptions = {
name: 'test-logger',
serializers: bunyan.stdSerializers,
streams: [{
type: 'stream',
stream: process.stdout,
+2 -2
View File
@@ -21,7 +21,7 @@ declare class Logger extends EventEmitter {
levels(name: number | string, value: number | string): void;
fields: any;
src:boolean;
src:boolean;
trace(error: Error, format?: any, ...params: any[]): void;
trace(buffer: Buffer, format?: any, ...params: any[]): void;
@@ -54,7 +54,7 @@ interface LoggerOptions {
streams?: Stream[];
level?: string | number;
stream?: NodeJS.WritableStream;
serializers?: Serializers;
serializers?: Serializers | StdSerializers;
src?: boolean;
}
+1 -2
View File
@@ -1,4 +1,3 @@
import {
connect,
Document as CamoDocument,
@@ -16,7 +15,7 @@ connect("mongodb://user:password@localhost:27017/database?authSource=admin").the
dateCreated?: Date;
}
class User extends CamoDocument {
class User extends CamoDocument<UserSchema> {
private name: SchemaTypeExtended = String;
private password: SchemaTypeExtended = String;
private friends: SchemaTypeExtended = [String];
+312 -127
View File
@@ -1,137 +1,322 @@
// Type definitions for camo v0.11.4
// Type definitions for camo v0.12.2
// Project: https://github.com/scottwrobinson/camo
// Definitions by: Lucas Matías Ciruzzi <https://github.com/lucasmciruzzi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "camo" {
/**
* Connect function
*
* @export
* @param {string} uri Connection URI
* @returns {Promise<any>}
*/
export function connect (uri: string): Promise<any>;
type TypeOrArray<Type> = Type | Type[];
type TypeOrArrayOfType<Type> = Type | Type[];
/**
* Supported type constructors for document properties
*/
export type SchemaTypeConstructor =
TypeOrArray<StringConstructor> |
TypeOrArray<NumberConstructor> |
TypeOrArray<BooleanConstructor> |
TypeOrArray<DateConstructor> |
TypeOrArray<ObjectConstructor> |
TypeOrArray<ArrayConstructor>;
/**
* Supported type constructors for document properties
*/
export type SchemaTypeConstructor =
TypeOrArrayOfType<StringConstructor> |
TypeOrArrayOfType<NumberConstructor> |
TypeOrArrayOfType<BooleanConstructor> |
TypeOrArrayOfType<ArrayBufferConstructor> |
TypeOrArrayOfType<DateConstructor> |
TypeOrArrayOfType<ObjectConstructor> |
TypeOrArrayOfType<ArrayConstructor>;
/**
* Supported types for document properties
*/
export type SchemaType = TypeOrArray<string | number | boolean | Date | Object>;
/**
* Supported types for document properties
*/
export type SchemaType = TypeOrArrayOfType<string | number | boolean | Date | Object>;
/**
* Document property with options
*/
export interface SchemaTypeOptions<Type> {
/**
* Type of data
*/
type: SchemaTypeConstructor;
/**
* Default value
*/
default?: Type;
/**
* Min value (only with Number)
*/
min?: number;
/**
* Max value (only with Number)
*/
max?: number;
/**
* Posible options
*/
choices?: Type[];
/**
* RegEx to match value
*/
match?: RegExp;
/**
* Validation function.
*
* @param {Type} value Value taken.
* @returns {boolean} true (validation ok) or false (validation wrong).
*/
validate?(value: Type): boolean;
/**
* Unique value (like ids)
*/
unique?: boolean;
/**
* Required field
*/
required?: boolean;
}
/**
* Document property type or options
*/
export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions<SchemaType>;
/**
* Schema passed to Document.create()
*/
export interface DocumentSchema {
/**
* Index signature
*/
[property: string]: SchemaType;
/**
* Document id
*/
_id?: string;
}
/**
* findOneAndUpdate method options.
*
* @interface findOneAndUpdateOptions
*/
export interface FindOneAndUpdateOptions {
/**
* Return a new document if one is not found with the given query.
*
* @type {boolean}
*/
upsert?: boolean;
}
/**
* findOne method options.
*
* @interface FindOneOptions
*/
export interface FindOneOptions {
/**
* Find all or no references.
* Pass an array of field names to only populate the specified references.
*
* @type {(boolean | string[])}
*/
populate?: boolean | string[];
}
/**
* find method options.
*
* @interface FindOptions
*/
export interface FindOptions {
/**
* Find all or no references.
* Pass an array of field names to only populate the specified references.
*
* @type {(boolean | string[])}
*/
populate?: boolean | string[];
/**
* Sort the documents by the given field(s).
*
* @type {TypeOrArrayOfType<string>}
*/
sort?: TypeOrArrayOfType<string>;
/**
* Limits the number of documents returned.
*
* @type {number}
*/
limit?: number;
/**
* Skips the given number of documents and returns the rest.
*
* @type {number}
*/
skip?: number;
}
/**
* Camo document
*/
export class Document<Schema extends DocumentSchema> {
/**
* Index signature
*/
[property: string]: SchemaTypeExtended | string | Document<any> | Function;
/**
* Static method to define the collection name.
*
* @protected
* @static
* @returns {string} The collection name.
*/
protected static collectionName(): string;
/**
* Sets the schema (to be used on the constructor).
*
* @protected
* @template Schema
* @param {Schema} schema
*/
protected schema<Schema>(schema: Schema): void;
/**
* Creates a camo document instance.
*
* @static
* @template StaticSchema
* @param {StaticSchema} schema Base schema to create a document.
* @returns {DocumentInstance<StaticSchema>} A camo document instance.
*/
public static create<StaticSchema extends DocumentSchema>(schema: StaticSchema): Document<StaticSchema>;
/**
* Saves the document instance to the database.
*
* @returns {Promise<Schema>}
*/
public save(): Promise<Schema>;
/**
* Return the first document found, even if multiple documents match the query.
*
* @static
* @template StaticSchema
* @param {*} query Find query.
* @param {FindOneOptions} options findOne method options.
* @returns {Promise<StaticSchema>}
*/
public static findOne<StaticSchema extends DocumentSchema>(query: any, options?: FindOneOptions): Promise<StaticSchema>;
/**
* Return all documents matching the query.
*
* @static
* @template StaticSchema
* @param {*} query Find query.
* @param {FindOptions} options
* @returns {Promise<StaticSchema>}
*/
public static find<StaticSchema extends DocumentSchema>(query: any, options?: FindOptions): Promise<StaticSchema[]>;
/**
* Find and update (or insert) a document in one atomic operation (atomic for MongoDB only).
*
* @static
* @template StaticSchema
* @param {*} query Find query.
* @param {Schema} values Values to set.
* @param {FindOneAndUpdateOptions} options findOneAndUpdate method options.
* @returns {Promise<StaticSchema>}
*/
public static findOneAndUpdate<StaticSchema extends DocumentSchema>(query: any, values: StaticSchema, options?: FindOneAndUpdateOptions): Promise<StaticSchema>;
/**
* Removes documents from the database.
* Should only be used on an instantiated document with a valid id.
*
* @returns {Promise<number>} Number of deleted documents.
*/
public delete(): Promise<number>;
/**
* Removes the first document found, even if multiple documents match the query.
*
* @static
* @param {*} query Delete query.
* @returns {Promise<number>} Number of deleted documents.
*/
public static deleteOne(query: any): Promise<number>;
/**
* Removes all documents matching the query.
*
* @static
* @param {*} query Delete query.
* @returns {Promise<number>} Number of deleted documents.
*/
public static deleteMany(query: any): Promise<number>;
/**
* Find the first document and delete it.
*
* @static
* @param {*} query Delete query.
* @param {*} options Database Options for findOneAndDelete method.
* @returns {Promise<number>} Number of deleted documents.
*/
public static findOneAndDelete(query: any, options?: any): Promise<number>;
/**
* Number of matching documents without retrieving all the data.
*
* @static
* @param {*} query Count query.
* @returns {Promise<number>}
*/
public static count(query: any): Promise<number>;
/**
* pre-validate hook.
*
* @protected
* @returns {Promise<any>}
*/
protected preValidate(): Promise<any>;
/**
* post-validate hook.
*
* @protected
* @returns {Promise<any>}
*/
protected postValidate(): Promise<any>;
/**
* pre-save hook.
*
* @protected
* @returns {Promise<any>}
*/
protected preSave(): Promise<any>;
/**
* post-save hook.
*
* @protected
* @returns {Promise<any>}
*/
protected postSave(): Promise<any>;
/**
* pre-delete hook.
*
* @protected
* @returns {Promise<any>}
*/
protected preDelete(): Promise<any>;
/**
* post-delete hook.
*
* @protected
* @returns {Promise<any>}
*/
protected postDelete(): Promise<any>;
/**
* Serialized document to just the data, which includes nested and referenced data.
*
* @returns {*}
*/
public toJSON(): any;
}
/**
* Document property with options
*/
export interface SchemaTypeOptions<Type> {
/**
* Type of data
*/
type: SchemaTypeConstructor;
/**
* Default value
*/
default?: Type;
/**
* Min value (only with Number)
*/
min?: number;
/**
* Max value (only with Number)
*/
max?: number;
/**
* Posible options
*/
choices?: Type[];
/**
* RegEx to match value
*/
match?: RegExp;
/**
* Validation function
*
* @param value Value taken
* @returns true (validation ok) or false (validation wrong)
*/
validate?(value: Type): boolean;
/**
* Unique value (like ids)
*/
unique?: boolean;
/**
* Required field
*/
required?: boolean;
}
/**
* Document property type or options
*/
export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions<SchemaType>;
/**
* Schema passed to Document.create()
*/
interface DocumentSchema {
/**
* Index signature
*/
[property: string]: SchemaType;
/**
* Document id
*/
_id?: string;
}
/**
* Camo document instance
*/
declare class DocumentInstance<Schema extends DocumentSchema> {
public save(): Promise<Schema>;
public loadOne(): Promise<Schema>;
public loadMany(): Promise<Schema>;
public delete(): Promise<Schema>;
public deleteOne(): Promise<Schema>;
public deleteMany(): Promise<Schema>;
public loadOneAndDelete(): Promise<Schema>;
public count(): Promise<Schema>;
public preValidate(): Promise<Schema>;
public postValidate(): Promise<Schema>;
public preSave(): Promise<Schema>;
public postSave(): Promise<Schema>;
public preDelete(): Promise<Schema>;
public postDelete(): Promise<Schema>;
}
/**
* Camo document
*/
export declare class Document {
/**
* Index signature
*/
[property: string]: SchemaTypeExtended | string | DocumentInstance<any>;
/**
* Static method to define the collection name
*
* @returns The collection name
*/
static collectionName(): string;
/**
* Creates a camo document instance
*
* @returns A camo document instance
*/
static create<Schema extends DocumentSchema>(schema: Schema): DocumentInstance<Schema>;
}
/**
* Connect function
*
* @param uri Connection URI
*/
export declare function connect(uri: string): Promise<any>;
+2 -2
View File
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": false,
"baseUrl": "../",
@@ -14,6 +14,6 @@
},
"files": [
"index.d.ts",
"cassandra-driver.tests.ts"
"cassandra-driver-tests.ts"
]
}
+135
View File
@@ -0,0 +1,135 @@
/// <reference types="chai" />
/// <reference types="mocha" />
import * as chai from 'chai';
import * as spies from 'chai-spies';
import * as Mocha from 'mocha';
function original(): void {
// do something cool
}
let ee = {
on(name: string, fn: () => void) {
}
};
let spiedFn = chai.spy(original);
// then use in place of original
ee.on('some event', spiedFn);
// or use without original
let spy_again = chai.spy();
ee.on('some other event', spy_again);
// or you can track an object's method
let array = [ 1, 2, 3 ];
chai.spy.on(array, 'push');
// or you can track multiple object's methods
chai.spy.on(array, 'push', 'pop');
array.push(5);
// and you can reset the object calls
// array.push.reset();
// or you can create spy object
let object = chai.spy.object([ 'push', 'pop' ]);
object.push(5);
// or you create spy which returns static value
spiedFn = chai.spy.returns(true);
spiedFn(); // true
let should = chai.should()
, expect = chai.expect;
const spy = chai.spy();
// .spy
expect(spy).to.be.spy;
spy.should.be.spy;
// .called
expect(spy).to.have.been.called();
spy.should.have.been.called();
// .with
const spyStringArg = chai.spy((arg: string) => arg);
spyStringArg('foo');
expect(spyStringArg).to.have.been.called.with('foo');
spyStringArg.should.have.been.called.with('foo');
const spyTwoStringArgsAndOneNumber = chai.spy((arg1: string, arg2: string, arg3: number) => arg3);
spyTwoStringArgsAndOneNumber('foo', 'bar', 1);
expect(spyTwoStringArgsAndOneNumber).to.have.been.called.with('bar', 'foo');
spyTwoStringArgsAndOneNumber.should.have.been.called.with('bar', 'foo');
// .with.exactly
const spyTwoStringArgs = chai.spy((arg1: string, arg2: string) => arg1);
spyTwoStringArgs('', '');
spyTwoStringArgs('foo', 'bar');
expect(spyTwoStringArgs).to.have.been.called.with.exactly('foo', 'bar');
spyTwoStringArgs.should.have.been.called.with.exactly('foo', 'bar');
// .always.with
const spyThreeAnyArgs = chai.spy((arg1: any, arg2: any, arg3: any) => arg1);
spyThreeAnyArgs('foo', null, null);
spyThreeAnyArgs('foo', 'bar', null);
spyThreeAnyArgs(1, 2, 'foo');
expect(spy).to.have.been.called.always.with('foo');
spy.should.have.been.called.always.with('foo');
// .always.with.exactly
spyStringArg('foo');
spyStringArg('foo');
expect(spyStringArg).to.have.been.called.always.with.exactly('foo');
spyStringArg.should.have.been.called.always.with.exactly('foo');
// .once
expect(spy).to.have.been.called.once;
expect(spy).to.not.have.been.called.once;
spy.should.have.been.called.once;
spy.should.not.have.been.called.once;
// .twice
expect(spy).to.have.been.called.twice;
expect(spy).to.not.have.been.called.twice;
spy.should.have.been.called.twice;
spy.should.not.have.been.called.twice;
// .exactly(n)
expect(spy).to.have.been.called.exactly(3);
expect(spy).to.not.have.been.called.exactly(3);
spy.should.have.been.called.exactly(3);
spy.should.not.have.been.called.exactly(3);
// .min(n) / .at.least(n)
expect(spy).to.have.been.called.min(3);
expect(spy).to.not.have.been.called.at.least(3);
spy.should.have.been.called.at.least(3);
spy.should.not.have.been.called.min(3);
// .max(n) / .at.most(n)
expect(spy).to.have.been.called.max(3);
expect(spy).to.not.have.been.called.at.most(3);
spy.should.have.been.called.at.most(3);
spy.should.not.have.been.called.max(3);
// .above(n) / .gt(n)
expect(spy).to.have.been.called.above(3);
expect(spy).to.not.have.been.called.gt(3);
spy.should.have.been.called.gt(3);
spy.should.not.have.been.called.above(3);
// .below(n) / .lt(n)
expect(spy).to.have.been.called.below(3);
expect(spy).to.not.have.been.called.lt(3);
spy.should.have.been.called.lt(3);
spy.should.not.have.been.called.below(3);
+411
View File
@@ -0,0 +1,411 @@
// Type definitions for chai-spies
// Project: https://github.com/chaijs/chai-spies
// Definitions by: Ilya Kuznetsov <https://github.com/kuzn-ilya>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="chai" />
declare namespace Chai {
interface ChaiStatic {
spy: ChaiSpies.Spy;
}
interface Assertion {
/**
* ####.spy
* Asserts that object is a spy.
* ```ts
* expect(spy).to.be.spy;
* spy.should.be.spy;
* ```
*/
spy: Assertion;
/**
* ####.called
* Assert that a spy has been called. Negation passes through.
* ```ts
* expect(spy).to.have.been.called();
* spy.should.have.been.called();
* ```
* Note that ```called``` can be used as a chainable method.
*/
called: ChaiSpies.Called;
}
}
declare namespace ChaiSpies {
interface Spy {
/**
* #### chai.spy (function)
*
* Wraps a function in a proxy function. All calls will pass through to the original function.
* ```ts
* function original() {}
* var spy = chai.spy(original)
* , e_spy = chai.spy();
* ```
* @param fn function to spy on. @default ```function () {}```
* @returns function to actually call
*/
(): SpyFunc0Proxy<void>;
<R>(fn: SpyFunc0<R>): SpyFunc0Proxy<R>;
<A1, R>(fn: SpyFunc1<A1, R>): SpyFunc1Proxy<A1, R>;
<A1, A2, R>(fn: SpyFunc2<A1, A2, R>): SpyFunc2Proxy<A1, A2, R>;
<A1, A2, A3, R>(fn: SpyFunc3<A1, A2, A3, R>): SpyFunc3Proxy<A1, A2, A3, R>;
<A1, A2, A3, A4, R>(fn: SpyFunc4<A1, A2, A3, A4, R>): SpyFunc4Proxy<A1, A2, A3, A4, R>;
<A1, A2, A3, A4, A5, R>(fn: SpyFunc5<A1, A2, A3, A4, A5, R>): SpyFunc5Proxy<A1, A2, A3, A4, A5, R>;
<A1, A2, A3, A4, A5, A6, R>(fn: SpyFunc6<A1, A2, A3, A4, A5, A6, R>): SpyFunc6Proxy<A1, A2, A3, A4, A5, A6, R>;
<A1, A2, A3, A4, A5, A6, A7, R>(fn: SpyFunc7<A1, A2, A3, A4, A5, A6, A7, R>): SpyFunc7Proxy<A1, A2, A3, A4, A5, A6, A7, R>;
<A1, A2, A3, A4, A5, A6, A7, A8, R>(fn: SpyFunc8<A1, A2, A3, A4, A5, A6, A7, A8, R>): SpyFunc8Proxy<A1, A2, A3, A4, A5, A6, A7, A8, R>;
<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>(fn: SpyFunc9<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>): SpyFunc9Proxy<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>;
<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>(fn: SpyFunc10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>): SpyFunc10Proxy<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>;
<R>(name: string, fn: SpyFunc0<R>): SpyFunc0Proxy<R>;
<A1, R>(name: string, fn: SpyFunc1<A1, R>): SpyFunc1Proxy<A1, R>;
<A1, A2, R>(name: string, fn: SpyFunc2<A1, A2, R>): SpyFunc2Proxy<A1, A2, R>;
<A1, A2, A3, R>(name: string, fn: SpyFunc3<A1, A2, A3, R>): SpyFunc3Proxy<A1, A2, A3, R>;
<A1, A2, A3, A4, R>(name: string, fn: SpyFunc4<A1, A2, A3, A4, R>): SpyFunc4Proxy<A1, A2, A3, A4, R>;
<A1, A2, A3, A4, A5, R>(name: string, fn: SpyFunc5<A1, A2, A3, A4, A5, R>): SpyFunc5Proxy<A1, A2, A3, A4, A5, R>;
<A1, A2, A3, A4, A5, A6, R>(name: string, fn: SpyFunc6<A1, A2, A3, A4, A5, A6, R>): SpyFunc6Proxy<A1, A2, A3, A4, A5, A6, R>;
<A1, A2, A3, A4, A5, A6, A7, R>(name: string, fn: SpyFunc7<A1, A2, A3, A4, A5, A6, A7, R>): SpyFunc7Proxy<A1, A2, A3, A4, A5, A6, A7, R>;
<A1, A2, A3, A4, A5, A6, A7, A8, R>(name: string, fn: SpyFunc8<A1, A2, A3, A4, A5, A6, A7, A8, R>): SpyFunc8Proxy<A1, A2, A3, A4, A5, A6, A7, A8, R>;
<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>(name: string, fn: SpyFunc9<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>): SpyFunc9Proxy<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>;
<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>(name: string, fn: SpyFunc10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>): SpyFunc10Proxy<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>;
/**
* #### chai.spy.on (function)
*
* Wraps an object method into spy. All calls will pass through to the original function.
* ```ts
* var spy = chai.spy.on(Array, 'isArray');
* ```
* @param {Object} object
* @param {String} method name to spy on
* @returns function to actually call
*/
on(object: Object, ...methodNames: string[]): any;
/**
* #### chai.spy.object (function)
*
* Creates an object with spied methods.
* ```ts
* var object = chai.spy.object('Array', [ 'push', 'pop' ]);
* ```
* @param {String} [name] object name
* @param {String[]|Object} method names or method definitions
* @returns object with spied methods
*/
object(name: string, methods: string[]): any;
object(methods: string[]): any;
object<T>(name: string, methods: T): T;
object<T>(methods: T): T;
/**
* #### chai.spy.returns (function)
*
* Creates a spy which returns static value.
*```ts
* var method = chai.spy.returns(true);
*```
* @param {*} value static value which is returned by spy
* @returns new spy function which returns static value
* @api public
*/
returns<T>(value: T): SpyFunc0Proxy<T>;
}
interface Called {
(): Chai.Assertion;
with: With;
always: Always;
/**
* ####.once
* Assert that a spy has been called exactly once.
* ```ts
* expect(spy).to.have.been.called.once;
* expect(spy).to.not.have.been.called.once;
* spy.should.have.been.called.once;
* spy.should.not.have.been.called.once;
* ```
*/
once: Chai.Assertion;
/**
* ####.twice
* Assert that a spy has been called exactly twice.
* ```ts
* expect(spy).to.have.been.called.twice;
* expect(spy).to.not.have.been.called.twice;
* spy.should.have.been.called.twice;
* spy.should.not.have.been.called.twice;
* ```
*/
twice: Chai.Assertion;
/**
* ####.exactly(n)
* Assert that a spy has been called exactly ```n``` times.
* ```ts
* expect(spy).to.have.been.called.exactly(3);
* expect(spy).to.not.have.been.called.exactly(3);
* spy.should.have.been.called.exactly(3);
* spy.should.not.have.been.called.exactly(3);
* ```
*/
exactly(n: number): Chai.Assertion;
/**
* ####.min(n) / .at.least(n)
* Assert that a spy has been called minimum of ```n``` times.
* ```ts
* expect(spy).to.have.been.called.min(3);
* expect(spy).to.not.have.been.called.at.least(3);
* spy.should.have.been.called.at.least(3);
* spy.should.not.have.been.called.min(3);
* ```
*/
min(n: number): Chai.Assertion;
/**
* ####.max(n) / .at.most(n)
* Assert that a spy has been called maximum of ```n``` times.
* ```ts
* expect(spy).to.have.been.called.max(3);
* expect(spy).to.not.have.been.called.at.most(3);
* spy.should.have.been.called.at.most(3);
* spy.should.not.have.been.called.max(3);
* ```
*/
max(n: number): Chai.Assertion;
at: At;
/**
* ####.above(n) / .gt(n)
* Assert that a spy has been called more than ```n``` times.
* ```ts
* expect(spy).to.have.been.called.above(3);
* spy.should.not.have.been.called.above(3);
* ```
*/
above(n: number): Chai.Assertion;
/**
* ####.above(n) / .gt(n)
* Assert that a spy has been called more than ```n``` times.
* ```ts
* expect(spy).to.have.been.called.gt(3);
* spy.should.not.have.been.called.gt(3);
* ```
*/
gt(n: number): Chai.Assertion;
/**
* ####.below(n) / .lt(n)
* Assert that a spy has been called fewer than ```n``` times.
* ```ts
* expect(spy).to.have.been.called.below(3);
* spy.should.not.have.been.called.below(3);
* ```
*/
below(n: number): Chai.Assertion;
/**
* ####.below(n) / .lt(n)
* Assert that a spy has been called fewer than ```n``` times.
* ```ts
* expect(spy).to.have.been.called.lt(3);
* spy.should.not.have.been.called.lt(3);
* ```
*/
lt(n: number): Chai.Assertion;
}
interface With {
/**
* ####.with
* Assert that a spy has been called with a given argument at least once, even if more arguments were provided.
* ```ts
* spy('foo');
* expect(spy).to.have.been.called.with('foo');
* spy.should.have.been.called.with('foo');
* ```
* Will also pass for ```spy('foo', 'bar')``` and ```spy(); spy('foo')```.
* If used with multiple arguments, assert that a spy has been called with all the given arguments at least once.
* ```ts
* spy('foo', 'bar', 1);
* expect(spy).to.have.been.called.with('bar', 'foo');
* spy.should.have.been.called.with('bar', 'foo');
* ```
*/
(a: any, b?: any, c?: any, d?: any, e?: any, f?: any, g?: any, h?: any, i?: any, j?: any): Chai.Assertion;
/**
* ####.with.exactly
* Similar to .with, but will pass only if the list of arguments is exactly the same as the one provided.
* ```ts
* spy();
* spy('foo', 'bar');
* expect(spy).to.have.been.called.with.exactly('foo', 'bar');
* spy.should.have.been.called.with.exactly('foo', 'bar');
* ```
* Will not pass for ```spy('foo')```, ```spy('bar')```, ```spy('bar'); spy('foo')```, ```spy('foo'); spy('bar')```, ```spy('bar', 'foo')``` or ```spy('foo', 'bar', 1)```.
* Can be used for calls with a single argument too.
*/
exactly(a?: any, b?: any, c?: any, d?: any, e?: any, f?: any, g?: any, h?: any, i?: any, j?: any): Chai.Assertion;
}
interface Always {
with: AlwaysWith;
}
interface AlwaysWith {
/**
* ####.always.with
* Assert that every time the spy has been called the argument list contained the given arguments.
* ```ts
* spy('foo');
* spy('foo', 'bar');
* spy(1, 2, 'foo');
* expect(spy).to.have.been.called.always.with('foo');
* spy.should.have.been.called.always.with('foo');
* ```
*/
(a: any, b?: any, c?: any, d?: any, e?: any, f?: any, g?: any, h?: any, i?: any, j?: any): Chai.Assertion;
/**
* ####.always.with.exactly
* Assert that the spy has never been called with a different list of arguments than the one provided.
* ```ts
* spy('foo');
* spy('foo');
* expect(spy).to.have.been.called.always.with.exactly('foo');
* spy.should.have.been.called.always.with.exactly('foo');
* ```
*/
exactly(a?: any, b?: any, c?: any, d?: any, e?: any, f?: any, g?: any, h?: any, i?: any, j?: any): Chai.Assertion;
}
interface At {
/**
* ####.min(n) / .at.least(n)
* Assert that a spy has been called minimum of ```n``` times.
* ```ts
* expect(spy).to.have.been.called.min(3);
* expect(spy).to.not.have.been.called.at.least(3);
* spy.should.have.been.called.at.least(3);
* spy.should.not.have.been.called.min(3);
* ```
*/
least(n: number): Chai.Assertion;
/**
* ####.max(n) / .at.most(n)
* Assert that a spy has been called maximum of ```n``` times.
* ```ts
* expect(spy).to.have.been.called.max(3);
* expect(spy).to.not.have.been.called.at.most(3);
* spy.should.have.been.called.at.most(3);
* spy.should.not.have.been.called.max(3);
* ```
*/
most(n: number): Chai.Assertion;
}
interface Resetable {
/**
* #### proxy.reset (function)
*
* Resets __spy object parameters for instantiation and reuse
* @returns proxy spy object
*/
reset(): this;
}
interface SpyFunc0<R> {
(): R;
}
interface SpyFunc1<A1, R> {
(a: A1): R;
}
interface SpyFunc2<A1, A2, R> {
(a: A1, b: A2): R;
}
interface SpyFunc3<A1, A2, A3, R> {
(a: A1, b: A2, c: A3): R;
}
interface SpyFunc4<A1, A2, A3, A4, R> {
(a: A1, b: A2, c: A3, d: A4): R;
}
interface SpyFunc5<A1, A2, A3, A4, A5, R> {
(a: A1, b: A2, c: A3, d: A4, e: A5): R;
}
interface SpyFunc6<A1, A2, A3, A4, A5, A6, R> {
(a: A1, b: A2, c: A3, d: A4, e: A5, f: A6): R;
}
interface SpyFunc7<A1, A2, A3, A4, A5, A6, A7, R> {
(a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7): R;
}
interface SpyFunc8<A1, A2, A3, A4, A5, A6, A7, A8, R> {
(a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8): R;
}
interface SpyFunc9<A1, A2, A3, A4, A5, A6, A7, A8, A9, R> {
(a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8, i: A9): R;
}
interface SpyFunc10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R> {
(a: A1, b: A2, c: A3, d: A4, e: A5, f: A6, g: A7, h: A8, i: A9, j: A10): R;
}
interface SpyFunc0Proxy<R> extends SpyFunc0<R>, Resetable {
}
interface SpyFunc1Proxy<A1, R> extends SpyFunc1<A1, R>, Resetable {
}
interface SpyFunc2Proxy<A1, A2, R> extends SpyFunc2<A1, A2, R>, Resetable {
}
interface SpyFunc3Proxy<A1, A2, A3, R> extends SpyFunc3<A1, A2, A3, R>, Resetable {
}
interface SpyFunc4Proxy<A1, A2, A3, A4, R> extends SpyFunc4<A1, A2, A3, A4, R>, Resetable {
}
interface SpyFunc5Proxy<A1, A2, A3, A4, A5, R> extends SpyFunc5<A1, A2, A3, A4, A5, R>, Resetable {
}
interface SpyFunc6Proxy<A1, A2, A3, A4, A5, A6, R> extends SpyFunc6<A1, A2, A3, A4, A5, A6, R>, Resetable {
}
interface SpyFunc7Proxy<A1, A2, A3, A4, A5, A6, A7, R> extends SpyFunc7<A1, A2, A3, A4, A5, A6, A7, R>, Resetable {
}
interface SpyFunc8Proxy<A1, A2, A3, A4, A5, A6, A7, A8, R> extends SpyFunc8<A1, A2, A3, A4, A5, A6, A7, A8, R>, Resetable {
}
interface SpyFunc9Proxy<A1, A2, A3, A4, A5, A6, A7, A8, A9, R> extends SpyFunc9<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>, Resetable {
}
interface SpyFunc10Proxy<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R> extends SpyFunc10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R>, Resetable {
}
}
declare var spies: ChaiSpies.Spy;
declare module "chai-spies" {
export = spies;
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"chai-spies-tests.ts"
]
}
+8 -2
View File
@@ -5,13 +5,19 @@
declare namespace Chance {
interface Seeded {
seed: number;
}
type SeededChance = Chance & Seeded;
interface ChanceStatic {
(): Chance
(seed: number): Chance
(seed: number): SeededChance
(generator: () => any): Chance
new(): Chance;
new(seed: number): Chance;
new(seed: number): SeededChance;
new(generator: () => any): Chance;
}
+1 -1
View File
@@ -392,7 +392,7 @@ interface RadialLinearScale {
}
declare class Chart {
constructor (context: CanvasRenderingContext2D, options: ChartConfiguration);
constructor (context: CanvasRenderingContext2D | HTMLCanvasElement, options: ChartConfiguration);
config: ChartConfiguration;
destroy: () => {};
update: (duration?: any, lazy?: any) => {};
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Dave Keen <http://www.keendevelopment.ch>, Adi Dahiya <https://github.com/adidahiya>, Jason Killian <https://github.com/JKillian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null;
declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false;
interface ClassDictionary {
[id: string]: boolean | undefined | null;
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Clipboard from 'clipboard';
var cb1 = new Clipboard('.btn');
var cb2 = new Clipboard(document.getElementById('id'), {
+50 -48
View File
@@ -3,54 +3,56 @@
// Definitions by: Andrei Kurosh <https://github.com/impworks>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class Clipboard {
constructor(selector: (string | Element | NodeListOf<Element>), options?: ClipboardOptions);
/**
* Subscribes to events that indicate the result of a copy/cut operation.
* @param type {String} Event type ('success' or 'error').
* @param handler Callback function.
*/
on(type: "success", handler: (e: ClipboardEvent) => void): this;
on(type: "error", handler: (e: ClipboardEvent) => void): this;
on(type: string, handler: (e: ClipboardEvent) => void): this;
/**
* Clears all event bindings.
*/
destroy(): void;
}
interface ClipboardOptions {
/**
* Overwrites default command ('cut' or 'copy').
* @param {Element} elem Current element
* @returns {String} Only 'cut' or 'copy'.
*/
action?: (elem: Element) => string;
/**
* Overwrites default target input element.
* @param {Element} elem Current element
* @returns {Element} <input> element to use.
*/
target?: (elem: Element) => Element;
/**
* Returns the explicit text to copy.
* @param {Element} elem Current element
* @returns {String} Text to be copied.
*/
text?: (elem: Element) => string;
}
interface ClipboardEvent {
action: string;
text: string;
trigger: Element;
clearSelection(): void;
}
declare module 'clipboard' {
class Clipboard {
constructor(selector: (string | Element | NodeListOf<Element>), options?: Clipboard.Options);
/**
* Subscribes to events that indicate the result of a copy/cut operation.
* @param type {String} Event type ('success' or 'error').
* @param handler Callback function.
*/
on(type: "success", handler: (e: Clipboard.Event) => void): this;
on(type: "error", handler: (e: Clipboard.Event) => void): this;
on(type: string, handler: (e: Clipboard.Event) => void): this;
/**
* Clears all event bindings.
*/
destroy(): void;
}
namespace Clipboard {
interface Options {
/**
* Overwrites default command ('cut' or 'copy').
* @param {Element} elem Current element
* @returns {String} Only 'cut' or 'copy'.
*/
action?: (elem: Element) => string;
/**
* Overwrites default target input element.
* @param {Element} elem Current element
* @returns {Element} <input> element to use.
*/
target?: (elem: Element) => Element;
/**
* Returns the explicit text to copy.
* @param {Element} elem Current element
* @returns {String} Text to be copied.
*/
text?: (elem: Element) => string;
}
interface Event {
action: string;
text: string;
trigger: Element;
clearSelection(): void;
}
}
export = Clipboard;
}
+2 -3
View File
@@ -393,8 +393,8 @@ declare namespace CodeMirror {
/** Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, before it is added to the document.
The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor. */
on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void;
off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void;
on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => void ): void;
off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => void ): void;
/** Expose the state object, so that the Editor.state.completionActive property is reachable*/
state: any;
@@ -1240,4 +1240,3 @@ declare namespace CodeMirror {
}
}
}
+79
View File
@@ -0,0 +1,79 @@
import * as Color from "color"
var color: Color.Color = Color("white")
var colorOther: Color.Color = Color("black")
var colorRGB: Color.Color = color.rgb(0, 0, 0)
var colorRGB: Color.Color = color.rgb([0, 0, 0])
var rgb: Color.RGBColor = color.rgb()
var colorHSL: Color.Color = color.hsl([0, 0, 0])
var hsl: Color.HSLColor = color.hsl()
var colorHSV: Color.Color = color.hsv([0, 0, 0])
var hsv: Color.HSVColor = color.hsv()
var colorHBW: Color.Color = color.hbw([0, 0, 0])
var hbw: Color.HBWColor = color.hbw()
var colorCMYK: Color.Color = color.cmyk([0, 0, 0, 0])
var cmyk: Color.CMYKColor = color.cmyk()
var hex: string = color.hexString()
var percent: string = color.percentString()
var keyword: string | void = color.keyword()
var alpha: number = color.alpha()
var red: number = color.red()
var green: number = color.green()
var blue: number = color.blue()
var hue: number = color.hue()
var saturation: number = color.saturation()
var lightness: number = color.lightness()
var saturationv: number = color.saturationv()
var value: number = color.value()
var whiteness: number = color.whiteness()
var blackness: number = color.blackness()
var cyan: number = color.cyan()
var magenta: number = color.magenta()
var yellow: number = color.yellow()
var black: number = color.black()
var luminosity: number = color.luminosity()
var contrast: number = color.contrast(colorOther)
var dark: boolean = color.dark()
var light: boolean = color.light()
var level: string = color.level(colorOther)
var chain: Color.Color = color
.rgb(0, 0, 0)
.hsl([0, 0, 0])
.hsv([0, 0, 0])
.hbw([0, 0, 0])
.cmyk([0, 0, 0 ,0])
.alpha(0)
.red(0)
.green(0)
.blue(0)
.hue(0)
.saturation(0)
.lightness(0)
.saturationv(0)
.value(0)
.whiteness(0)
.blackness(0)
.cyan(0)
.magenta(0)
.yellow(0)
.black(0)
.negate()
.lighten(0)
.darken(0)
.saturate(0)
.desaturate(0)
.greyscale()
.whiten(0)
.blacken(0)
.clearer(0)
.opaquer(0)
.rotate(0)
.mix(colorOther, 0)
.clone()
+161
View File
@@ -0,0 +1,161 @@
// Type definitions for color v0.12.0
// Project: https://github.com/qix-/color
// Definitions by: Karol Janyst <https://github.com/LKay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Color {
interface RGBColor {
r: number
g: number
b: number
a?: number
}
interface FullRGBColor {
red: number
green: number
blue: number
alpha?: number
}
interface HSLColor {
h: number
s: number
l: number
a?: number
}
interface FullHSLColor {
hue: number
saturation: number
lightness: number
alpha?: number
}
interface HSVColor {
h: number
s: number
v: number
}
interface FullHSVColor {
hue: number
saturation: number
value: number
}
interface HBWColor {
h: number
b: number
w: number
}
interface FullHBWColor {
hue: number
whiteness: number
blackness: number
}
interface CMYKColor {
c: number
m: number
y: number
k: number
}
interface FullCMYKColor {
cyan: number
magenta: number
yellow: number
black: number
}
type ColorParam = string | RGBColor | FullRGBColor | HSLColor | FullHSLColor | HSVColor
| FullHSVColor | HBWColor | FullHBWColor | CMYKColor | FullCMYKColor
interface Color {
(color: ColorParam | Color) : Color
rgb(values: Array<number>): Color
rgb(r: number, g: number, b: number, a?: number): Color
rgb(values: RGBColor): Color
rgb(values: FullRGBColor): Color
rgb(): RGBColor
rgbArray(): Array<number>
rgbString(): string
rgbaString(): string
rgbNumber(): number
hsl(values: Array<number>): Color
hsl(): HSLColor
hslArray(): Array<number>
hslString(): string
hslaString(): string
hsv(values: Array<number>): Color
hsv(): HSVColor
hsvArray(): Array<number>
hsvString(): string
hbw(values: Array<number>): Color
hbw(): HBWColor
hbwArray(): Array<number>
hbwString(): string
cmyk(values: Array<number>): Color
cmyk(): CMYKColor
cmykArray(): Array<number>
cmykString(): string
hexString(): string
percentString(): string
keyword(): string | void
alpha(alpha: number): Color
alpha(): number
red(red: number): Color
red(): number
green(green: number): Color
green(): number
blue(blue: number): Color
blue(): number
hue(hue: number): Color
hue(): number
saturation(saturation: number): Color
saturation(): number
lightness(lightness: number): Color
lightness(): number
saturationv(saturationv: number): Color
saturationv(): number
value(value: number): Color
value(): number
whiteness(whiteness: number): Color
whiteness(): number
blackness(blackness: number): Color
blackness(): number
cyan(cyan: number): Color
cyan(): number
magenta(magenta: number): Color
magenta(): number
yellow(yellow: number): Color
yellow(): number
black(black: number): Color
black(): number
luminosity(): number
contrast(color: Color): number
dark(): boolean
light(): boolean
negate(): Color
lighten(value: number): Color
darken(value: number): Color
saturate(value: number): Color
desaturate(value: number): Color
greyscale(): Color
whiten(value: number): Color
blacken(value: number): Color
clearer(value: number): Color
opaquer(value: number): Color
rotate(value: number): Color
mix(color: Color, value?: number): Color
level(color: Color): string
clone(): Color
}
}
declare const Color: Color.Color;
export = Color;
export as namespace Color;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"color-tests.ts"
]
}
+2 -2
View File
@@ -5,11 +5,11 @@
"noImplicitAny": true,
"strictNullChecks": false,
"baseUrl": "../",
"typesSearchPaths": [
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"forceConsistentCasingInFileNames": true
},
"files": [
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
@@ -0,0 +1,119 @@
var log = (msg : string) => {};
var devices: BLECentralPlugin.PeripheralData[] = [];
var demoDevice :BLECentralPlugin.PeripheralData = {
"name": "Battery Demo",
"id": "20:FF:D0:FF:D1:C0",
"advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121],
"rssi": -55
};
devices.push(demoDevice);
var demoExtendedData : BLECentralPlugin.PeripheralDataExtended = {
"name": "Battery Demo",
"id": "20:FF:D0:FF:D1:C0",
"advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121],
"rssi": -55,
"services": [
"1800",
"1801",
"180f"
],
"characteristics": [
{
"service": "1800",
"characteristic": "2a00",
"properties": [
"Read"
]
},
{
"service": "1800",
"characteristic": "2a01",
"properties": [
"Read"
]
},
{
"service": "1801",
"characteristic": "2a05",
"properties": [
"Read"
]
},
{
"service": "180f",
"characteristic": "2a19",
"properties": [
"Read"
],
"descriptors": [
{
"uuid": "2901"
},
{
"uuid": "2904"
}
]
}
]
};
//get updates about the bluethooth states
ble.startStateNotifications((state) => log(`BLE state ${state}`));
ble.isEnabled(()=> log(`bluetooth is enabled`), ()=>log(`bluetooth is not enabled`));
//here we try to enable bluetooth
ble.enable(() => log(`yes it worked, or it was already enabled `), () => log(`nope it didn't work, the user pressed cancel, or we are in iOS`));
ble.showBluetoothSettings(() => log(`yes it worked`), () => log(`nope it didn't work`))
//stop getting updates about the bluethooth states
ble.stopStateNotifications()
//scan 5 seconds
ble.scan([], 5000, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') );
//scan continously
ble.startScan([], (data) => { devices.push(data); }, ()=> log('couldn\'t connect') )
////scan continously
ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') )
//stop scanning
ble.stopScan(()=> log('all good'), ()=> log('couldn\'t stop scanning'));
//are we conenected to that device?
ble.isConnected(demoDevice.id, () => log(`already connected to this device`), ()=> log(`not yet connected to that device`));
//connect to a specific device
var extendedData : BLECentralPlugin.PeripheralDataExtended;
ble.connect(demoDevice.id, (data)=> extendedData = data, () => log(`couldn't connect to the device`) );
//read some data from a characteristic
var charsOfOneOfItsServices = demoExtendedData.characteristics.filter((value) => value.service == demoExtendedData.services[0]);
ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data) => log(`we've received some data`), ()=> log(`couldn't read any data`));
//read the rssi
ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`));
var notificationsReceived : number = 0;
//get notified of changes for that characteristic
ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data)=> notificationsReceived++, ()=> log(`darn`));
//write some data
ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`));
//write some data without getting notified
ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`));
//stop getting notified of changes.
ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic);
//notificationsReceived == 1
//just disconnect
ble.disconnect(demoDevice.id);
+108
View File
@@ -0,0 +1,108 @@
// Type definitions for cordova-plugin-ble-central 1.1.2
// Project: https://github.com/don/cordova-plugin-ble-central
// Definitions by: Gidon Junge <https://github.com/gjunge>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace BLECentralPlugin {
interface PeripheralCharacteristic {
service: string;
characteristic: string;
properties: string[];
descriptors?: any[];
}
interface PeripheralData {
name: string;
id: string;
rssi: number
advertising: ArrayBuffer|any;
}
interface PeripheralDataExtended extends PeripheralData{
services: string[];
characteristics: PeripheralCharacteristic[]
}
interface StartScanOptions {
reportDuplicates?: boolean;
}
export interface BLECentralPluginStatic {
scan(services: string[], seconds: number, success : (data: PeripheralData) => any): void;
scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure : () => any): void;
startScan(services: string[], success: (data: PeripheralData) => any): void;
startScan(services: string[], success: (data: PeripheralData) => any, failure: () => any): void;
startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any): void;
startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure: () => any): void;
stopScan(): void;
stopScan(success: () => any): void;
stopScan(success: () => any, failure: () => any): void;
connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: () => any): void;
disconnect(device_id:string): void;
disconnect(device_id:string, success: () => any): void;
disconnect(device_id:string, success: () => any, failure: () => any): void;
read(device_id: string, service_uuid:string, characteristic_uuid:string): void;
read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void;
read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void;
write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void;
write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void;
write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void;
/* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack.
The success callback is be called when the characteristic is written.*/
writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void;
writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void;
writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void;
/* Register to be notified when the value of a characteristic changes. */
startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void;
startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void;
stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string): void;
stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any): void;
stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any, failure: () => any): void;
/* Reports if bluetooth is enabled. */
isEnabled(success: () => any , failure: () => any): void;
/* Calls the success callback when the peripheral is connected and the failure callback when not connected. */
isConnected(device_id: string, success: () => any): void;
isConnected(device_id: string, success: () => any, failure: () => any): void;
startStateNotifications(success: (state: string) => any): void;
startStateNotifications(success: (state: string) => any, failure: () => any): void;
stopStateNotifications(): void;
stopStateNotifications(success: () => any): void;
stopStateNotifications(success: () => any, failure: () => any): void;
/* Opens the Bluetooth settings for the operating systems.
[iOS] showBluetoothSettings is not supported on iOS. */
showBluetoothSettings(): void;
showBluetoothSettings(success: () => any): void;
showBluetoothSettings(success: () => any, failure: () => any): void;
/* Enable Bluetooth on the device.
[iOS] enable is not supported on iOS. */
enable(success: () => any, failure: () => any): void;
readRSSI(device_id:string, success: (rssi: number) => any): void;
readRSSI(device_id:string, success: (rssi: number) => any, failure: () => any): void;
}
}
declare var ble: BLECentralPlugin.BLECentralPluginStatic;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cordova-plugin-ble-central-tests.ts"
]
}
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -9,7 +9,8 @@
"../"
],
"types": [],
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -4,7 +4,8 @@
"target": "es6",
"noImplicitAny": false,
"strictNullChecks": false,
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
@@ -0,0 +1,532 @@
/// <reference types="cordova-plugin-device" />
cordova.plugins.diagnostic.isLocationAvailable(function(available){
console.log("Location is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isWifiAvailable(function(available){
console.log("WiFi is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isCameraAvailable(function(available){
console.log("Camera is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isBluetoothAvailable(function(available){
console.log("Bluetooth is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.switchToLocationSettings();
cordova.plugins.diagnostic.switchToMobileDataSettings();
cordova.plugins.diagnostic.switchToBluetoothSettings();
cordova.plugins.diagnostic.switchToWifiSettings();
cordova.plugins.diagnostic.isWifiEnabled(function(enabled){
console.log("WiFi is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.setWifiState(function(){
console.log("Wifi was enabled");
}, function(error){
console.error("The following error occurred: "+error);
}, true
);
cordova.plugins.diagnostic.setBluetoothState(function(){
console.log("Bluetooth was enabled");
}, function(error){
console.error("The following error occurred: "+error);
}, true
);
cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
console.log("Location setting is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isLocationAuthorized(function(enabled){
console.log("Location authorization is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getLocationAuthorizationStatus(function(status){
switch(status){
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission not requested");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied");
break;
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted always");
break;
case cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE:
console.log("Permission granted only when in use");
break;
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestLocationAuthorization(function(status){
switch(status){
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission not requested");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied");
break;
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted always");
break;
case cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE:
console.log("Permission granted only when in use");
break;
}
}, function(error){
console.error(error);
}, cordova.plugins.diagnostic.locationAuthorizationMode.ALWAYS);
cordova.plugins.diagnostic.isCameraPresent(function(present){
console.log("Camera is " + (present ? "present" : "absent"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isCameraAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "denied") + " access to the camera");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getCameraAuthorizationStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Camera use is authorized");
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestCameraAuthorization(function(status){
console.log("Authorization request for camera use was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isMicrophoneAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "denied") + " access to the microphone");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getMicrophoneAuthorizationStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Microphone use is authorized");
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestMicrophoneAuthorization(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Microphone use is authorized");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isContactsAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "denied") + " access to contacts");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getContactsAuthorizationStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Contacts use is authorized");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.requestContactsAuthorization(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Contacts use is authorized");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isCalendarAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "denied") + " access to calendar");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getCalendarAuthorizationStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Calendar use is authorized");
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestCalendarAuthorization(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Calendar use is authorized");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.switchToSettings(function(){
console.log("Successfully switched to Settings app");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getBluetoothState(function(state){
if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){
console.log("Bluetooth is able to connect");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.registerBluetoothStateChangeHandler(function(state){
if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){
console.log("Bluetooth is able to connect");
}
});
cordova.plugins.diagnostic.registerLocationStateChangeHandler(function(state){
if((device.platform === "Android" && state !== cordova.plugins.diagnostic.locationMode.LOCATION_OFF)
|| (device.platform === "iOS") && ( state === cordova.plugins.diagnostic.permissionStatus.GRANTED
|| state === cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE
)){
console.log("Location is available");
}
});
cordova.plugins.diagnostic.getLocationMode(function(locationMode){
switch(locationMode){
case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY:
console.log("High accuracy");
break;
case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING:
console.log("Battery saving");
break;
case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY:
console.log("Device only");
break;
case cordova.plugins.diagnostic.locationMode.LOCATION_OFF:
console.log("Location off");
break;
}
},function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isGpsLocationAvailable(function(available){
console.log("GPS location is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
console.log("GPS location is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isNetworkLocationAvailable(function(available){
console.log("Network location is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isNetworkLocationEnabled(function(enabled){
console.log("Network location is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getLocationMode(function(locationMode){
switch(locationMode){
case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY:
console.log("High accuracy");
break;
case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING:
console.log("Battery saving");
break;
case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY:
console.log("Device only");
break;
case cordova.plugins.diagnostic.locationMode.LOCATION_OFF:
console.log("Location off");
break;
}
},function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getPermissionAuthorizationStatus(function(status){
switch(status){
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted to use the camera");
break;
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission to use the camera has not been requested yet");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied to use the camera - ask again?");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
console.log("Permission permanently denied to use the camera - guess we won't be using it then!");
break;
}
}, function(error){
console.error("The following error occurred: "+error);
}, cordova.plugins.diagnostic.permission.CAMERA);
cordova.plugins.diagnostic.getPermissionsAuthorizationStatus(function(statuses){
for (var permission in statuses){
switch(statuses[permission]){
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted to use "+permission);
break;
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission to use "+permission+" has not been requested yet");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied to use "+permission+" - ask again?");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
console.log("Permission permanently denied to use "+permission+" - guess we won't be using it then!");
break;
}
}
}, function(error){
console.error("The following error occurred: "+error);
},[
cordova.plugins.diagnostic.permission.ACCESS_FINE_LOCATION,
cordova.plugins.diagnostic.permission.ACCESS_COARSE_LOCATION
]);
cordova.plugins.diagnostic.requestRuntimePermission(function(status){
switch(status){
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted to use the camera");
break;
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission to use the camera has not been requested yet");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied to use the camera - ask again?");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
console.log("Permission permanently denied to use the camera - guess we won't be using it then!");
break;
}
}, function(error){
console.error("The following error occurred: "+error);
}, cordova.plugins.diagnostic.permission.CAMERA);
cordova.plugins.diagnostic.requestRuntimePermissions(function(statuses){
for (var permission in statuses){
switch(statuses[permission]){
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted to use "+permission);
break;
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission to use "+permission+" has not been requested yet");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied to use "+permission+" - ask again?");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
console.log("Permission permanently denied to use "+permission+" - guess we won't be using it then!");
break;
}
}
}, function(error){
console.error("The following error occurred: "+error);
},[
cordova.plugins.diagnostic.permission.ACCESS_FINE_LOCATION,
cordova.plugins.diagnostic.permission.ACCESS_COARSE_LOCATION
]);
if(!cordova.plugins.diagnostic.isRequestingPermission()){
console.log("Request some permissions");
}else{
cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(function(statuses){
cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(null); // de-register handler after single call
console.log("Request some permissions");
});
}
function onPermissionRequestComplete(statuses:any){
console.info("Permission request complete");
for (var permission in statuses){
switch(statuses[permission]){
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted to use "+permission);
break;
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission to use "+permission+" has not been requested yet");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied to use "+permission);
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
console.log("Permission permanently denied to use "+permission);
break;
}
}
cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(null); // de-register handler
}
cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(onPermissionRequestComplete)
cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){
console.log("Bluetooth is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.hasBluetoothSupport(function(supported){
console.log("Bluetooth is " + (supported ? "supported" : "unsupported"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.hasBluetoothLESupport(function(supported){
console.log("Bluetooth LE is " + (supported ? "supported" : "unsupported"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.hasBluetoothLEPeripheralSupport(function(supported){
console.log("Bluetooth LE Peripheral Mode is " + (supported ? "supported" : "unsupported"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isCameraRollAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "denied") + " access to the camera roll");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getCameraRollAuthorizationStatus(function(status){
switch(status){
case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
console.log("Permission not requested");
break;
case cordova.plugins.diagnostic.permissionStatus.DENIED:
console.log("Permission denied");
break;
case cordova.plugins.diagnostic.permissionStatus.GRANTED:
console.log("Permission granted");
break;
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestCameraRollAuthorization(function(status){
console.log("Authorization request for camera roll was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isRemoteNotificationsEnabled(function(enabled){
console.log("Remote notifications are " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isRegisteredForRemoteNotifications(function(registered){
console.log("Device " + (registered ? "is" : "isn't") + " registered for remote notifications");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getRemoteNotificationTypes(function(types){
for(var type in types){
console.log(type + " is " + (types[type] ? "enabled" : "disabled"));
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isRemindersAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "denied") + " access to reminders");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getRemindersAuthorizationStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Reminders authorization allowed");
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestRemindersAuthorization(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Reminders authorization allowed");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isBackgroundRefreshAuthorized(function(authorized){
console.log("App is " + (authorized ? "authorized" : "not authorized") + " to perform background refresh");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getBackgroundRefreshStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("Background refresh is allowed");
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestBluetoothAuthorization(function(){
console.log("Bluetooth authorization requested");
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isMotionAvailable(function(available){
console.log("Motion tracking is " + (available ? "available" : "not available") + " on this device");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isMotionRequestOutcomeAvailable(function(available){
console.log("Motion tracking request outcome is " + (available ? "available" : "not available") + " on this device");
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestAndCheckMotionAuthorization(function(status){
console.log("Motion authorization is " +status);
}, function(error){
console.error(error);
});
+738
View File
@@ -0,0 +1,738 @@
// Type definitions for cordova.plugins.diagnostic v3.3.0
// Project: https://github.com/dpa99c/cordova-diagnostic-plugin
// Definitions by: Dave Alden <https://github.com/dpa99c/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="cordova" />
/**
* Checks whether device hardware features are enabled or available to the app, e.g. camera, GPS, wifi
*/
interface Diagnostic {
/**
* ANDROID ONLY
* "Dangerous" permissions that need to be requested at run-time (Android 6.0/API 23 and above)
* See http://developer.android.com/guide/topics/security/permissions.html#perm-groups
* @type {Object}
*/
permission?: any;
/**
* ANDROID ONLY
* Permission groups indicate which associated permissions will also be requested if a given permission is requested.
* See http://developer.android.com/guide/topics/security/permissions.html#perm-groups
* @type {Object}
*/
permissionGroups?: any;
/**
* ANDROID and iOS ONLY
* Constants for requesting and reporting the various permission states.
* @type {Object}
*/
permissionStatus?: any;
/**
* iOS ONLY
* Location authorization mode
* @type {Object}
*/
locationAuthorizationMode?: any;
/**
* ANDROID ONLY
* Constants for the various location modes on Android.
* @type {Object}
*/
locationMode?: any;
/**
* ANDROID and iOS ONLY
* Constants for the various Bluetooth hardware states.
* @type {Object}
*/
bluetoothState?: any;
/**
* Checks if app is able to access device location.
* @param successCallback
* @param errorCallback
*/
isLocationAvailable: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* Checks if Wifi is available.
* On iOS this returns true if the device is connected to a network by WiFi.
* On Android and Windows 10 Mobile this returns true if the WiFi setting is set to enabled, and is the same as isWifiEnabled()
* @param successCallback
* @param errorCallback
*/
isWifiAvailable: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* Checks if camera is available.
* On Android & iOS this returns true if the device has a camera AND the application is authorized to use it.
* On Windows 10 Mobile this returns true if the device has a rear-facing camera.
* @param successCallback
* @param errorCallback
*/
isCameraAvailable: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* Checks if Bluetooth is available to the app.
* Returns true if the device has Bluetooth capabilities AND if Bluetooth setting is switched on (same on Android, iOS and Windows 10 Mobile)
* @param successCallback
* @param errorCallback
*/
isBluetoothAvailable: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and WINDOWS ONLY
* Displays the device location settings to allow user to enable location services/change location mode.
*/
switchToLocationSettings?: () => void;
/**
* ANDROID and WINDOWS ONLY
* Displays mobile settings to allow user to enable mobile data.
*/
switchToMobileDataSettings?: () => void;
/**
* ANDROID and WINDOWS ONLY
* Displays Bluetooth settings to allow user to enable Bluetooth.
*/
switchToBluetoothSettings?: () => void;
/**
* ANDROID and WINDOWS ONLY
* Displays WiFi settings to allow user to enable WiFi.
*/
switchToWifiSettings?: () => void;
/**
* ANDROID and WINDOWS ONLY
* Returns true if the WiFi setting is set to enabled, and is the same as isWifiAvailable()
* @param successCallback
* @param errorCallback
*/
isWifiEnabled?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and WINDOWS ONLY
* Enables/disables WiFi on the device.
* @param successCallback
* @param errorCallback
* @param state
*/
setWifiState?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void,
state: boolean
) => void;
/**
* ANDROID and WINDOWS ONLY
* Enables/disables Bluetooth on the device.
* @param successCallback
* @param errorCallback
* @param state
*/
setBluetoothState?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void,
state: boolean
) => void;
/**
* ANDROID and iOS ONLY
* Returns true if the device setting for location is on.
* On Android this returns true if Location Mode is switched on.
* On iOS this returns true if Location Services is switched on.
* @param successCallback
* @param errorCallback
*/
isLocationEnabled?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Checks if the application is authorized to use location.
* @param successCallback
* @param errorCallback
*/
isLocationAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Returns the location authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getLocationAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Requests location authorization for the application.
* @param successCallback
* @param errorCallback
* @param mode - (iOS-only / optional) location authorization mode specified as a locationAuthorizationMode constant. If not specified, defaults to WHEN_IN_USE.
*/
requestLocationAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void,
mode?: string
) => void;
/**
* ANDROID and iOS ONLY
* Checks if camera hardware is present on device.
* @param successCallback
* @param errorCallback
*/
isCameraPresent?: (
successCallback: (present: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Checks if the application is authorized to use the camera.
* @param successCallback
* @param errorCallback
*/
isCameraAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Returns the camera authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getCameraAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Requests camera authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestCameraAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Checks if the application is authorized to use the microphone.
* @param successCallback
* @param errorCallback
*/
isMicrophoneAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Returns the microphone authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getMicrophoneAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Requests microphone authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestMicrophoneAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Checks if the application is authorized to use contacts (address book).
* @param successCallback
* @param errorCallback
*/
isContactsAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Returns the contacts authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getContactsAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Requests contacts authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestContactsAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Checks if the application is authorized to use the calendar.
* @param successCallback
* @param errorCallback
*/
isCalendarAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Returns the calendar authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getCalendarAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Requests calendar authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestCalendarAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Opens settings page for this app.
* On Android, this opens the "App Info" page in the Settings app.
* On iOS, this opens the app settings page in the Settings app. This works only on iOS 8+ - iOS 7 and below will invoke the errorCallback.
*/
switchToSettings?: (
successCallback: () => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Returns the state of Bluetooth on the device.
* @param successCallback
* @param errorCallback
*/
getBluetoothState?: (
successCallback: (state: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Registers a function to be called when a change in Bluetooth state occurs. Pass in a falsey value to de-register the currently registered function.
* @param successCallback
*/
registerBluetoothStateChangeHandler?: (
successCallback: (state: string) => void
) => void;
/**
* ANDROID and iOS ONLY
* Registers a function to be called when a change in Location state occurs. Pass in a falsey value to de-register the currently registered function.
* On Android, this occurs when the Location Mode is changed.
* On iOS, this occurs when location authorization status is changed. This can be triggered either by the user's response to a location permission authorization dialog, by the user turning on/off Location Services, or by the user changing the Location authorization state specifically for your app.
* @param successCallback
*/
registerLocationStateChangeHandler?: (
successCallback: (state: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if high-accuracy locations are available to the app from GPS hardware.
* Returns true if Location mode is enabled and is set to "Device only" or "High accuracy" AND if the app is authorised to use location.
* @param successCallback
* @param errorCallback
*/
isGpsLocationAvailable?: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device location setting is set to return high-accuracy locations from GPS hardware.
* Returns true if Location mode is enabled and is set to either Device only or High accuracy
* @param successCallback
* @param errorCallback
*/
isGpsLocationEnabled?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if low-accuracy locations are available to the app from network triangulation/WiFi access points.
* Returns true if Location mode is enabled and is set to "Battery saving" or "High accuracy" AND if the app is authorised to use location.
* @param successCallback
* @param errorCallback
*/
isNetworkLocationAvailable?: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device location setting is set to return high-accuracy locations from GPS hardware.
* Returns true if Location mode is enabled and is set to either Battery saving or High accuracy
* @param successCallback
* @param errorCallback
*/
isNetworkLocationEnabled?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Returns the current location mode setting for the device.
* @param successCallback
* @param errorCallback
*/
getLocationMode?: (
successCallback: (mode: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Returns the current authorisation status for a given permission.
* @param successCallback
* @param errorCallback
* @param permission
*/
getPermissionAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void,
permission: string
) => void;
/**
* ANDROID ONLY
* Returns the current authorisation status for multiple permissions.
* @param successCallback
* @param errorCallback
* @param permissions
*/
getPermissionsAuthorizationStatus?: (
successCallback: (status: string[]) => void,
errorCallback: (error: string) => void,
permissions: string[]
) => void;
/**
* ANDROID ONLY
* Requests app to be granted authorisation for a runtime permission.
* @param successCallback
* @param errorCallback
* @param permission
*/
requestRuntimePermission?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void,
permission: string
) => void;
/**
* ANDROID ONLY
* Requests app to be granted authorisation for multiple runtime permissions.
* @param successCallback
* @param errorCallback
* @param permissions
*/
requestRuntimePermissions?: (
successCallback: (status: string[]) => void,
errorCallback: (error: string) => void,
permissions: string[]
) => void;
/**
* ANDROID ONLY
* Indicates if the plugin is currently requesting a runtime permission via the native API.
*/
isRequestingPermission?: () => boolean;
/**
* ANDROID ONLY
* Registers a function to be called when a runtime permission request has completed. Pass in a falsey value to de-register the currently registered function.
* @param successCallback
*/
registerPermissionRequestCompleteHandler?: (
successCallback: (statuses: any) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device setting for Bluetooth is switched on.
* @param successCallback
* @param errorCallback
*/
isBluetoothEnabled?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device has Bluetooth capabilities.
* @param successCallback
* @param errorCallback
*/
hasBluetoothSupport?: (
successCallback: (supported: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device has Bluetooth Low Energy (LE) capabilities.
* @param successCallback
* @param errorCallback
*/
hasBluetoothLESupport?: (
successCallback: (supported: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device supports Bluetooth Low Energy (LE) Peripheral mode.
* @param successCallback
* @param errorCallback
*/
hasBluetoothLEPeripheralSupport?: (
successCallback: (supported: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Checks if the application is authorized to use the Camera Roll in Photos app.
* @param successCallback
* @param errorCallback
*/
isCameraRollAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Returns the authorization status for the application to use the Camera Roll in Photos app.
* @param successCallback
* @param errorCallback
*/
getCameraRollAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Requests camera roll authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestCameraRollAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Checks if remote (push) notifications are enabled.
* @param successCallback
* @param errorCallback
*/
isRemoteNotificationsEnabled?: (
successCallback: (enabled: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Indicates if the app is registered for remote (push) notifications on the device.
* @param successCallback
* @param errorCallback
*/
isRegisteredForRemoteNotifications?: (
successCallback: (registered: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Indicates the current setting of notification types for the app in the Settings app.
* @param successCallback
* @param errorCallback
*/
getRemoteNotificationTypes?: (
successCallback: (types: any) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Checks if the application is authorized to use reminders.
* @param successCallback
* @param errorCallback
*/
isRemindersAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Returns the reminders authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getRemindersAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Requests reminders authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestRemindersAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Checks if the application is authorized for background refresh.
* @param successCallback
* @param errorCallback
*/
isBackgroundRefreshAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Returns the background refresh authorization status for the application.
* @param successCallback
* @param errorCallback
*/
getBackgroundRefreshStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Requests Bluetooth authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestBluetoothAuthorization?: (
successCallback: () => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Checks if motion tracking is available on the current device.
* @param successCallback
* @param errorCallback
*/
isMotionAvailable?: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Checks if it's possible to determine the outcome of a motion authorization request on the current device.
* @param successCallback
* @param errorCallback
*/
isMotionRequestOutcomeAvailable?: (
successCallback: (available: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* iOS ONLY
* Requests and checks motion authorization for the application.
* @param successCallback
* @param errorCallback
*/
requestAndCheckMotionAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
}
interface CordovaPlugins {
diagnostic: Diagnostic
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cordova.plugins.diagnostic-tests.ts"
]
}
+2 -1
View File
@@ -9,7 +9,8 @@
"../"
],
"types": [],
"noEmit": true
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
@@ -0,0 +1,5 @@
import * as creditCardType from "credit-card-type"
var cardTypes: Array<creditCardType.CreditCardTypeInfo> = creditCardType("")
var cardInfo: creditCardType.CreditCardTypeInfo = creditCardType.getTypeInfo("")
var types: { [type: string]: string } = creditCardType.types
+30
View File
@@ -0,0 +1,30 @@
// Type definitions for Credit Card Type v5.0.0
// Project: https://github.com/braintree/credit-card-type
// Definitions by: Karol Janyst <https://github.com/LKay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace creditCardType {
type CardBrand = "american-express" | "diners-club" | "discover" | "jcb" | "maestro" | "master-card" | "unionpay" | "visa"
interface CreditCardTypeInfo {
niceType?: string
type?: CardBrand
pattern?: RegExp
gaps?: Array<number>
lengths?: Array<number>
code?: {
name?: string
size?: number
}
}
interface CreditCardType {
(number: string): Array<CreditCardTypeInfo>
getTypeInfo (type: string): CreditCardTypeInfo
types: { [type: string]: string }
}
}
declare const creditCardType: creditCardType.CreditCardType
export = creditCardType
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"credit-card-type-tests.ts"
]
}
+80 -41
View File
@@ -293,6 +293,12 @@ let multiString: GeoJSON.MultiLineString = graticuleGenerator();
let lines: GeoJSON.LineString[] = graticuleGenerator.lines();
let polygon2: GeoJSON.Polygon = graticuleGenerator.outline();
// geoGraticule10() =====================================================
// test convenience function:
multiString = d3Geo.geoGraticule10();
// ----------------------------------------------------------------------
// Raw Projections
// ----------------------------------------------------------------------
@@ -360,7 +366,7 @@ let clipAngle: number = constructedProjection.clipAngle();
constructedProjection = constructedProjection.clipAngle(null);
constructedProjection = constructedProjection.clipAngle(45);
let clipExtent: [[number, number], [number, number]] = constructedProjection.clipExtent();
let clipExtent: [[number, number], [number, number]] | null = constructedProjection.clipExtent();
constructedProjection = constructedProjection.clipExtent(null);
constructedProjection = constructedProjection.clipExtent([[0, 0], [1, 1]]);
@@ -416,14 +422,27 @@ conicConformal = conicConformal.fitSize([960, 500], samplePolygon); // inherited
// GeoPath Generator
// ----------------------------------------------------------------------
let minimalRenderingContextMockUp: d3Geo.GeoContext = {
beginPath: () => { return; },
moveTo: (x: number, y: number) => { return; },
lineTo: (x: number, y: number) => { return; },
arc: (x, y, radius, startAngle, endAngle) => { return; },
closePath: () => { return; }
};
// Create geoPath Generator =============================================
let geoPathCanvas: d3Geo.GeoPath<any, d3Geo.GeoPermissibleObjects>;
geoPathCanvas = d3Geo.geoPath();
geoPathCanvas = d3Geo.geoPath(null);
geoPathCanvas = d3Geo.geoPath(null, null);
geoPathCanvas = d3Geo.geoPath(d3Geo.geoAzimuthalEqualArea());
geoPathCanvas = d3Geo.geoPath(d3Geo.geoAzimuthalEqualArea(), minimalRenderingContextMockUp);
let geoPathSVG: d3Geo.GeoPath<SVGPathElement, d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>>;
geoPathSVG = d3Geo.geoPath<SVGPathElement, d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>>();
geoPathSVG = d3Geo.geoPath<SVGPathElement, d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>>(d3Geo.geoAzimuthalEqualArea());
geoPathSVG = d3Geo.geoPath<SVGPathElement, d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>>(d3Geo.geoAzimuthalEqualArea(), null);
// Configure geoPath Generator ==========================================
// projection(...) ------------------------------------------------------
@@ -440,14 +459,8 @@ let geoPathConicProjection: d3Geo.GeoConicProjection = geoPathSVG.projection<d3G
// context(...) ------------------------------------------------------
// minimal context interface
geoPathCanvas = geoPathCanvas.context({
beginPath: () => { return; },
moveTo: (x: number, y: number) => { return; },
lineTo: (x: number, y: number) => { return; },
arc: (x, y, radius, startAngle, endAngle) => { return; },
closePath: () => { return; }
});
// minimal context interface (mockup)
geoPathCanvas = geoPathCanvas.context(minimalRenderingContextMockUp);
let geoPathContext: d3Geo.GeoContext = geoPathCanvas.context();
@@ -461,13 +474,13 @@ let canvasContext: CanvasRenderingContext2D;
geoPathCanvas = geoPathCanvas.context(canvasContext);
canvasContext = geoPathCanvas.context<CanvasRenderingContext2D>();
// canvasContext = geoPathSimple.context(); // fails without casting to CanvasRenderingContext2D
// canvasContext = geoPathSimple.context<SampleProperties1>(); // fails as SampleProperties does not extend GeoCanvas
// canvasContext = geoPathCanvas.context(); // fails without casting to CanvasRenderingContext2D
// canvasContext = geoPathCanvas.context<SampleProperties1>(); // fails as SampleProperties does not extend GeoCanvas
// pointRadius(...) ------------------------------------------------------
geoPathCanvas = geoPathCanvas.pointRadius(5);
let geoPathCanvasPointRadiusAccessor: (this: any, d: d3Geo.GeoPermissibleObjects, ...args: any[]) => number = geoPathCanvas.pointRadius();
let geoPathCanvasPointRadiusAccessor: ((this: any, d: d3Geo.GeoPermissibleObjects, ...args: any[]) => number) | number = geoPathCanvas.pointRadius();
geoPathSVG = geoPathSVG.pointRadius(function (datum) {
let that: SVGPathElement = this;
@@ -475,9 +488,9 @@ geoPathSVG = geoPathSVG.pointRadius(function (datum) {
return datum.properties.name === 'Alabama' ? 10 : 15;
});
let geoPathSVGPointRadiusAccessor: (this: SVGPathElement, d: d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>, ...args: any[]) => number = geoPathSVG.pointRadius();
// let geoPathSVGPointRadiusAccessorWrong1: (this: SVGCircleElement, d: d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>, ...args: any[]) => number = geoPathSVG.pointRadius(); // fails, mismatch in this context
// let geoPathSVGPointRadiusAccessorWrong2: (this: SVGPathElement, d: d3Geo.GeoGeometryObjects, ...args: any[]) => number = geoPathSVG.pointRadius(); // fails, mismatch in object datum type
let geoPathSVGPointRadiusAccessor: number | ((this: SVGPathElement, d: d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>, ...args: any[]) => number) = geoPathSVG.pointRadius();
// let geoPathSVGPointRadiusAccessorWrong1: number | ((this: SVGCircleElement, d: d3Geo.ExtendedFeature<GeoJSON.Polygon, SampleProperties1>, ...args: any[]) => number) = geoPathSVG.pointRadius(); // fails, mismatch in this context
// let geoPathSVGPointRadiusAccessorWrong2: number | ((this: SVGPathElement, d: d3Geo.GeoGeometryObjects, ...args: any[]) => number) = geoPathSVG.pointRadius(); // fails, mismatch in object datum type
// Use geoPath Generator ================================================
@@ -549,33 +562,8 @@ let svgCircleWrong: Selection<SVGCircleElement, d3Geo.ExtendedFeature<GeoJSON.Po
let svgPathWrong: Selection<SVGPathElement, GeoJSON.Polygon, any, any>;
// svgPathWrong.attr('d', geoPathSVG); // fails, mismatch in datum type
// ----------------------------------------------------------------------
// geoClipExtent
// ----------------------------------------------------------------------
let geoClipExtent: d3Geo.GeoExtent = d3Geo.geoClipExtent();
// extent(...) ----------------------------------------------------------
let extent2: [[number, number], [number, number]] = geoClipExtent.extent();
geoClipExtent = geoClipExtent.extent([[0, 0], [960, 500]]);
// stream(...) ----------------------------------------------------------
let stream: d3Geo.GeoStream;
stream = geoClipExtent.stream(stream);
// ----------------------------------------------------------------------
// Stream interface
// ----------------------------------------------------------------------
stream.point(0, 0);
stream.point(0, 0, 0);
stream.lineStart();
stream.lineEnd();
stream.polygonStart();
stream.polygonEnd();
stream.sphere();
// ----------------------------------------------------------------------
// Context interface
@@ -611,6 +599,57 @@ customTransformProto = {
let t: { stream: (s: d3Geo.GeoStream) => (CustomTranformProto & d3Geo.GeoStream) } = d3Geo.geoTransform(customTransformProto);
// geoIdentity() ========================================================
let identityTransform: d3Geo.GeoIdentityTranform;
identityTransform = d3Geo.geoIdentity();
scale = identityTransform.scale();
identityTransform = identityTransform.scale(2);
translate = identityTransform.translate();
identityTransform = identityTransform.translate([10, 10]);
clipExtent = identityTransform.clipExtent();
identityTransform = identityTransform.clipExtent(null);
identityTransform = identityTransform.clipExtent([[0, 0], [100, 100]]);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], samplePolygon);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleSphere);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleGeometryCollection);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedGeometryCollection);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleFeature);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedFeature1);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedFeature2);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleFeatureCollection);
identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedFeatureCollection);
identityTransform = identityTransform.fitSize([960, 500], samplePolygon);
identityTransform = identityTransform.fitSize([960, 500], sampleSphere);
identityTransform = identityTransform.fitSize([960, 500], sampleGeometryCollection);
identityTransform = identityTransform.fitSize([960, 500], sampleExtendedGeometryCollection);
identityTransform = identityTransform.fitSize([960, 500], sampleFeature);
identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeature1);
identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeature2);
identityTransform = identityTransform.fitSize([960, 500], sampleFeatureCollection);
identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeatureCollection);
// ----------------------------------------------------------------------
// Stream interface
// ----------------------------------------------------------------------
let stream: d3Geo.GeoStream;
stream.point(0, 0);
stream.point(0, 0, 0);
stream.lineStart();
stream.lineEnd();
stream.polygonStart();
stream.polygonEnd();
stream.sphere();
// geoStream(...) ========================================================
d3Geo.geoStream(samplePolygon, stream);
+1156 -67
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for D3JS d3 standard bundle v4.2
// Type definitions for D3JS d3 standard bundle v4.3
// Project: https://github.com/d3/d3
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+2 -2
View File
@@ -12,7 +12,7 @@
"@types/d3-ease": "1.0",
"@types/d3-force": "1.0",
"@types/d3-format": "1.0",
"@types/d3-geo": "1.2",
"@types/d3-geo": "1.3",
"@types/d3-hierarchy": "1.0",
"@types/d3-interpolate": "1.1",
"@types/d3-path": "1.0",
@@ -28,7 +28,7 @@
"@types/d3-time-format": "2.0",
"@types/d3-timer": "1.0",
"@types/d3-transition": "1.0",
"@types/d3-voronoi": "1.0",
"@types/d3-voronoi": "1.1",
"@types/d3-zoom": "1.0"
}
}
+54 -14
View File
@@ -1,7 +1,7 @@
// Type definitions for dat.GUI v0.5
// Type definitions for dat.GUI v0.6.1
// Project: https://github.com/dataarts/dat.gui
// Definitions by: Satoru Kimura <https://github.com/gyohk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Definitions by: Satoru Kimura <https://github.com/gyohk>, ZongJing Lu <https://github.com/sonic3d>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace dat {
export class GUI {
@@ -23,11 +23,40 @@ declare namespace dat {
addColor(target: Object, propName:string, rgba: number[]): GUIController; // rgb or rgba
addColor(target: Object, propName:string, hsv:{h:number; s:number; v:number}): GUIController;
remove(controller: GUIController): void;
destroy(): void;
addFolder(propName:string): GUI;
close(): void;
open(): void;
remember(target: Object): void;
close(): void;
remember(target: Object, ...additionalTargets: Object[]): void;
getRoot(): GUI;
getSaveObject(): Object;
save(): void;
saveAs(presetName:string): void;
revert(gui:GUI): void;
listen(controller: GUIController): void;
updateDisplay(): void;
// gui properties in dat/gui/GUI.js
parent(): GUI;
scrollable(): boolean;
autoPlace(): boolean;
preset(): string;
preset(s: string): void;
width(): number;
width(n: number): void;
name(): string;
name(s: string): void;
closed(): boolean;
closed(b: boolean): void;
load(): Object;
useLocalStorage(): boolean;
useLocalStorage(b: boolean): void;
}
export interface GUIParams{
@@ -41,17 +70,28 @@ declare namespace dat {
export class GUIController {
destroy(): void;
fire(): GUIController;
getValue(): any;
isModified(): boolean;
listen(): GUIController;
min(n: number): GUIController;
remove(target: GUIController): void;
setValue(value: any): GUIController;
step(n: number): GUIController;
updateDisplay(): void;
// Controller
onChange: (value?: any) => void;
onFinishChange: (value?: any) => void;
setValue(value: any): GUIController;
getValue(): any;
updateDisplay(): void;
isModified(): boolean;
// NumberController
min(n: number): GUIController;
max(n: number): GUIController;
step(n: number): GUIController;
// FunctionController
fire(): GUIController;
// augmentController in dat/gui/GUI.js
options(option:any):GUIController;
name(s: string): GUIController;
listen(): GUIController;
remove(): GUIController;
}
}
+208
View File
@@ -0,0 +1,208 @@
// Example from deku/examples/basic
(function (){
const {h, createApp} = deku
function view(state = { count: 0 }, dispatch: Function){
return (
h('div', {}, [
h('div', {}, 'Counter: ' + state.count),
h('button', {onClick: increment(dispatch)}, 'Increment'),
h('button', {onClick: decrement(dispatch)}, 'Decrement')
])
)
}
function increment(dispatch: Function){
return () => dispatch({
type: 'INCREMENT'
})
}
function decrement(dispatch: Function){
return () => dispatch({
type: 'DECREMENT'
})
}
let render = createApp(document.body)
function main(state: any){
let vnode = view(state, (action: any) => main({ count: 0 }))
render(vnode)
}
main({ count: 0 })
})();
// Example from deku/docs/api/create-app
(function (){
const {createApp, element} = deku
const App = ({ props = { size: 'medium' } }) => {
return element('div', { class: `size-${ props.size }` })
}
const render = createApp(document.body)
render(element(App, { size: 'small' }))
render(element(App, { size: 'large' }))
})();
// Example from deku/docs/api/string
(function (){
const { h } = deku
const html = deku.string.render(h('div', {}, [
h('header'),
h('sidebar'),
h('app'),
]))
})();
// Example from deku/docs/api/element
(function (){
const { element } = deku
// Native elements
element('div', { class: 'greeting' }, [
element('span', {}, ['Hello'])
])
// Components
let App = {
render: ({ props = { name: '' } }) => element('div', {}, `Hello ${ props.name }!`)
}
element(App, { name: 'Tom' })
})();
// deku.createApp
(function (){
const { createApp, element } = deku
let render: Function = createApp(document.body)
render(element('div'))
render = createApp(document.body, (action: any) => {
render(element('div'))
})
render(element('div'))
})();
// deku.dom
(function (){
const { dom, element } = deku
let el: HTMLElement = dom.create(element('div'), '0.0', ()=>{}, {})
const update: (DOMElement: HTMLElement, action: any) => HTMLElement = dom.update(()=>{}, {})
el = update(el, {})
})();
// deku.string
(function (){
const { element } = deku
let html: string = deku.string.render(element('div'))
html = deku.string.render(element('div'), {})
})();
// deku.element
(function (){
const { element } = deku
let v: deku.VirtualElement = element('div')
v = element('div', {})
v = element('div', {}, [])
v = element('div', {}, ['foo', 0, 'bar'])
v = element('div', {}, 'foo')
v = element('div', {}, 0)
v = element('div', {}, 'foo', 'bar')
let Component = {
render({}){
return element('div')
}
}
v = element(Component)
v = element(Component, {})
v = element(Component, {}, [])
})();
// deku.diff
(function (){
const { diff, element } = deku
const { Actions } = diff
let diffs: any[] = diff.diffNode(element('div'), element('span'))
let actions: deku.diff.Actions[] = [
Actions.setAttribute('class', 'foo', 'bar'),
Actions.removeAttribute('foo', {}),
Actions.insertChild({}, 0, '0.0'),
Actions.removeChild(0),
Actions.updateChild(0, []),
Actions.updateChildren([]),
Actions.insertBefore(0),
Actions.replaceNode({}, {}, '0.0'),
Actions.removeNode({}),
Actions.sameNode(),
Actions.updateThunk({}, {}, '0.0')
]
actions.forEach(action => {
Actions.case({
setAttribute: (name: string, value: any, previousValue: any) => {
},
_: () => {
}
}, action)
})
})();
// deku.vnode
(function (){
const { vnode, element } = deku
let v: deku.VirtualElement = vnode.create('div')
v = vnode.createTextElement('foo')
const Component = {
render({}){
return element('div')
}
}
v = vnode.createThunkElement(Component.render, '', Component, [], {})
v = vnode.createEmptyElement()
let b: boolean = vnode.isThunk(v)
b = vnode.isText(v)
b = vnode.isEmpty(v)
b = vnode.isSameThunk(v, v)
let path: string = vnode.createPath('0', '1', '2', '3')
path = vnode.createPath(0, 1, 2, 3)
})();
+136
View File
@@ -0,0 +1,136 @@
// Type definitions for deku v2.0
// Project: https://github.com/anthonyshort/deku
// Definitions by: Sho Fuji <https://github.com/pocka/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = deku;
export as namespace deku;
declare namespace deku {
interface VirtualElement {
type: string;
}
/**
* Create a DOM renderer using a container element.
* Everything will be rendered inside of that container.
* Returns a function that accepts new state that can replace what is currently rendered.
*/
function createApp(el: HTMLElement, dispatch?: Dispatch): Render;
namespace dom {
/**
* Create a real DOM element from a virtual element, recursively looping down.
* When it finds custom elements it will render them, cache them, and keep going,
* so they are treated like any other native element.
*/
function create<C>(vnode: VirtualElement, path: string, dispatch: Dispatch, context: C): HTMLElement;
/**
* Modify a DOM element given an array of actions.
*/
function update<C, A>(dispatch: Dispatch, context: C): (DOMElement: HTMLElement, action: A) => HTMLElement;
}
namespace string {
/**
* Render a virtual element to a string. You can pass in an option state context object that will be given to all components.
*/
function render(vnode: VirtualElement): string;
function render<C>(vnode: VirtualElement, context: C): string;
}
/**
* This function lets us create virtual nodes using a simple syntax.
* It is compatible with JSX transforms so you can use JSX to write nodes that will compile to this function.
*/
function element(type: string): VirtualElement;
function element<A>(type: string, attributes: A, ...children: any[]): VirtualElement;
function element(type: Thunk): VirtualElement;
function element<A>(type: Thunk, attributes: A, ...children: any[]): VirtualElement;
var h: typeof element;
namespace diff {
/**
* Compare two virtual nodes and return an array of changes to turn the left into the right.
*/
function diffNode(prevNode: VirtualElement, nextNode: VirtualElement): any[];
class Actions {
private _keys: string[];
private _name: string;
static setAttribute(a: string, b: any, c: any): Actions;
static removeAttribute(a: string, b: any): Actions;
static insertChild(a: any, b: number, c: string): Actions;
static removeChild(a: number): Actions;
static updateChild(a: number, b: any[]): Actions;
static updateChildren(a: any[]): Actions;
static insertBefore(a: number): Actions;
static replaceNode(a: any, b: any, c: string): Actions;
static removeNode(a: any): Actions;
static sameNode(): Actions;
static updateThunk(a: any, b: any, c: string): Actions;
static case(pat: any, action: Actions): any;
}
}
namespace vnode {
var create: typeof element;
/**
* Text nodes are stored as objects to keep things simple
*/
function createTextElement(text: string): VirtualElement;
/**
* Lazily-rendered virtual nodes
*/
function createThunkElement<P, T, O>(fn: (model: Model) => VirtualElement, key: string, props: P, children: T[], options: O): VirtualElement;
function createEmptyElement(): VirtualElement;
function isThunk(vnode: VirtualElement): boolean;
function isText(vnode: VirtualElement): boolean;
function isEmpty(vnode: VirtualElement): boolean;
function isSameThunk(prevNode: VirtualElement, nextNode: VirtualElement): boolean;
// function isValidAttribute<A>(value: A): boolean;
/**
* Create a node path, eg. (23,5,2,4) => '23.5.2.4'
*/
function createPath(...paths: (number|string)[]): string;
}
}
interface Model {
props?: any,
children?: any[],
path?: string,
dispatch?: Dispatch,
context?: any
}
interface Component {
render: (model: Model) => deku.VirtualElement;
onCreate?: (model: Model) => any;
onUpdate?: (model: Model) => any;
onRemove?: (model: Model) => any;
}
/**
* Thunk object passed to `element`
*/
type Thunk = Component | ((model: Model) => deku.VirtualElement);
type Render = (vnode: deku.VirtualElement, context?: any) => void;
type Dispatch = (action: any) => any;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"deku-tests.ts"
]
}

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