Merge branch 'master' of github.com:DefinitelyTyped/DefinitelyTyped

# Conflicts:
#	types/i18next/i18next-tests.ts
#	types/sequelize/v3/index.d.ts
#	types/sequelize/v3/sequelize-tests.ts
This commit is contained in:
Jan Klimke
2017-05-16 17:21:55 +02:00
715 changed files with 92003 additions and 46135 deletions

View File

@@ -89,6 +89,13 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
* Make changes. Remember to edit tests.
* You may also want to add yourself to "Definitions by" section of the package header.
- Do this by adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `npm install -g typescript@2.0` and run `tsc`.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.

View File

@@ -354,6 +354,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/path-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "path-to-regexp",
"typingsPackageName": "path-to-regexp",
"sourceRepoURL": "https://github.com/pillarjs/path-to-regexp",
"asOfVersion": "1.7.0"
},
{
"libraryName": "pg-promise",
"typingsPackageName": "pg-promise",

View File

@@ -30,6 +30,10 @@ declare module 'angular' {
* Latency Threshold
*/
latencyThreshold?: number;
/**
* HTML element selector of parent
*/
parentSelector?: string;
}
}

View File

@@ -1,4 +1,4 @@
// Type definitions for angular-local-storage v0.1.5
// Type definitions for angular-local-storage v0.1.6
// Project: https://github.com/grevory/angular-local-storage
// Definitions by: Ken Fukuyama <https://github.com/kenfdev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -60,19 +60,19 @@ declare module 'angular' {
*/
set(key: string, val: string): boolean;
/**
* Directly adds a value to cookies with an expiration.
* Note: Typically used as a fallback if local storage is not supported.
* Returns: Boolean
* @param key
* @param val
* @param daysToExpiry
*/
* Directly adds a value to cookies with an expiration.
* Note: Typically used as a fallback if local storage is not supported.
* Returns: Boolean
* @param key
* @param val
* @param daysToExpiry
*/
set(key: string, val: string, daysToExpiry: number): boolean;
/**
* Directly get a value from a cookie.
* Returns: value from local storage
* @param key
*/
* Directly get a value from a cookie.
* Returns: value from local storage
* @param key
*/
get(key: string): string;
/**
* Remove directly value from a cookie.
@@ -84,8 +84,9 @@ declare module 'angular' {
* Remove all data for this app from cookie.
*/
clearAll(): any;
}
type StorageType = 'localStorage' | 'sessionStorage';
interface ILocalStorageService {
/**
@@ -104,19 +105,19 @@ declare module 'angular' {
* @param key
* @param value
*/
set<T>(key: string, value: T): boolean;
set<T>(key: string, value: T, storageType?: StorageType): boolean;
/**
* Directly get a value from local storage.
* If local storage is not supported, use cookies instead.
* Returns: value from local storage
* @param key
*/
get<T>(key: string): T;
get<T>(key: string, storageType?: StorageType): T;
/**
* Return array of keys for local storage, ignore keys that not owned.
* Returns: value from local storage
*/
keys(): string[];
keys(storageType?: StorageType): string[];
/**
* Remove an item from local storage by key.
* If local storage is not supported, use cookies instead.
@@ -131,7 +132,7 @@ declare module 'angular' {
* Returns: Boolean
* @param regularExpression
*/
clearAll(regularExpression?: RegExp): boolean;
clearAll(regularExpression?: RegExp, storageType?: StorageType): boolean;
/**
* Bind $scope key to localStorageService.
* Usage: localStorageService.bind(scope, property, value[optional], key[optional])
@@ -141,7 +142,7 @@ declare module 'angular' {
* @param value optional
* @param key The corresponding key used in local storage
*/
bind(scope: angular.IScope, property: string, value?: any, key?: string): Function;
bind(scope: angular.IScope, property: string, value?: any, key?: string, storageType?: StorageType): Function;
/**
* Return the derive key
* Returns String
@@ -152,7 +153,7 @@ declare module 'angular' {
* Return localStorageService.length, ignore keys that not owned.
* Returns Number
*/
length(): number;
length(storageType?: StorageType): number;
/**
* Deal with browser's cookies directly.
*/

View File

@@ -27,7 +27,7 @@ declare module 'angular' {
escapeToClose?: boolean;
resolve?: ResolveObject;
controllerAs?: string;
parent?: ((scope: ng.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node
parent?: ((scope: angular.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node
disableParentScroll?: boolean; // default: true
}
@@ -107,9 +107,9 @@ declare module 'angular' {
resolve?: ResolveObject;
controllerAs?: string;
parent?: string | Element | JQuery; // default: root node
onShowing?(scope: ng.IScope, element: JQuery): void;
onComplete?(scope: ng.IScope, element: JQuery): void;
onRemoving?(element: JQuery, removePromise: ng.IPromise<any>): void;
onShowing?(scope: angular.IScope, element: JQuery): void;
onComplete?(scope: angular.IScope, element: JQuery): void;
onRemoving?(element: JQuery, removePromise: angular.IPromise<any>): void;
skipHide?: boolean;
multiple?: boolean;
fullscreen?: boolean; // default: false
@@ -214,6 +214,7 @@ declare module 'angular' {
contrastDefaultColor?: string;
contrastDarkColors?: string | string[];
contrastLightColors?: string | string[];
contrastStrongLightColors?: string|string[];
}
interface IThemeHues {

View File

@@ -1,6 +1,6 @@
// Type definitions for Angular Toastr v1.6.0
// Project: https://github.com/Foxandxss/angular-toastr
// Definitions by: Niko Kovačič <https://github.com/nkovacic>
// Definitions by: Niko Kovačič <https://github.com/nkovacic>, Troy McKinnon <https://github.com/trodi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="angular" />
@@ -15,9 +15,9 @@ declare module 'angular' {
closeHtml?: string;
extendedTimeOut?: number;
messageClass?: string;
onHidden?: Function;
onShown?: Function;
onTap?: Function;
onHidden?: (wasClicked: boolean, toast: angular.toastr.IToast) => void;
onShown?: (toast: angular.toastr.IToast) => void;
onTap?: (toast: angular.toastr.IToast) => void;
progressBar?: boolean;
tapToDismiss?: boolean;
templates?: {

View File

@@ -311,7 +311,7 @@ declare module 'angular' {
openClass?: string;
}
interface IModalProvider {
interface IModalProvider extends IServiceProvider {
/**
* Default options all modals will use.
*/
@@ -875,7 +875,7 @@ declare module 'angular' {
useContentExp?: boolean;
}
interface ITooltipProvider {
interface ITooltipProvider extends IServiceProvider {
/**
* Provide a set of defaults for certain tooltip and popover attributes.
*/

View File

@@ -484,7 +484,14 @@ namespace TestInjector {
function foobar(v: boolean): number {
return 7;
}
let result: number = $injector.invoke(foobar);
let result = $injector.invoke(foobar);
if (!(typeof result === 'number')) {
// This fails to compile if 'result' is not exactly a number.
let expectNever: never = result;
}
let anyFunction: Function = foobar;
let anyResult: string = $injector.invoke(anyFunction);
}
}

View File

@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.6
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>, Caleb St-Denis <https://github.com/calebstdenis>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery" />
@@ -1847,6 +1847,77 @@ declare namespace angular {
$postLink?(): void;
}
/**
* Interface for the $onInit lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IOnInit {
/**
* Called on each controller after all the controllers on an element have been constructed and had their bindings
* initialized (and before the pre & post linking functions for the directives on this element). This is a good
* place to put initialization code for your controller.
*/
$onInit(): void;
}
/**
* Interface for the $doCheck lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IDoCheck {
/**
* Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes.
* Any actions that you wish to take in response to the changes that you detect must be invoked from this hook;
* implementing this has no effect on when `$onChanges` is called. For example, this hook could be useful if you wish
* to perform a deep equality check, or to check a `Dat`e object, changes to which would not be detected by Angular's
* change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; if detecting changes,
* you must store the previous value(s) for comparison to the current values.
*/
$doCheck(): void;
}
/**
* Interface for the $onChanges lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IOnChanges {
/**
* Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as
* cloning the bound value to prevent accidental mutation of the outer value.
*/
$onChanges(onChangesObj: IOnChangesObject): void;
}
/**
* Interface for the $onDestroy lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IOnDestroy {
/**
* Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources,
* watches and event handlers.
*/
$onDestroy(): void;
}
/**
* Interface for the $postLink lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IPostLink {
/**
* Called after this controller's element and its children have been linked. Similar to the post-link function this
* hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain
* templateUrl directives will not have been compiled and linked since they are waiting for their template to load
* asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered
* analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather
* different in Angular 1 there is no direct mapping and care should be taken when upgrading.
*/
$postLink(): void;
}
interface IOnChangesObject {
[property: string]: IChangesObject<any>;
}
@@ -1981,6 +2052,7 @@ declare namespace angular {
instantiate<T>(typeConstructor: {new(...args: any[]): T}, locals?: any): T;
invoke(inlineAnnotatedFunction: any[]): any;
invoke<T>(func: (...args: any[]) => T, context?: any, locals?: any): T;
invoke(func: Function, context?: any, locals?: any): any;
strictDi: boolean;
}

View File

@@ -17,4 +17,4 @@
"unified-signatures": false,
"void-return": false
}
}
}

View File

@@ -1,26 +1,36 @@
import Archiver = require('archiver');
import FS = require('fs');
import * as Archiver from 'archiver';
import * as fs from 'fs';
const archiver = Archiver.create('zip');
const writeStream = FS.createWriteStream('./archiver.d.ts');
const readStream = FS.createReadStream('./archiver.d.ts');
const writeStream = fs.createWriteStream('./archiver.d.ts');
const readStream = fs.createReadStream('./archiver.d.ts');
archiver.abort();
archiver.pipe(writeStream);
archiver.append(readStream, { name: 'archiver.d.ts' });
archiver.append(readStream, {name: 'archiver.d.ts'})
.append(readStream, {name: 'archiver.d.ts'});
archiver.bulk({ mappaing: {} });
archiver.directory('./path', './someOtherPath');
archiver.directory('./path', { name: "testName"} );
archiver.directory('./path', { name: "testName" });
archiver.directory('./', "", {});
archiver.directory('./', {name: 'test'}, {});
archiver.directory('./', { name: 'test' }, {});
archiver.append(readStream, {
name: "sub/folder.xml"
});
archiver.glob("**", {
cwd: 'path/to/files',
});
archiver.glob('./path', {}, {});
archiver.file('./path', { name: 'test' });
archiver.glob('./path', {}, {});
archiver.finalize();
archiver.setFormat('zip');
archiver.setModule(() => {});
@@ -28,4 +38,4 @@ archiver.setModule(() => {});
archiver.pointer();
archiver.use(() => {});
archiver.pipe(writeStream);
archiver.finalize();

View File

@@ -1,51 +1,67 @@
// Type definitions for archiver 1.3
// Project: https://github.com/archiverjs/node-archiver
// Definitions by: Esri <https://github.com/archiverjs/node-archiver>
// Definitions by: Esri <https://github.com/archiverjs/node-archiver>, Dolan Miu <https://github.com/dolanmiu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/* =================== USAGE ===================
import Archiver = require('archiver);
var archiver = Archiver.create('zip');
archiver.pipe(FS.createWriteStream('xxx'));
archiver.append(FS.createReadStream('xxx'));
archiver.pipe(fs.createWriteStream('xxx'));
archiver.append(fs.createReadStream('xxx'));
archiver.finalize();
=============================================== */
/// <reference types="node" />
import * as FS from 'fs';
import * as STREAM from 'stream';
import * as fs from 'fs';
import * as stream from 'stream';
import * as express from 'express';
import * as glob from 'glob';
declare function archiver(format: string, options?: {}): archiver.Archiver;
declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver;
declare namespace archiver {
function create(format: string, options?: {}): Archiver;
type Format = 'zip' | 'tar';
function create(format: string, options?: ArchiverOptions): Archiver;
function registerFormat(format: string, module: Function): void;
interface nameInterface {
interface EntryData {
name?: string;
prefix?: string;
stats?: string;
}
interface Archiver extends STREAM.Transform {
interface Archiver extends stream.Transform {
abort(): this;
append(source: STREAM.Readable | Buffer | string, name: nameInterface): this;
append(source: stream.Readable | Buffer | string, name?: EntryData): this;
bulk(mappings: any): this;
directory(dirpath: string, destpath: nameInterface | string, data?: any | Function): this;
directory(dirpath: string, options: EntryData | string, data?: EntryData): this;
file(filepath: string, data: any): this;
glob(pattern: string, options: {}, data: any): this;
file(filename: string, data: EntryData): this;
glob(pattern: string, options?: glob.IOptions, data?: EntryData): this;
finalize(): this;
pipe(stream: fs.WriteStream | express.Response): void;
setFormat(format: string): this;
setModule(module: Function): this;
pointer(): number;
use(plugin: Function): this;
}
interface ArchiverOptions {
store?: boolean;
gzip?: boolean;
gzipOptions?: {
level: number,
};
}
}
export = archiver;

View File

@@ -0,0 +1,6 @@
import * as autosni from "auto-sni";
let a = autosni({
agreeTos: true,
email: '',
domains: ['']
});

25
types/auto-sni/index.d.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
// Type definitions for auto-sni 2.1
// Project: https://www.npmjs.com/package/auto-sni
// Definitions by: Jan Wolf <https://github.com/janwo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import {Server} from "https";
declare namespace createServer {
interface Options {
email: string;
agreeTos: boolean;
domains: Array<string | string[]>;
ports?: {
http?: number,
https?: number
};
debug?: boolean;
}
}
declare function createServer(opts: createServer.Options, app?: any): Server;
export = createServer;

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"auto-sni-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -1,6 +1,6 @@
// Type definitions for AutobahnJS v0.9.7
// Project: http://autobahn.ws/js/
// Definitions by: Elad Zelingher <https://github.com/darkl/>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>
// Definitions by: Elad Zelingher <https://github.com/darkl/>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>, Wladimir Totino <https://github.com/valepu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
@@ -167,8 +167,14 @@ declare namespace autobahn {
interface IPublishOptions {
acknowledge?: boolean;
exclude?: number[];
exclude_authid?: string[];
exclude_authrole?: string[];
eligible?: number[];
disclose_me?: Boolean;
eligible_authid?: string[];
eligible_authrole?: string[];
retain?: boolean;
disclose_me?: boolean;
exclude_me?: boolean;
}
interface ISubscribeOptions {

View File

@@ -1627,7 +1627,7 @@ export interface Entity {
RowKey: string;
Timestamp?: Date;
etag?: string;
[property: string]: string | number | boolean | Date;
[property: string]: string | number | boolean | Date | undefined;
}
//#endregion
//#region BlobService Interfaces

View File

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

View File

@@ -14,6 +14,9 @@ traverse(ast, {
if (t.isIdentifier(node, { name: "n" })) {
node.name = "x";
}
if (t.isFunctionExpression(node)) {
node.params = [t.identifier('param')];
}
}
});
@@ -24,3 +27,5 @@ if (t.isBinaryExpression(ast)) {
}
t.assertBinaryExpression(ast);
t.assertBinaryExpression(ast, { operator: "*" });
var exp: t.Expression = t.nullLiteral();

View File

@@ -1,6 +1,6 @@
// Type definitions for babel-types v6.7
// Project: https://github.com/babel/babel/tree/master/packages/babel-types
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Definitions by: Troy Gerwien <https://github.com/yortus>, Sam Baxter <https://github.com/baxtersa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface Comment {
@@ -88,7 +88,7 @@ export interface CallExpression extends Node {
export interface CatchClause extends Node {
type: "CatchClause";
param: Pattern;
param: Identifier;
body: BlockStatement;
}
@@ -148,7 +148,7 @@ export interface ForStatement extends Node {
export interface FunctionDeclaration extends Node {
type: "FunctionDeclaration";
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -159,7 +159,7 @@ export interface FunctionDeclaration extends Node {
export interface FunctionExpression extends Node {
type: "FunctionExpression";
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -252,7 +252,7 @@ export interface ObjectMethod extends Node {
value: Expression;
decorators?: Decorator[];
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -353,20 +353,20 @@ export interface WithStatement extends Node {
export interface AssignmentPattern extends Node {
type: "AssignmentPattern";
left: Pattern;
left: Identifier;
right: Expression;
}
export interface ArrayPattern extends Node {
type: "ArrayPattern";
elements: Array<Pattern>;
elements: Array<Expression>;
typeAnnotation?: TypeAnnotation;
}
export interface ArrowFunctionExpression extends Node {
type: "ArrowFunctionExpression";
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement | Expression;
generator: boolean;
async: boolean;
@@ -472,7 +472,7 @@ export interface ClassMethod extends Node {
static: boolean;
decorators?: Decorator[];
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -870,7 +870,7 @@ export interface SpreadProperty extends Node {
argument: Expression;
}
export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression;
export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression;
export type Binary = BinaryExpression | LogicalExpression;
export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod;
export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod;
@@ -886,11 +886,11 @@ export type For = ForInStatement | ForStatement | ForOfStatement;
export type ForXStatement = ForInStatement | ForOfStatement;
export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod;
export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod;
export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression;
export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression;
export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias;
export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern;
export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral;
export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement;
export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | TemplateLiteral;
export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement;
export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty;
export type Method = ObjectMethod | ClassMethod;
export type ObjectMember = ObjectMethod | ObjectProperty;
@@ -925,8 +925,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen
export function file(program?: Program, comments?: Comment[], tokens?: any[]): File;
export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement;
export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement;
export function functionDeclaration(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration;
export function functionExpression(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression;
export function functionDeclaration(id?: Identifier, params?: Array<LVal>, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration;
export function functionExpression(id?: Identifier, params?: Array<LVal>, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression;
export function identifier(name?: string): Identifier;
export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement;
export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement;
@@ -940,7 +940,7 @@ export function memberExpression(object?: Expression | Super, property?: Express
export function newExpression(callee?: Expression | Super, _arguments?: Array<Expression | SpreadElement>): NewExpression;
export function program(body?: Array<Statement | ModuleDeclaration>, directives?: Directive[]): Program;
export function objectExpression(properties?: Array<ObjectProperty | ObjectMethod | SpreadProperty>): ObjectExpression;
export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean): ObjectMethod;
export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Array<LVal>, body?: BlockStatement, computed?: boolean): ObjectMethod;
export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty;
export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement;
export function returnStatement(argument?: Expression): ReturnStatement;
@@ -957,8 +957,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar
export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement;
export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement;
export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern;
export function arrayPattern(elements?: Array<Pattern>, typeAnnotation?: TypeAnnotation): ArrayPattern;
export function arrowFunctionExpression(params?: Pattern[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression;
export function arrayPattern(elements?: Array<Expression>, typeAnnotation?: TypeAnnotation): ArrayPattern;
export function arrowFunctionExpression(params?: Array<LVal>, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression;
export function classBody(body?: Array<ClassMethod | ClassProperty>): ClassBody;
export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration;
export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression;
@@ -972,7 +972,7 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi
export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier;
export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier;
export function metaProperty(meta?: string, property?: string): MetaProperty;
export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod;
export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Array<LVal>, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod;
export function objectPattern(properties?: Array<AssignmentProperty | RestProperty>, typeAnnotation?: TypeAnnotation): ObjectPattern;
export function spreadElement(argument?: Expression): SpreadElement;
export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression;

View File

@@ -5,10 +5,11 @@
/// <reference types="babel-types" />
import * as t from 'babel-types';
type Node = t.Node;
import { File, Expression } from 'babel-types';
export function parse(code: string, opts?: BabylonOptions): Node;
export function parse(code: string, opts?: BabylonOptions): File;
export function parseExpression(input: string, options?: BabylonOptions): Expression;
export interface BabylonOptions {
/**

View File

@@ -292,6 +292,14 @@ function RegionTests() {
}
function ViewTests() {
const v = new MyView(new MyModel());
const isDestroyed: boolean = v.isDestroyed();
const isRendered: boolean = v.isRendered();
const isAttached: boolean = v.isAttached();
const vv: Marionette.View<Backbone.Model> = v.delegateEntityEvents();
}
function CollectionViewTests() {
var cv = new MyCollectionView();
cv.collection.add(new MyModel());

View File

@@ -856,7 +856,10 @@ declare namespace Marionette {
/**
* Internal properties extended in Marionette.View.
*/
isDestroyed: boolean;
isDestroyed(): boolean;
isRendered(): boolean;
isAttached(): boolean;
delegateEntityEvents(): View<TModel>;
supportsRenderLifecycle: boolean;
supportsDestroyLifecycle: boolean;

View File

@@ -2,9 +2,9 @@
// Project: https://github.com/nulab/backlog-js
// Definitions by: Yuichi Watanabe <https://github.com/vvatanabe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
/// <reference types="isomorphic-fetch" />
declare class Request {
private configure;

View File

@@ -190,6 +190,11 @@ function CommonMethodsInEventStreamsAndProperties() {
console.log(sum); // returns [-1, 2, 8] in an order
});
}
{
var src = Bacon.fromArray([1, 2, 3]);
src.doLog('element value');
}
}
function EventStream() {

View File

@@ -1,6 +1,6 @@
// Type definitions for Bacon.js 0.7.0
// Project: https://baconjs.github.io/
// Definitions by: Alexander Matsievsky <https://github.com/alexander-matsievsky>
// Definitions by: Alexander Matsievsky <https://github.com/alexander-matsievsky>, Joonas Javanainen <https://github.com/gekkio>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery" />
@@ -69,7 +69,7 @@ declare namespace Bacon {
/**
* @function
* @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream.
* @param {Promise<A>|JQueryXHR} promise
* @param {PromiseLike<A>|JQueryXHR} promise
* @param {boolean} [abort]
* @returns {EventStream<E, A>}
* @example
@@ -78,7 +78,7 @@ declare namespace Bacon {
* Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true);
* Bacon.fromPromise(Promise.resolve(1), false);
*/
function fromPromise<E, A>(promise:Promise<A>|JQueryXHR, abort?:boolean):EventStream<E, A>;
function fromPromise<E, A>(promise:PromiseLike<A>|JQueryXHR, abort?:boolean):EventStream<E, A>;
/**
* @callback Bacon.fromPromise~eventTransformer
@@ -88,7 +88,7 @@ declare namespace Bacon {
/**
* @function Bacon.fromPromise
* @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`.
* @param {Promise<A>|JQueryXHR} promise
* @param {PromiseLike<A>|JQueryXHR} promise
* @param {boolean} abort
* @param {Bacon.fromPromise~eventTransformer} eventTransformer
* @returns {EventStream<E, B>}
@@ -100,7 +100,7 @@ declare namespace Bacon {
* return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()];
* });
*/
function fromPromise<E, A, B>(promise:Promise<A>|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial<B>|Next<B>|End<B>|Error<E>)[]):EventStream<E, B>;
function fromPromise<E, A, B>(promise:PromiseLike<A>|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial<B>|Next<B>|End<B>|Error<E>)[]):EventStream<E, B>;
/**
* @function
@@ -1026,9 +1026,10 @@ declare namespace Bacon {
/**
* @method EventStream#doLog
* @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that unlike `log` is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does.
* @param {string} [label]
* @returns {EventStream<E, A>}
*/
doLog():EventStream<E, A>;
doLog(label?:string):EventStream<E, A>;
/**
* @method
@@ -1613,9 +1614,10 @@ declare namespace Bacon {
/**
* @method Property#doLog
* @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that unlike `log` is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does.
* @param {string} [label]
* @returns {Property<E, A>}
*/
doLog():Property<E, A>;
doLog(label?:string):Property<E, A>;
/**
* @method

View File

@@ -0,0 +1,56 @@
import * as Bleno from 'bleno';
export class EchoCharacteristic extends Bleno.Characteristic {
_value: any;
_updateValueCallback: any;
constructor() {
super({
uuid: 'ec0e',
properties: ['read', 'write', 'notify'],
value: null
});
this._value = new ArrayBuffer(0);
this._updateValueCallback = null;
}
onReadRequest(offset: number, callback: any) {
callback(Bleno.Characteristic.RESULT_SUCCESS, this._value);
}
onWriteRequest(data: any, offset: number, withoutResponse: boolean, callback: any) {
this._value = data;
if (this._updateValueCallback) {
this._updateValueCallback(this._value);
}
callback(Bleno.Characteristic.RESULT_SUCCESS);
}
onSubscribe(maxValueSize: number, updateValueCallback: any) {
this._updateValueCallback = updateValueCallback;
}
onUnsubscribefunction() {
this._updateValueCallback = null;
}
}
Bleno.on('stateChange', (state: string) => {
if (state === 'poweredOn') {
Bleno.startAdvertising('echo', ['ec00'], () => {});
} else {
Bleno.stopAdvertising(() => {});
}
});
let characteristic = new EchoCharacteristic();
Bleno.on('advertisingStart', (error: string) => {
if (!error) {
Bleno.setServices(
[new Bleno.PrimaryService({uuid: 'ec00', characteristics: [ characteristic ] })],
() => {}
);
}
});

128
types/bleno/index.d.ts vendored Normal file
View File

@@ -0,0 +1,128 @@
// Type definitions for bleno 0.4
// Project: https://github.com/sandeepmistry/bleno
// Definitions by: Manuel Francisco Naranjo <naranjo.manuel@gmail.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class Characteristic {
uuid: any;
properties: any;
secure: any;
value: any;
descriptors: any;
constructor(options: any);
onIndicate(): void;
onNotify(): void;
onReadRequest(offset: any, callback: any): void;
onSubscribe(maxValueSize: any, updateValueCallback: any): void;
onUnsubscribe(): void;
onWriteRequest(data: any, offset: any, withoutResponse: any, callback: any): void;
toString(): any;
static RESULT_ATTR_NOT_LONG: number;
static RESULT_INVALID_ATTRIBUTE_LENGTH: number;
static RESULT_INVALID_OFFSET: number;
static RESULT_SUCCESS: number;
static RESULT_UNLIKELY_ERROR: number;
}
export class Descriptor {
uuid: any;
value: any;
constructor(options: any);
toString(): any;
}
export class PrimaryService {
uuid: any;
characteristics: any;
constructor(options: any);
toString(): any;
}
export const address: string;
export const domain: any;
export const mtu: number;
export const platform: string;
export const rssi: number;
export const state: string;
export function addListener(type: any, listener: any): any;
export function disconnect(): void;
export function emit(type: any, ...args: any[]): any;
export function eventNames(): any;
export function getMaxListeners(): any;
export function listenerCount(type: any): any;
export function listeners(type: any): any;
export function on(type: any, listener: any): any;
export function onAccept(clientAddress: any): void;
export function onAddressChange(address: any): void;
export function onAdvertisingStart(error: any): void;
export function onAdvertisingStop(): void;
export function onDisconnect(clientAddress: any): void;
export function onMtuChange(mtu: any): void;
export function onPlatform(platform: any): void;
export function onRssiUpdate(rssi: any): void;
export function onServicesSet(error: any): void;
export function onStateChange(state: any): void;
export function once(type: any, listener: any): any;
export function prependListener(type: any, listener: any): any;
export function prependOnceListener(type: any, listener: any): any;
export function removeAllListeners(type: any, ...args: any[]): any;
export function removeListener(type: any, listener: any): any;
export function setMaxListeners(n: any): any;
export function setServices(services: any, callback: any): void;
export function startAdvertising(name: any, serviceUuids: any, callback: any): void;
export function startAdvertisingIBeacon(uuid: any, major: any, minor: any, measuredPower: any, callback: any): void;
export function startAdvertisingWithEIRData(advertisementData: any, scanData: any, callback: any): void;
export function stopAdvertising(callback: any): void;
export function updateRssi(callback: any): void;

22
types/bleno/tsconfig.json Normal file
View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bleno-tests.ts"
]
}

1
types/bleno/tslint.json Normal file
View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -726,7 +726,28 @@ declare namespace Bluebird {
*
* `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail.
*/
export class AggregateError extends Error {}
export class AggregateError extends Error implements ArrayLike<Error> {
length: number;
[index: number]: Error;
join(separator?: string): string;
pop(): Error;
push(...errors: Error[]): number;
shift(): Error;
unshift(...errors: Error[]): number;
slice(begin?: number, end?: number): AggregateError;
filter(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
forEach(callback: (element: Error, index: number, array: AggregateError) => void, thisArg?: any): undefined;
some(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
every(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
map(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
indexOf(searchElement: Error, fromIndex?: number): number;
lastIndexOf(searchElement: Error, fromIndex?: number): number;
reduce(callback: (accumulator: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
reduceRight(callback: (previousValue: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
sort(compareFunction?: (errLeft: Error, errRight: Error) => number): AggregateError;
reverse(): AggregateError;
}
/**
* returned by `Bluebird.disposer()`.

View File

@@ -1,20 +1,23 @@
import * as bonjour from 'bonjour';
var bonjourOptions: bonjour.BonjourOptions;
var bonjourInstance: bonjour.Bonjour;
let bonjourOptions: bonjour.BonjourOptions;
let bonjourInstance: bonjour.Bonjour;
var serviceOptions: bonjour.ServiceOptions;
var service: bonjour.Service;
let serviceOptions: bonjour.ServiceOptions;
let service: bonjour.Service;
var browserOptions: bonjour.BrowserOptions;
var browser: bonjour.Browser;
let browserOptions: bonjour.BrowserOptions;
let browser: bonjour.Browser;
bonjourOptions = { interface: '192.168.1.1', port: 5353 };
bonjourInstance = new bonjour.Bonjour(bonjourOptions);
bonjourOptions = {};
bonjourInstance = bonjour(bonjourOptions);
serviceOptions = { name: 'My Web Server', type: 'http', port: 3000 };
// Publish a dummy server under name 'My Website' type http port 3000
serviceOptions = { name: 'My Website', type: 'http', port: 3000 };
service = bonjourInstance.publish(serviceOptions);
browserOptions = { protocol: 'tcp', type: 'http' };
browser = bonjour.find(browserOptions);
// Look for the server
browser = bonjourInstance.findOne(browserOptions, (srv: bonjour.Service) => {
// You can test here if the found server (srv) name is 'My Website'
});

View File

@@ -1,68 +1,82 @@
// Type definitions for bonjour v3.5.0
// Type definitions for bonjour 3.5
// Project: https://github.com/watson/bonjour
// Definitions by: Quentin Lampin <https://github.com/quentin-ol/>
// Definitions by: Quentin Lampin <https://github.com/quentin-ol/>, Nicolas Voigt <https://github.com/octo-sniffle>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference types="node" />
export interface BonjourOptions {
multicast?: boolean;
interface?: string;
port?: number;
ip?: string;
ttl?: number;
loopback?: boolean;
reuseAddr?: boolean;
declare function bonjour(opts?: bonjour.BonjourOptions): bonjour.Bonjour;
export = bonjour;
declare namespace bonjour {
/**
* Start a browser
*
* The browser listens for services by querying for PTR records of a given
* type, protocol and domain, e.g. _http._tcp.local.
*
* If no type is given, a wild card search is performed.
*
* An internal list of online services is kept which starts out empty. When
* ever a new service is discovered, it's added to the list and an "up" event
* is emitted with that service. When it's discovered that the service is no
* longer available, it is removed from the list and a "down" event is emitted
* with that service.
*/
interface Browser extends NodeJS.EventEmitter {
services: Service[];
start(): void;
update(): void;
stop(): void;
on(event: 'up' | 'down', listener: (service: Service) => void): this;
once(event: 'up' | 'down', listener: (service: Service) => void): this;
removeListener(event: 'up' | 'down', listener: (service: Service) => void): this;
removeAllListeners(event: 'up' | 'down'): this;
}
interface BrowserOptions {
type?: string;
subtypes?: string[];
protocol?: string;
txt?: Object;
}
interface ServiceOptions {
name: string;
host?: string;
port: number;
type: string;
subtypes?: string[];
protocol?: 'udp'|'tcp';
txt?: Object;
}
interface Service extends NodeJS.EventEmitter {
name: string;
type: string;
subtypes: string[];
protocol: string;
host: string;
port: number;
fqdn: string;
txt: Object;
published: boolean;
stop(cb: () => any): void;
start(): void;
}
interface BonjourOptions {
multicast?: boolean;
interface?: string;
port?: number;
ip?: string;
ttl?: number;
loopback?: boolean;
reuseAddr?: boolean;
}
interface Bonjour {
(opts?: BonjourOptions): Bonjour;
publish(options: ServiceOptions): Service;
unpublishAll(cb?: () => void): void;
find(options: BrowserOptions, onUp?: (service: Service) => void): Browser;
findOne(options: BrowserOptions, cb?: (service: Service) => void): Browser;
destroy(): void;
}
}
export interface BrowserOptions {
type?: string;
subtypes?: string[];
protocol?: string;
txt?: Object;
}
export interface ServiceOptions {
name: string;
host?: string;
port: number;
type: string;
subtypes?: string[];
protocol?: 'udp'|'tcp';
txt?: Object;
}
export interface Service {
name: string;
type: string;
subtypes: string[];
protocol: string;
host: string;
port: number;
fqdn: string;
rawTxt: Object;
txt: Object;
published: boolean;
stop: (cb: ()=>any) => void;
start: () => void;
}
export class Bonjour {
constructor(opts: BonjourOptions);
publish(options: ServiceOptions):Service;
unpublishAll(cb: ()=>any): void;
find(options:BrowserOptions, onUp: ()=>any): Browser;
findOne(options:any, cb: (service: Service)=>any): Browser;
destroy():void;
}
export class Browser {
services: Service[];
start():void;
update():void;
stop():void;
}
export function find(options: BrowserOptions, onUp?: ()=>any): Browser;
export function findOne(options: BrowserOptions): Browser;

View File

@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"ban-types": false
}
}

View File

@@ -481,6 +481,15 @@ new Book({'ISBN-13': '9780440180296'})
/* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */
{
(new User).fetchAll({
columns: ['id', 'name'],
withRelated: ['posts.tags']
}).then((user: any) => {
console.log(user);
})
}
/* model.format(), see http://bookshelfjs.org/#Model-instance-format */
/* model.get(), see http://bookshelfjs.org/#Model-instance-get */
@@ -637,6 +646,16 @@ customer.on('fetching', (model, columns) => {
/* model.once(), see http://bookshelfjs.org/#Model-instance-once */
/* model.orderBy(), see http://bookshelfjs.org/#Model-instance-orderBy */
{
(new User)
.orderBy('name', 'ASC')
.fetchAll()
.then((users: Bookshelf.Collection<User>) => {
console.log(users)
});
}
/* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */
// Example of a "parse" to convert snake_case to camelCase, using `underscore.string`
@@ -1096,6 +1115,16 @@ ships.on('fetched', (collection, response) => {
/* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */
/* collection.orderBy(), see http://bookshelfjs.org/#Collection-instance-orderBy */
{
User.collection()
.orderBy('-name')
.fetch()
.then((users: Bookshelf.Collection<User>) => {
console.log(users);
})
}
/* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */
/* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */
@@ -1376,4 +1405,4 @@ new User({name: 'John'}).fetchAll({require: true})
new Country({id: 1}).capital().fetch().then(model => {
// ...
});
}
}

View File

@@ -1,6 +1,6 @@
// Type definitions for bookshelfjs v0.8.2
// Type definitions for bookshelfjs v0.9.3
// Project: http://bookshelfjs.org/
// Definitions by: Andrew Schurman <http://github.com/arcticwaters>
// Definitions by: Andrew Schurman <http://github.com/arcticwaters>, Vesa Poikajärvi <https://github.com/vesse>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -23,6 +23,8 @@ interface Bookshelf extends Bookshelf.Events<any> {
declare function Bookshelf(knex: knex): Bookshelf;
declare namespace Bookshelf {
type SortOrder = 'ASC'|'asc'|'DESC'|'desc';
abstract class Events<T> {
on(event?: string, callback?: EventFunction<T>, context?: any): void;
off(event?: string): void;
@@ -105,6 +107,7 @@ declare namespace Bookshelf {
morphOne<R extends Model<any>>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): R;
morphTo(name: string, columnNames?: string[], ...target: typeof Model[]): T;
morphTo(name: string, ...target: typeof Model[]): T;
orderBy(column: string, order?: SortOrder): T;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query(): Knex.QueryBuilder;
@@ -242,6 +245,7 @@ declare namespace Bookshelf {
detach(options?: SyncOptions): BlueBird<any>;
fetchOne(options?: CollectionFetchOneOptions): BlueBird<T>;
load(relations: string | string[], options?: SyncOptions): BlueBird<Collection<T>>;
orderBy(column: string, order?: SortOrder): T;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query(): Knex.QueryBuilder;
@@ -278,8 +282,7 @@ declare namespace Bookshelf {
[index: string]: (query: Knex.QueryBuilder) => Knex.QueryBuilder;
}
interface FetchAllOptions extends SyncOptions {
require?: boolean;
interface FetchAllOptions extends FetchOptions {
}
interface SaveOptions extends SyncOptions {

View File

@@ -3,8 +3,6 @@
// Definitions by: Igor Rogatty <http://github.com/rogatty>, AJP <http://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = Boom;
declare namespace Boom {

View File

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

View File

@@ -337,16 +337,16 @@ export interface DatetimepickerOptions {
/** Shows the week of the year to the left of first day of the week.
* @default: false
*/
calendarWeeks?: boolean;
calendarWeeks?: boolean;
/** Using a Bootstraps collapse to switch between date/time pickers.
* @default: true
*/
collapse?: boolean;
collapse?: boolean;
/** Disables the section of days of the week, e.g. weekends.
* Accepts: array of numbers from 0-6
* @default: false
*/
daysOfWeekDisabled?: number[] | boolean;
daysOfWeekDisabled?: number[] | boolean;
/** Changes the heading of the datepicker when in "days" view.
* @default: "MMMM YYYY"
*/
@@ -358,14 +358,14 @@ export interface DatetimepickerOptions {
/** Sets the picker default date/time. Overrides useCurrent
* @default: false
*/
defaultDate?: boolean | moment.Moment | Date | string;
defaultDate?: boolean | moment.Moment | Date | string;
/** Disables selection of dates in the array, e.g. holidays
* @default: false
* IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true.
* eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true }
* https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499
*/
disabledDates?: boolean | Array<moment.Moment | Date | string> | any;
disabledDates?: boolean | Array<moment.Moment | Date | string> | any;
/** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days
* @default: false
* IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true.
@@ -384,7 +384,7 @@ export interface DatetimepickerOptions {
* eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true }
* https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499
*/
enabledDates?: boolean | Array<moment.Moment | Date | string> | any;
enabledDates?: boolean | Array<moment.Moment | Date | string> | any;
/** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days
* @default: false
* IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true.
@@ -403,17 +403,17 @@ export interface DatetimepickerOptions {
/** See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker.
* @default: false
*/
format?: boolean | string | moment.MomentBuiltinFormat;
format?: boolean | string | moment.MomentBuiltinFormat;
/** Change the default icons for the pickers functions. */
icons?: Icons;
icons?: Icons;
/** Allow date picker show event to fire even when the associated input element has the readonly="readonly"property.
* @default: false
*/
ignoreReadonly?: boolean;
ignoreReadonly?: boolean;
/** Will display the picker inline without the need of a input field. This will also hide borders and shadows.
* @default: false
*/
inline?: boolean;
inline?: boolean;
/** Allows for custom events to fire on keyboard press.
* eg: keybinds: {
* up: (widget) => console.log(widget),
@@ -433,17 +433,17 @@ export interface DatetimepickerOptions {
/** See momentjs for valid locales. You must include moment-with-locales.js or a local js file.
* @default: moment.locale()
*/
locale?: string;
locale?: string;
/** Prevents date/time selections after this date.
* maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected.
* @default: false
*/
maxDate?: boolean | moment.Moment | Date | string;
maxDate?: boolean | moment.Moment | Date | string;
/** Prevents date/time selections before this date.
* minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected.
* @default: false
*/
minDate?: boolean | moment.Moment | Date | string;
minDate?: boolean | moment.Moment | Date | string;
/** Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago".
* {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate}
*/
@@ -452,7 +452,7 @@ export interface DatetimepickerOptions {
* Clicking the "Clear" button will set the calendar to null.
* @default: false
*/
showClear?: boolean;
showClear?: boolean;
/** Show the "Close" button in the icon toolbar.
* Clicking the "Close" button will call hide()
* @default: false
@@ -462,11 +462,11 @@ export interface DatetimepickerOptions {
* Clicking the "Today" button will set the calendar view and set the date to now.
* @default: false
*/
showTodayButton?: boolean;
showTodayButton?: boolean;
/** Shows the picker side by side when using the time and date together.
* @default: false
*/
sideBySide?: boolean;
sideBySide?: boolean;
/** Number of minutes the up/down arrow's will move the minutes value in the time picker
* @default: 1
*/
@@ -479,17 +479,17 @@ export interface DatetimepickerOptions {
/** Changes the placement of the icon toolbar.
* @default: "default"
*/
toolbarPlacement?: "default" | "top" | "bottom";
toolbarPlacement?: "default" | "top" | "bottom";
/** This will change the tooltips over each icon to a custom string */
tooltips?: Tooltips;
/** On show, will set the picker to the current date/time
* @default: true
*/
useCurrent?: boolean;
useCurrent?: boolean;
/** Defines if moment should use strict date parsing when considering a date to be valid
* @default: false
*/
useStrict?: boolean;
useStrict?: boolean;
/** This will change the viewDate without changing or setting the selected date.
* @default: false
*/
@@ -498,7 +498,7 @@ export interface DatetimepickerOptions {
* Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY
* @default: "days"
*/
viewMode?: "decades" | "years" | "months" | "days";
viewMode?: "decades" | "years" | "months" | "days";
/** On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative"
* @default: null
*/
@@ -520,7 +520,7 @@ export interface Icons {
/** default: "glyphicon glyphicon-screenshot" */
previous?: string;
/** default: "glyphicon glyphicon-chevron-right" */
time?: string;
time?: string;
/** default: "glyphicon glyphicon-chevron-down" */
today?: string;
/** default: "glyphicon glyphicon-chevron-up" */

View File

@@ -1087,7 +1087,7 @@ declare namespace braintree {
* });
* @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame.
*/
tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn;
tokenize(options: { flow: string, intent?: string, offerCredit?: boolean, useraction?: string, amount?: (string | number), currency?: string, displayName?: string, locale?: string, enableShippingAddress?: boolean, shippingAddressOverride?: PayPalShippingAddress, shippingAddressEditable?: boolean, billingAgreementDescription?: string }, callback: callback): PayPalTokenizeReturn;
/**
* Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}.

View File

@@ -0,0 +1,12 @@
import * as capitalize from "capitalize";
import { words } from "capitalize";
capitalize("united states");
capitalize.words("united states");
capitalize.words('hello-cañapolísas');
capitalize.words("it's a nice day");
words("united states");

19
types/capitalize/index.d.ts vendored Normal file
View File

@@ -0,0 +1,19 @@
// Type definitions for capitalize 1.0
// Project: https://github.com/grncdr/js-capitalize
// Definitions by: Frederick Fogerty <https://github.com/frederickfogerty/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/**
* Capitalize the first letter of a string
* @param input the string to capitalize
*/
declare function capitalize(input: string): string;
declare namespace capitalize {
/**
* Capitalize each word in a string
* @param input the string to capitalize
*/
function words(input: string): string;
}
export = capitalize;

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"capitalize-tests.ts"
]
}

View File

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

247
types/catbox/index.d.ts vendored Normal file
View File

@@ -0,0 +1,247 @@
// Type definitions for catbox 7.1
// Project: https://github.com/hapijs/catbox
// Definitions by: Jason Swearingen <http://github.com/jasonswearingen>, AJP <https://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import * as Boom from 'boom';
export interface CallBackNoResult {
(err?: Boom.BoomError): void;
}
export interface CallBackWithResult<T> {
(err: Boom.BoomError | null | undefined, result: T): void;
}
/**
* Client
* The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where:
* engine - is an object or a prototype function implementing the cache strategy:
* * function - a prototype function with the signature function(options). catbox will call new func(options).
* * object - a pre instantiated client implementation object. Does not support passing options.
* options - the strategy configuration object. Each strategy defines its own configuration options with the following common options:
* * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name.
* @see {@link https://github.com/hapijs/catbox#client}
*/
export interface Client extends ClientApi {
new(engine: EnginePrototypeOrObject, options: ClientOptions): Client;
}
type EnginePrototypeOrObject = EnginePrototype | ClientApi;
/**
* A prototype CatBox engine function
*/
export interface EnginePrototype {
new(settings: ClientOptions): ClientApi;
}
/**
* Client API
* The Client object provides the following methods:
* @see {@link https://github.com/hapijs/catbox#api}
*/
export interface ClientApi {
/** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */
start(callback: CallBackNoResult): void;
/** stop() - terminates the connection to the cache server. */
stop(): void;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned
*/
get(key: CacheKey, callback: CallBackWithResult<null | CachedObject>): CacheItem;
/**
* set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* * callback - a function with the signature function(err).
*/
set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void;
/**
* drop(key, callback) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err).
*/
drop(key: CacheKey, callback: CallBackNoResult): void;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Boom.BoomError;
}
/**
* Any method with a key argument takes an object with the following required properties:
*/
export interface CacheKey {
/** segment - a caching segment name string. Enables using a single cache server for storing different sets of items with overlapping ids. */
segment: string;
/** id - a unique item identifier string (per segment). Can be an empty string. */
id: string;
}
/** Cached object contains the following: */
export interface CachedObject {
/** item - the value stored in the cache using set(). */
item: any;
/** stored - the timestamp when the item was stored in the cache (in milliseconds). */
stored: number;
/** ttl - the remaining time-to-live (not the original value used when storing the object). */
ttl: number;
}
type CacheItem = any;
export interface ClientOptions {
partition: string;
}
/**
* The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where:
* * options - an object with the IPolicyOptions structure
* * cache - a Client instance (which has already been started).
* * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export interface Policy extends PolicyAPI {
new(options: PolicyOptions, cache: Client, segment: string): Policy;
}
/**
* Policy API
* The Policy object provides the following methods:
* @see {@link https://github.com/hapijs/catbox#api-1}
*/
export interface PolicyAPI {
/**
* get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are:
* * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key.
* * callback - the return function.
*/
get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem;
/**
* set(id, value, ttl, callback) - store an item in the cache where:
* * id - the unique item identifier (within the policy segment).
* * value - the string or object value to be stored.
* * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object.
* * callback - a function with the signature function(err).
*/
set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void;
/**
* drop(id, callback) - remove the item from cache where:
* * id - the unique item identifier (within the policy segment).
* * callback - a function with the signature function(err).
*/
drop(id: string | {id: string}, callback: CallBackNoResult): void;
/** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */
ttl(created: number): number;
/** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */
rules(options: PolicyOptions): void;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */
isReady(): boolean;
/** stats - an object with cache statistics */
stats(): CacheStatisticsObject;
}
/**
* The return function. The function signature is function(err, value, cached, report) where:
* @param err - any errors encountered.
* @param value - the fetched or generated value.
* @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions
* @param report - an object with logging information about the generation operation
*/
export interface PolicyGetCallback{
(err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void;
}
export interface PolicyGetCallbackCachedOptions {
/** item - the cached value. */
item: CacheItem;
/** stored - the timestamp when the item was stored in the cache. */
stored: number;
/** ttl - the cache ttl value for the record. */
ttl: number;
/** isStale - true if the item is stale. */
isStale: boolean;
}
/**
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export interface PolicyOptions {
/** expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */
expiresIn?: number;
/** expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Uses local time. Cannot be used together with expiresIn. */
expiresAt?: string;
/** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */
generateFunc?: GenerateFunc;
/**
* staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where:
* * stored - the timestamp when the item was stored in the cache (in milliseconds).
* * ttl - the remaining time-to-live (not the original value used when storing the object).
*/
staleIn?: number | ((stored: number, ttl: number) => number);
/** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */
staleTimeout?: number;
/** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */
generateTimeout?: number | false;
/** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */
dropOnError?: boolean;
/** generateOnReadError - if false, an upstream cache read error will stop the get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */
generateOnReadError?: boolean;
/** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */
generateIgnoreWriteError?: boolean;
/** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */
pendingGenerateTimeout?: number;
}
/**
* generateFunc
* Is used in PolicyOptions
* A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next)
* @param id - the id string or object provided to the get() method.
* @param next - the method called when the new item is returned with the signature function(err, value, ttl) where:
* * err - an error condition.
* * value - the new value generated.
* * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export interface GenerateFunc {
(id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void;
}
/**
* An object with logging information about the generation operation containing the following keys (as relevant):
*/
export interface PolicyGetCallbackReportLog {
/** msec - the cache lookup time in milliseconds. */
msec: number;
/** stored - the timestamp when the item was stored in the cache. */
stored: number;
/** isStale - true if the item is stale. */
isStale: boolean;
/** ttl - the cache ttl value for the record. */
ttl: number;
/** error - lookup error. */
error?: Boom.BoomError;
}
/**
* an object with cache statistics where:
*/
export interface CacheStatisticsObject {
/** sets - number of cache writes. */
sets: number;
/** gets - number of cache get() requests. */
gets: number;
/** hits - number of cache get() requests in which the requested id was found in the cache (can be stale). */
hits: number;
/** stales - number of cache reads with stale requests (only counts the first request in a queued get() operation). */
stales: number;
/** generates - number of calls to the generate function. */
generates: number;
/** errors - cache operations errors. TODO check this*/
errors: number;
}

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts"
]
}

View File

@@ -0,0 +1,76 @@
import { expect } from 'chai';
import { assert } from 'chai';
import chai = require('chai');
import ChaiArrays = require('chai-arrays');
chai.use(ChaiArrays);
chai.should();
const arr: any[] = [1, 2, 3];
const str: string = 'abcdef';
const otherArr: number[] = [1, 2, 3];
const anotherArr: number[] = [2, 4];
const yetAnotherArr: number[] = [8, 5, 7];
arr.should.be.array();
str.should.not.be.array();
expect(arr).to.be.array();
expect(str).not.to.be.array();
assert.array(arr, 'is array');
arr.should.be.ofSize(3);
arr.should.not.be.ofSize(4);
expect(arr).to.be.ofSize(3);
expect(str).not.to.be.ofSize(4);
assert.ofSize(arr, 3, 'has 3 elements');
arr.should.be.equalTo(otherArr);
arr.should.not.be.equalTo(anotherArr);
expect(arr).to.be.equalTo(otherArr);
expect(str).to.be.not.equalTo(anotherArr);
assert.equalTo(arr, otherArr, 'is equal to');
arr.should.be.containing(1);
arr.should.not.be.containing(4);
expect(arr).to.be.containing(1);
expect(str).to.be.not.containing(4);
assert.containing(arr, 1, 'contains');
arr.should.be.containingAllOf(otherArr);
arr.should.not.be.containingAllOf(anotherArr);
expect(arr).to.be.containingAllOf(otherArr);
expect(str).to.be.not.containingAllOf(anotherArr);
assert.containingAllOf(arr, otherArr, 'contains all of');
arr.should.be.containingAnyOf(otherArr);
arr.should.be.containingAnyOf(anotherArr);
arr.should.not.be.containingAnyOf(yetAnotherArr);
expect(arr).to.be.containingAnyOf(otherArr);
expect(str).to.be.containingAnyOf(anotherArr);
expect(str).to.be.not.containingAnyOf(yetAnotherArr);
assert.containingAnyOf(arr, otherArr, 'contains any of');
assert.containingAnyOf(arr, anotherArr, 'contains any of');
arr.should.be.sorted();
anotherArr.should.be.sorted();
yetAnotherArr.should.be.sorted();
expect(arr).to.be.sorted();
expect(anotherArr).to.be.sorted();
expect(yetAnotherArr).to.be.not.sorted();
assert.sorted(arr, 'sorted');

37
types/chai-arrays/index.d.ts vendored Normal file
View File

@@ -0,0 +1,37 @@
// Type definitions for chai-arrays 1.0
// Project: https://github.com/GaneshSPatil/chai-arrays
// Definitions by: Clément Prévot <https://github.com/clementprevot/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference types="chai" />
declare global {
namespace Chai {
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
array(): Assertion;
ofSize(size: number): Assertion;
equalTo(arr: any[]): Assertion;
containing(value: any): Assertion;
containingAllOf(values: any[]): Assertion;
containingAnyOf(values: any[]): Assertion;
sorted(): Assertion;
}
interface Assert {
array(val: any[], msg?: string): void;
ofSize(val: any[], size: number, msg?: string): void;
equalTo(val: any[], array: any[], msg?: string): void;
containing(val: any[], value: any, msg?: string): void;
containingAllOf(val: any[], values: any[], msg?: string): void;
containingAnyOf(val: any[], values: any[], msg?: string): void;
sorted(val: any[], msg?: string): void;
}
}
interface Array<T> {
should: Chai.Assertion;
}
}
declare function chaiArrays(chai: any, utils: any): void;
export = chaiArrays;

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"chai-arrays-tests.ts"
]
}

View File

@@ -848,7 +848,7 @@ declare namespace Chai {
* @param regExp Potential expected message match.
* @param message Message to display on error.
*/
throws(fn: Function, regExp: RegExp): void;
throws(fn: Function, regExp: RegExp, message?: string): void;
/**
* Asserts that function will throw an error that is an instance of constructor.

View File

@@ -39,6 +39,7 @@ declare namespace Chance {
// Person
age(opts?: Options): number;
gender(): string;
birthday(): Date;
birthday(opts?: Options): Date|string;
cpf(): string;

View File

@@ -438,7 +438,7 @@ interface ChocolateChipStatic {
/**
* Serialize
*/
serialize(form: HTMLFormElement | ChocolateChipElementArray): string;
serialize(form: HTMLFormElement | ChocolateChipElementArray): string;
/**
* Grabs values from a form and converts them into a JSON object.
@@ -862,7 +862,7 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param property The property to remove.
* @return HTMLElement[]
*/
removeProp(property: string): ChocolateChipElementArray;
removeProp(property: string): ChocolateChipElementArray;
/**
* Adds the specified class(es) to each of the set of matched elements.

View File

@@ -1,6 +1,7 @@
import classNames = require('classnames')
import classNames = require('classnames');
import * as classNames2 from 'classnames';
classNames('foo', 'bar'); // => 'foo bar'
classNames2('foo', 'bar'); // => 'foo bar'
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
@@ -21,4 +22,4 @@ classNames(["foo", ["bar", {baz: true}]]); // => 'foo bar baz'
classNames(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
// Supporting booleans is tricky since we should only support passing in false, which is ignored
//classNames(false, 'bar', 0, 1, { baz: null }, ''); // => 'bar 1'
// classNames(false, 'bar', 0, 1, { baz: null }, ''); // => 'bar 1'

View File

@@ -1,22 +1,25 @@
// Type definitions for classnames
// Type definitions for classnames 2.2
// Project: https://github.com/JedWatson/classnames
// Definitions by: Dave Keen <http://www.keendevelopment.ch>, Adi Dahiya <https://github.com/adidahiya>, Jason Killian <https://github.com/JKillian>
// Definitions by: Dave Keen <http://www.keendevelopment.ch>
// Adi Dahiya <https://github.com/adidahiya>
// Jason Killian <https://github.com/JKillian>
// Sean Kelley <https://github.com/seansfkelley/>
// Michal Adamczyk <https://github.com/mradamczyk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false;
type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false;
interface ClassDictionary {
[id: string]: boolean | undefined | null;
}
interface ClassArray extends Array<ClassValue> { }
// This is the only way I found to break circular references between ClassArray and ClassValue
// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
interface ClassArray extends Array<ClassValue> { } // tslint:disable-line no-empty-interface
interface ClassNamesFn {
(...classes: ClassValue[]): string;
}
type ClassNamesFn = (...classes: ClassValue[]) => string;
declare var classNames: ClassNamesFn;
declare const classNames: ClassNamesFn;
declare module "classnames" {
export = classNames
}
export = classNames;
export as namespace classNames;

View File

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

View File

@@ -178,7 +178,7 @@ declare namespace CodeMirror {
/** Remove a CSS class from a line.line can be a line handle or number.
where should be one of "text", "background", or "wrap"(see addLineClass).
class can be left off to remove all classes for the specified node, or be a string to remove only a specific class. */
removeLineClass(line: any, where: string, class_: string): CodeMirror.LineHandle;
removeLineClass(line: any, where: string, class_?: string): CodeMirror.LineHandle;
/**
* Compute the line at the given pixel height.
@@ -439,7 +439,7 @@ declare namespace CodeMirror {
/** Replace the part of the document between from and to with the given string.
from and to must be {line, ch} objects. to can be left off to simply insert the string at position from. */
replaceRange(replacement: string, from: CodeMirror.Position, to?: CodeMirror.Position): void;
replaceRange(replacement: string, from: CodeMirror.Position, to?: CodeMirror.Position, origin?: string): void;
/** Get the content of line n. */
getLine(n: number): string;

View File

@@ -59,3 +59,4 @@ var chain: Color.Color = color
.opaquer(0)
.rotate(0)
.mix(colorOther, 0)
.hsl();

View File

@@ -67,6 +67,13 @@ declare namespace Color {
hex(color: string): Color;
hex(): string;
rgb(): Color;
hsl(): Color;
hsv(): Color;
hwb(): Color;
hcg(): Color;
cmyk(): Color;
xyz(): Color;
lab(): Color;
rgbNumber(): number;
luminosity(): number;
contrast(color: Color): number;
@@ -85,6 +92,7 @@ declare namespace Color {
opaquer(value: number): Color;
rotate(value: number): Color;
mix(color: Color, value?: number): Color;
hsl(): Color;
}
}

View File

@@ -0,0 +1,43 @@
/**
* Display Messenger
*/
NativeKeyboard.showMessenger({
onSubmit: (text) => {},
onKeyboardDidHide: () => {},
onKeyboardDidShow: () => {},
onKeyboardWillShow: () => {},
onTextChanged: (text) => {},
onKeyboardWillHide: () => {},
});
/**
* Display Messenger Keyboard
*/
NativeKeyboard.showMessengerKeyboard(
() => {},
() => {});
/**
* Hide Messenger
*/
NativeKeyboard.hideMessenger(
{ animated: true},
() => {},
() => {});
NativeKeyboard.hideMessenger();
/**
* Hide Messenger Keyboard
*/
NativeKeyboard.hideMessengerKeyboard(
() => {},
() => {});
/**
* Update Messenger Keyboard
*/
NativeKeyboard.updateMessenger(
{text: 'FooBar'},
() => {},
() => {});

View File

@@ -0,0 +1,303 @@
// Type definitions for cordova-plugin-native-keyboard 1.3
// Project: https://github.com/EddyVerbruggen/cordova-plugin-native-keyboard#readme
// Definitions by: Daniel Brolli <https://github.com/lobo87>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface NativeKeyboard {
/**
* Show the messenger, the bare minimum which has to be passed to the function is
* the onSubmit callback
* @param options
*/
showMessenger(
options: NativeKeyboardShowOptions
): void;
/**
* It's likely your app only has 1 one page where you want to show the messenger,
* so you want to hide it when the user navigates away. You can choose to do this
* either animated (a quick slide down animation) or not.
*
* @param options
* @param onSuccess
* @param onError
*/
hideMessenger(
options?: NativeKeyboardHideOptions,
onSuccess?: () => void,
onError?: (err: any) => void
): void;
/**
* Show a previously hidden keyboard
*
* @param onSuccess
* @param onError
*/
showMessengerKeyboard(
onSuccess?: () => void,
onError?: (err: any) => void,
): void;
/**
* Hide the keyboard, but not the messenger bar
*
* @param onSuccess
* @param onError
*/
hideMessengerKeyboard(
onSuccess?: () => void,
onError?: (err: any) => void,
): void;
/**
* Manipulate the messenger while it's open. For instance if you want to
* update the text programmatically based on what the user typed (by responding to
* onTextChanged events).
*
* @param options
* @param onSuccess
* @param onError
*/
updateMessenger(
options: NativeKeyboardUpdateOptions,
onSuccess?: () => void,
onError?: (err: any) => void
): void;
}
interface NativeKeyboardUpdateOptions {
/**
* Replace the messenger's text by this. The current text remains if omitted.
*/
text?: string;
/**
* Position the cursor anywhere in the text range. Defaults to the end of the text.
*/
caretIndex?: number;
/**
* If false or omitted no changes to the keyboard state are made.
*/
showKeyboard?: boolean;
}
interface NativeKeyboardHideOptions {
/**
* A boolean flag inidicating if the keyboard should be shown/hidden with an animation
*/
animated?: boolean;
}
interface NativeKeyboardShowOptions {
/**
* Callback function, which is being called as soon as the user submits
* @param text
*/
onSubmit(text: string): void;
/**
* Callback function which is being executed as soon as the keyboard will show
*/
onKeyboardWillShow?(): void;
/**
* Callback function which is being executed as soon as the keyboard did show
*/
onKeyboardDidShow?(): void;
/**
* Callback function which is being executed as soon as the keyboard will hide
*/
onKeyboardWillHide?(): void;
/**
* Callback function which is being executed as soon as the keyboard did hide
*/
onKeyboardDidHide?(): void;
/**
* Callback function which is being executed as soon as the entered text changes. Will
* return the new text
*
* @param text
*/
onTextChanged?(text: string): void;
/**
* DOM element, which should be scrolled automatically
*/
autoscrollElement?: any;
/**
* Boolean value indicating if the content should be scrolled to the end after the messenger is
* shown
*/
scrollToBottomAfterMessengerShows?: boolean;
/**
* Boolean value indicating if the keyboard should be kept open after submitting the entered
* text
*
* Default: false
*/
keepOpenAfterSubmit?: boolean;
/**
* Makes the messenger bar slide in from the bottom.
*
* Default: false
*/
animated?: boolean;
/**
* Open the keyboard when showing the messenger.
*
* Default: false
*/
showKeyboard?: boolean;
/**
* A text which will be in the messenger bar, when opening
*/
text?: string;
/**
* The color of the typed text in HEX.
*
* Default: #444
*/
textColor?: string;
/**
* A placeholder which will be in the messenger bar, when opening and the input field is
* empty
*/
placeholder?: string;
/**
* The color of the placeholder.
*
* Default: #ccc
*/
placeholderColor?: string;
/**
* The background color of the messenger bar.
*
* Default: #F6F6F6
*/
backgroundColor?: string;
/**
* The background color of the textview. Looks nicest on Android
* if it's the same color as the backgroundColor property.
*
* Default: #F6F6F6
*/
textViewBackgroundColor?: string;
/**
* The border color of the textview.
*
* Default: #666666
*/
textViewBorderColor?: string;
/**
* Maximum amount of chars that can be entered
*/
maxChars?: number;
/**
* Options are: "none", "split", "countdown", "countdownreversed".
* Note that if maxChars is set, "none" will still show a counter.
*
* Default: "none"
*/
counterStyle?: string;
/**
* Options are: "default", "decimalpad", "phonepad", "numberpad", "namephonepad",
* "number", "email", "twitter", "url", "alphabet", "search", "ascii"
*
* Default: "default"
*/
type?: string;
/**
* Options are: "light", "dark".
*
* Default: "default"
*/
appearance?: string;
/**
* Disables things like the Emoji keyboard and the Predicive text entry bar
*
* Default: false
*/
secure?: boolean;
/**
* The left button of the messenger bar
*/
leftButton?: LeftButtonOptions;
/**
* The right button of the messenger bar
*/
rightButton?: ButtonOptions;
}
interface ButtonOptions {
/**
* The type of the button.
* Either "text", "fontawesome" or "ionicon".
*
* Default: "text"
*/
type?: string;
/**
* The value of the button. On "text" the string is used as label
* On fonatawesome or ionicon the icon name is used (e.g. fa-rocket)
*
* Default: "Send"
*/
value?: string;
/**
* If type is "text" you can set this to either "normal", "bold" or "italic".
*
* Default: "normal"
*/
textStyle?: string;
/**
* The color of the button in HEX
*
* Default: #000
*/
color: string;
/**
* A callback being executed as soon as the button is clicked
*/
onPress(): void;
}
interface LeftButtonOptions extends ButtonOptions {
/**
* Set to true to disable the button once text has been entered.
*
* Default: false
*/
disabledWhenTextEntered?: boolean;
}
/** NativeKeyboard instance */
declare var NativeKeyboard: NativeKeyboard;
interface Window {
NativeKeyboard: NativeKeyboard;
}

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cordova-plugin-native-keyboard-tests.ts"
]
}

View File

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

View File

@@ -3,7 +3,7 @@
var QRScanner: QRScanner = window.QRScanner;
QRScanner.prepare();
QRScanner.prepare((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: String = results; });
QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: string = results; });
QRScanner.cancelScan();
QRScanner.cancelScan((status) => {var obj: QRScannerStatus = status; });
QRScanner.show();
@@ -31,12 +31,12 @@ QRScanner.destroy((status) => {var obj: QRScannerStatus = status; });
QRScanner.prepare((err, status) => {
var error: QRScannerError = err;
var num: Number = error.code;
var str: String = error.name;
var num: number = error.code;
var str: string = error.name;
str = error._message;
var obj: QRScannerStatus = status;
var bool: Boolean = status.authorized;
var bool: boolean = status.authorized;
bool = status.denied;
bool = status.restricted;
bool = status.prepared;
@@ -46,5 +46,5 @@ QRScanner.prepare((err, status) => {
bool = status.lightEnabled;
bool = status.canOpenSettings;
bool = status.canEnableLight;
var num: Number = status.currentCamera;
var num: number = status.currentCamera;
});

View File

@@ -1,6 +1,7 @@
// Type definitions for cordova-plugin-qrscanner v1.0.0
// Type definitions for cordova-plugin-qrscanner v1.0.1
// Project: https://github.com/bitpay/cordova-plugin-qrscanner
// Definitions by: Jason Dreyzehner <https://github.com/bitjson/>
// Josh Bronson <https://github.com/jab>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
@@ -32,7 +33,7 @@ interface QRScanner {
* not need to be visible for scanning to function.
* @param {function} callback Callback that gets an error or the results string.
*/
scan: (callback: (error: QRScannerError, result: String) => any) => void;
scan: (callback: (error: QRScannerError, result: string) => any) => void;
/**
* Cancels the current scan. If `QRScanner.prepare()` has not been called,
@@ -82,7 +83,7 @@ interface QRScanner {
* @param {number} index A number representing the index of the camera to use.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useCamera: (index: Number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
useCamera: (index: number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the device's front camera. If `QRScanner.prepare()`
@@ -150,7 +151,7 @@ interface QRScannerStatus {
* (`AVAuthorizationStatus.Authorized`). On platforms with permissions granted
* at install (Android pre-6.0, Windows Phone) this property is always true.
*/
authorized: Boolean,
authorized: boolean,
/**
* A boolean value which is true if the user permenantly denied camera access
@@ -158,59 +159,59 @@ interface QRScannerStatus {
* only be gained by requesting the user change their decision (consider
* offering a link to the setting via `openSettings()`).
*/
denied: Boolean,
denied: boolean,
/**
* A boolean value which is true if the user is unable to grant permissions due
* to parental controls, organization security configuration profiles, or
* similar reasons.
*/
restricted: Boolean,
restricted: boolean,
/**
* A boolean value which is true if QRScanner is prepared to capture video and
* render it to the view.
*/
prepared: Boolean,
prepared: boolean,
/**
* A boolean value which is true if QRScanner is actively scanning for a QR code.
*/
scanning: Boolean,
scanning: boolean,
/**
* A boolean value which is true if QRScanner is displaying a live preview
* from the device's camera. Set to false when the preview is paused.
*/
previewing: Boolean,
previewing: boolean,
/**
* A boolean value which is true when the native webview background is transparent.
*/
webviewBackgroundIsTransparent: Boolean,
webviewBackgroundIsTransparent: boolean,
/**
* A boolean value which is true if the light is enabled.
*/
lightEnabled: Boolean,
lightEnabled: boolean,
/**
* A boolean value which is true only if the users' operating system is able
* to `QRScanner.openSettings()`.
*/
canOpenSettings: Boolean,
canOpenSettings: boolean,
/**
* A boolean value which is true only if the users' device can enable a light
* in the direction of the currentCamera.
*/
canEnableLight: Boolean,
canEnableLight: boolean,
/**
* A number representing the index of the currentCamera. `0` is the back
* camera, `1` is the front.
*/
currentCamera: Number
currentCamera: number
}
/**
@@ -218,8 +219,8 @@ interface QRScannerStatus {
*
* Many QRScanner functions accept a callback with an `error` parameter. When
* QRScanner experiences errors, this parameter contains a QRScannerError object
* with properties `name` (_String_), `code` (_Number_), and `_message`
* (_String_). When handling errors, rely only on the `name` or `code` parameter,
* with properties `name` (_string_), `code` (_number_), and `_message`
* (_string_). When handling errors, rely only on the `name` or `code` parameter,
*as the specific content of `_message` is not considered part of the plugin's
* stable API.
*
@@ -242,17 +243,17 @@ interface QRScannerError {
/**
* The standard string identifying the type of this QRScannerError.
*/
name: String,
name: string,
/**
* The standard number identifying the type of this QRScannerError.
*/
code: Number,
code: number,
/**
* A simple message describing this QRScannerError.
*/
_message: String
_message: string
}
declare var QRScanner: QRScanner;

View File

@@ -14,6 +14,7 @@ interface CronJobStatic {
interface CronJob {
start(): void;
stop(): void;
running: boolean | undefined;
}
export declare var CronJob: CronJobStatic;

View File

@@ -131,6 +131,11 @@ declare namespace cropperjs {
*/
rotatable?: boolean;
/**
* Enable to restore the cropped area after resizing the window.
* @default true
*/
restore?: boolean;
/**
* Enable to scale the image.
* @default true
*/

View File

@@ -7,7 +7,7 @@ function StepSample() {
type HookScenarioResult = cucumber.HookScenarioResult;
cucumber.defineSupportCode(function ({setWorldConstructor, defineParameterType, After, Around, Before, registerHandler, Given, When, Then}) {
setWorldConstructor(function ({attach, parameters}) {
setWorldConstructor(function ({attach, parameters}: any) {
this.attach = attach;
this.parameters = parameters;
this.visit = function (url: string, callback: Callback) {
@@ -19,7 +19,7 @@ function StepSample() {
console.log(scenarioResult.status === "failed");
callback();
});
Before({ timeout: 1000 }, function (scenarioResult: HookScenarioResult, callback: Callback) {
console.log(scenarioResult.status === "failed");
callback();
@@ -35,7 +35,7 @@ function StepSample() {
console.log("After");
callback();
});
After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback?: Callback) => {
console.log("After");
callback();
@@ -48,7 +48,7 @@ function StepSample() {
Given(/^a variable set to (\d+)$/, (x: string) => {
console.log("the number is: " + x);
});
Given(/^a variable set to (\d+)$/, (x: number) => {
console.log(typeof x);
});

View File

@@ -0,0 +1,76 @@
/// <reference types='node' />
import * as parse from 'cwise-parser';
import * as ndarray from 'ndarray';
import * as compile from 'cwise-compiler';
import * as tape from 'tape';
tape("block tests", (t) => {
const ops = require('ndarray-ops');
const body2 = parse((a: number, b: number[]) => {
a = b[0] + b[1] + 1;
});
const body23 = parse((a: number, b: number[][]) => {
a = b[0][0] * b[1][0] + b[0][1] * b[1][1] + b[0][2] * b[1][2];
});
// Test with block index at the front of the indices
const c1 = compile({
args: ["array", { blockIndices: 1 }],
pre: parse(() => { }),
body: body2,
post: parse(() => { }),
debug: false,
funcName: "cwise",
blockSize: 64
});
const a1 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]);
const b1 = ndarray([57, 17, 95, 78, 16, 96, 85, 93, 38, 42, 16, 66, 23, 77, 17, 36, 30, 52, 16, 18, 23, 69, 67, 27], [2, 3, 4]);
const ref1 = ndarray([81, 95, 113, 115, 47, 149, 102, 112, 62, 112, 84, 94], [3, 4]);
c1(a1, b1);
t.ok(ops.equals(a1, ref1), "front block");
// Test with block index at the back of the indices
const c2 = compile({
args: ["array", { blockIndices: -1 }],
pre: parse(() => { }),
body: body2,
post: parse(() => { }),
debug: false,
funcName: "cwise",
blockSize: 64
});
const a2 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]);
const b2 = ndarray([57, 17, 95, 78, 16, 96, 85, 93, 38, 42, 16, 66, 23, 77, 17, 36, 30, 52, 16, 18, 23, 69, 67, 27], [3, 4, 2]);
const ref2 = ndarray([75, 174, 113, 179, 81, 83, 101, 54, 83, 35, 93, 95], [3, 4]);
c2(a2, b2);
t.ok(ops.equals(a2, ref2), "back block");
// Multiple block indices
const c3 = compile({
args: ["array", { blockIndices: -2 }],
pre: parse(() => { }),
body: body23,
post: parse(() => { }),
debug: false,
funcName: "cwise",
blockSize: 64
});
const a3 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]);
const b3 = ndarray([48, 46, 89, 64, 72, 96, 38, 37, 79, 92, 89, 62, 84, 41, 13, 81, 53, 30, 68, 78, 34, 81, 90, 50,
82, 97, 46, 18, 11, 79, 15, 68, 88, 58, 71, 84, 76, 35, 74, 82, 27, 47, 59, 25, 78, 61, 10, 43,
96, 59, 21, 74, 41, 67, 11, 72, 38, 62, 95, 66, 57, 44, 93, 10, 51, 59, 50, 85, 71, 41, 79, 45], [3, 4, 2, 3]);
const ref = ndarray([14928, 11687, 9367, 14228, 6177, 13090, 10655, 7203, 10930, 10030, 8301, 11960], [3, 4]);
c3(a3, b3);
t.ok(ops.equals(a3, ref), "block with two indices");
t.end();
});

49
types/cwise-compiler/index.d.ts vendored Normal file
View File

@@ -0,0 +1,49 @@
// Type definitions for cwise-compiler 1.1
// Project: https://github.com/scijs/cwise-compiler
// Definitions by: taoqf <https://github.com/taoqf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { CompiledRoutine } from 'cwise-parser';
import * as ndarray from 'ndarray';
declare namespace cwise_compiler {
interface BlockIndice {
blockIndices: number;
}
interface OffsetArg {
offset: number[];
array: number;
}
type ArgType = 'array' | 'offset' | 'shape' | 'scalar' | 'index' | BlockIndice | OffsetArg;
interface UserArgs {
args: ArgType[];
pre: CompiledRoutine;
body: CompiledRoutine;
post: CompiledRoutine;
debug: boolean;
funcName: string;
blockSize: number;
printCode?: boolean;
}
interface Procedure {
argTypes: ArgType[];
shimArgs: string[];
arrayArgs: number[];
arrayBlockIndices: number[];
scalarArgs: number[];
offsetArgs: OffsetArg[];
offsetArgIndex: number[];
indexArgs: number[];
shapeArgs: number[];
funcName: string;
pre: CompiledRoutine;
body: CompiledRoutine;
post: CompiledRoutine;
debug: boolean;
blockSize?: number;
}
}
declare function cwise_compiler(user_args: cwise_compiler.UserArgs): (a: ndarray, b: ndarray, ...args: ndarray[]) => ndarray;
export = cwise_compiler;

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cwise-compiler-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -0,0 +1,26 @@
import * as parser from "cwise-parser";
// import parser = require("cwise-parser");
import * as tape from "tape";
tape("basic tests", (t) => {
const parsed = parser((a: number, b: number, c: number) => {
a += b;
c = Math.cos(b);
});
t.equals(parsed.args.length, 3);
t.equals(parsed.args[0].lvalue, true);
t.equals(parsed.args[0].rvalue, true);
t.equals(parsed.args[0].count, 1);
t.equals(parsed.args[1].lvalue, false);
t.equals(parsed.args[1].rvalue, true);
t.equals(parsed.args[1].count, 2);
t.equals(parsed.args[2].lvalue, true);
t.equals(parsed.args[2].rvalue, false);
t.equals(parsed.args[2].count, 1);
t.end();
});

22
types/cwise-parser/index.d.ts vendored Normal file
View File

@@ -0,0 +1,22 @@
// Type definitions for cwise-parser 1.0
// Project: https://github.com/scijs/cwise-parser#readme
// Definitions by: taoqf <https://github.com/taoqf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace cwise_parser {
interface CompiledArgument {
name: string;
lvalue: boolean;
rvalue: boolean;
count: number;
}
interface CompiledRoutine {
body: string;
args: CompiledArgument[];
thisVars: string[];
localVars: string[];
}
}
declare function cwise_parser<T>(func: (a: number, ...args: T[]) => any): cwise_parser.CompiledRoutine;
export = cwise_parser;

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cwise-parser-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

366
types/cwise/cwise-tests.ts Normal file
View File

@@ -0,0 +1,366 @@
import * as cwise from 'cwise';
import * as ndarray from 'ndarray';
import * as tape from 'tape';
// basic
tape("only allow same shape", (t) => {
const op1 = cwise({
args: ["array"],
body: (a: number) => { a = 1; }
});
const op2 = cwise({
args: ["array", "array"],
body: (a: number, b: number) => { a = b; }
});
const op3 = cwise({
args: ["array", "array", "array"],
body: (a: number, b: number, c: number) => { a = b + c; }
});
const op2block_pos = cwise({
args: ["array", { blockIndices: 1 }],
body: (a: number, b: number[]) => { a = b[1]; }
});
const op2block_neg = cwise({
args: ["array", { blockIndices: -1 }],
body: (a: number, b: number[]) => { a = b[1]; }
});
t.doesNotThrow(() => { op1(ndarray([1, 2, 3], [3])); });
t.doesNotThrow(() => { op2(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); });
t.doesNotThrow(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); });
t.doesNotThrow(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); });
t.doesNotThrow(() => { op2block_pos(ndarray([1, 2], [2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); });
t.doesNotThrow(() => { op2block_neg(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); });
t.throws(() => { op2(ndarray([1, 2, 3], [3]), ndarray([1, 2], [2])); });
t.throws(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3], [3, 1])); });
t.throws(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); });
t.throws(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3]), ndarray([1, 2], [2])); });
t.throws(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2], [2]), ndarray([1, 2, 3], [3])); });
t.throws(() => { op3(ndarray([1, 2], [2]), ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); });
t.throws(() => { op2block_pos(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); });
t.throws(() => { op2block_neg(ndarray([1, 2], [2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); });
t.throws(() => { op2block_pos(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); });
t.throws(() => { op2block_neg(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); });
t.end();
});
// binarry
class DumbStorage {
data: Int32Array;
length: number;
constructor(n: number) {
this.data = new Int32Array(n);
this.length = n;
}
get(i: number) {
return this.data[i];
}
set(i: number, v: number) {
return this.data[i] = v;
}
}
tape("binary", (t) => {
const binary = cwise({
args: ["array", "array", "scalar", "shape", "index"],
body(a: number, b: number, t: tape.Test, s: number[], idx: number) {
if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a);
a = b + 1001;
}
});
function testBinary1D(P: ndarray, Q: ndarray, testName: string) {
t.equals(P.shape[0], Q.shape[0], testName + "; shape");
for (let i = 0; i < P.shape[0]; ++i) {
Q.set(i, i);
P.set(i, 0);
}
binary(P, Q, t);
for (let i = 0; i < P.shape[0]; ++i) {
if (!(P.get(i) === i + 1001)) {
t.fail(testName + "; encountered " + P.get(i) + " instead of " + (i + 1001) + " at " + i);
return;
}
}
t.pass(testName);
}
const A1 = ndarray(new Int32Array(128));
const B1 = ndarray(new Int32Array(128));
testBinary1D(ndarray(new Int32Array(0)), ndarray(new Int32Array(0)), "length==0");
testBinary1D(ndarray(new Int32Array(1)), ndarray(new Int32Array(1)), "length==1");
testBinary1D(A1, B1, "A, B");
testBinary1D(A1.lo(32), B1.hi(128 - 32), "A.lo(32), B.hi(128-32)");
testBinary1D(A1.step(-1), B1, "A.step(-1), B");
testBinary1D(A1, B1.step(-1), "A, B.step(-1)");
const A2 = ndarray(new DumbStorage(128) as any);
const B2 = ndarray(new DumbStorage(128) as any);
testBinary1D(ndarray(new DumbStorage(0) as any), ndarray(new DumbStorage(0) as any), "DS; length==0");
testBinary1D(ndarray(new DumbStorage(1) as any), ndarray(new DumbStorage(1) as any), "DS; length==0");
testBinary1D(A2, B2, "DS; A, B");
testBinary1D(A2.lo(32), B2.hi(128 - 32), "DS; A.lo(32), B.hi(128-32)");
testBinary1D(A2.step(-1), B2, "DS; A.step(-1), B");
testBinary1D(A2, B2.step(-1), "DS; A, B.step(-1)");
const X = ndarray(new Int32Array(64 * 64), [64, 64]);
const Y = ndarray(new Int32Array(64 * 64), [64, 64]);
function testBinary2D(P: ndarray, Q: ndarray, testName: string) {
for (let i = 0; i < X.shape[0]; ++i) {
for (let j = 0; j < X.shape[1]; ++j) {
X.set(i, j, -10000);
Y.set(i, j, -256);
}
}
t.equals(P.shape[0], Q.shape[0], testName + "; shape[0]");
t.equals(P.shape[1], Q.shape[1], testName + "; shape[1]");
for (let i = 0; i < P.shape[0]; ++i) {
for (let j = 0; j < P.shape[1]; ++j) {
Q.set(i, j, i * 1000 + j);
P.set(i, j, 0);
}
}
binary(P, Q, t, P.shape);
for (let i = 0; i < P.shape[0]; ++i) {
for (let j = 0; j < P.shape[1]; ++j) {
if (!(P.get(i, j) === i * 1000 + j + 1001)) {
t.fail(testName + "; encountered " + P.get(i, j) + " instead of " + (i * 1000 + j + 1001) + " at (" + i + "," + j + ")");
return;
}
}
}
t.pass(testName);
}
testBinary2D(X, Y, "X, Y");
testBinary2D(X.transpose(1, 0), Y.transpose(1, 0), "X.T, Y.T");
testBinary2D(X.transpose(1, 0), Y, "X.T, Y");
testBinary2D(X, Y.transpose(1, 0), "X, Y.T");
testBinary2D(X.hi(32, 32), Y.hi(32, 32), "X.hi(32,32), Y.hi(32,32)");
testBinary2D(X.hi(31, 31), Y.hi(31, 31), "X.hi(31,31), Y.hi(31,31)");
testBinary2D(X.hi(0, 32), Y.hi(0, 32), "X.hi(0,32), Y.hi(0,32)");
testBinary2D(X.transpose(1, 0).hi(0, 32), Y.hi(0, 32), "X.T.hi(0,32), Y.hi(0,32)");
testBinary2D(X.transpose(1, 0).hi(33, 33), Y.hi(33, 33), "X.T.hi(33,33), Y.hi(33,33)");
testBinary2D(X.transpose(1, 0).hi(31, 31), Y.hi(31, 31), "X.T.hi(31,31), Y.hi(31,31)");
t.end();
});
// browserify
import * as browserify from "browserify";
import * as vm from 'vm';
import * as path from 'path';
const cases = ["unary", "binary", "offset", "fill"];
bundleCasesFrom(0);
function bundleCasesFrom(i: number) {
if (i >= cases.length) return;
const b = browserify();
b.ignore("tape");
b.add(__dirname + "/" + cases[i] + ".js");
b.transform(path.normalize(__dirname + "/../cwise.js"));
tape(cases[i], (t) => { // Without nested tests, the asynchronous nature of bundle causes issues with tape...
b.bundle((err, src) => {
if (err) {
throw new Error("failed to bundle!");
}
vm.runInNewContext(src.toString(), {
test: t.test.bind(t),
Buffer,
Int8Array,
Int16Array,
Int32Array,
Float32Array,
Float64Array,
Uint8Array,
Uint16Array,
Uint32Array,
Uint8ClampedArray,
console: { log: console.log.bind(console) }
});
t.end();
});
});
bundleCasesFrom(i + 1);
}
// fill
tape("fill", (t) => {
const fill = cwise({
args: ["index", "array", "scalar"],
body(idx, out, f) {
out = f.apply(undefined, idx);
}
});
const xlen = 10;
const ylen = 5;
const array = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]);
fill(array, (row: number, col: number) => {
return 0;
});
for (let i = 0; i < xlen; i++) {
for (let j = 0; j < ylen; j++) {
t.equals(array.get(i, j), 0, 'fill (' + i + ',' + j + ')');
}
}
fill(array, (row: number, col: number) => {
return 10 * (row + col);
});
for (let i = 0; i < xlen; i++) {
for (let j = 0; j < ylen; j++) {
t.equals(array.get(i, j), 10 * (i + j), 'fill (' + i + ',' + j + ')');
}
}
t.end();
});
// offset
tape("offset", (t) => {
const binary = cwise({
args: ["array", "array", { offset: [1], array: 1 }, "scalar", "shape", "index"],
body(a, b, c, t, s, idx) {
if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a);
a = c + b + 1000;
}
});
function testBinary1D(P: ndarray, Q: ndarray, testName: string) {
t.equals(P.shape[0], Q.shape[0] - 1, testName + "; shape");
for (let i = 0; i < P.shape[0]; ++i) {
Q.set(i, i);
P.set(i, 0);
}
Q.set(P.shape[0], P.shape[0]);
binary(P, Q.hi(Q.shape[0] - 1), t);
for (let i = 0; i < P.shape[0]; ++i) {
if (!(P.get(i) === 2 * i + 1001)) {
t.fail(testName + "; encountered " + P.get(i) + " instead of " + (2 * i + 1001) + " at " + i);
return;
}
}
t.pass(testName);
}
const A1 = ndarray(new Int32Array(128));
const B1 = ndarray(new Int32Array(129));
testBinary1D(ndarray(new Int32Array(0)), ndarray(new Int32Array(1)), "length==0");
testBinary1D(ndarray(new Int32Array(1)), ndarray(new Int32Array(2)), "length==1");
testBinary1D(A1, B1, "A, B");
testBinary1D(A1.lo(32), B1.lo(32), "A.lo(32), B.lo(32)");
testBinary1D(A1.step(-1), B1, "A.step(-1), B");
testBinary1D(A1, B1.step(-1), "A, B.step(-1)");
const A2 = ndarray(new DumbStorage(128) as any);
const B2 = ndarray(new DumbStorage(129) as any);
testBinary1D(ndarray(new DumbStorage(0) as any), ndarray(new DumbStorage(1) as any), "DS; length==0");
testBinary1D(ndarray(new DumbStorage(1) as any), ndarray(new DumbStorage(2) as any), "DS; length==1");
testBinary1D(A2, B2, "DS; A, B");
testBinary1D(A2.lo(32), B2.lo(32), "DS; A.lo(32), B.lo(32)");
testBinary1D(A2.step(-1), B2, "DS; A.step(-1), B");
testBinary1D(A2, B2.step(-1), "DS; A, B.step(-1)");
t.end();
});
// unary
tape("unary", (t) => {
const unary = cwise({
args: ["array"],
body(a) {
++a;
}
});
function testUnary1D(arr: ndarray, testName: string) {
for (let i = 0; i < arr.shape[0]; ++i) {
arr.set(i, i);
}
unary(arr);
for (let i = 0; i < arr.shape[0]; ++i) {
if (!(arr.get(i) === i + 1)) {
t.fail(testName + "; encountered " + arr.get(i) + " instead of " + (i + 1) + " at " + i);
return;
}
}
t.pass(testName);
}
const simple_zeros = ndarray(new Int32Array(4096));
testUnary1D(simple_zeros.hi(0), "simple_zeros.hi(0)");
testUnary1D(simple_zeros.hi(1), "simple_zeros.hi(1)");
testUnary1D(simple_zeros.hi(2), "simple_zeros.hi(2)");
testUnary1D(simple_zeros, "simple_zeros");
testUnary1D(simple_zeros.hi(31), "simple_zeros.hi(31)");
testUnary1D(simple_zeros.hi(32), "simple_zeros.hi(32)");
testUnary1D(simple_zeros.hi(33), "simple_zeros.hi(33)");
testUnary1D(simple_zeros.step(-1), "simple_zeros.step(-1)");
testUnary1D(simple_zeros.step(3), "simple_zeros.step(3)");
testUnary1D(simple_zeros.step(4), "simple_zeros.step(4)");
testUnary1D(simple_zeros.step(5).lo(10), "simple_zeros.step(5).lo(10)");
const custom_zeros = ndarray(new DumbStorage(4096) as any);
testUnary1D(custom_zeros.hi(0), "custom_zeros.hi(0)");
testUnary1D(custom_zeros.hi(1), "custom_zeros.hi(1)");
testUnary1D(custom_zeros.hi(2), "custom_zeros.hi(2)");
testUnary1D(custom_zeros, "custom_zeros");
testUnary1D(custom_zeros.hi(31), "custom_zeros.hi(31)");
testUnary1D(custom_zeros.hi(32), "custom_zeros.hi(32)");
testUnary1D(custom_zeros.hi(33), "custom_zeros.hi(33)");
testUnary1D(custom_zeros.step(-1), "custom_zeros.step(-1)");
testUnary1D(custom_zeros.step(3), "custom_zeros.step(3)");
testUnary1D(custom_zeros.step(4), "custom_zeros.step(4)");
testUnary1D(custom_zeros.step(5).lo(10), "custom_zeros.step(5).lo(10)");
function testUnary2D(arr: ndarray, testName: string) {
for (let i = 0; i < arr.shape[0]; ++i) {
for (let j = 0; j < arr.shape[1]; ++j) {
arr.set(i, j, i + j * arr.shape[0]);
}
}
unary(arr);
for (let i = 0; i < arr.shape[0]; ++i) {
for (let j = 0; j < arr.shape[1]; ++j) {
if (!(arr.get(i, j) === 1 + i + j * arr.shape[0])) {
t.fail(testName + "; encountered " + arr.get(i, j) + " instead of " + (1 + i + j * arr.shape[0]) + " at (" + i + "," + j + ")");
return;
}
}
}
t.pass(testName);
}
const M1 = ndarray(new Int32Array(128 * 128), [128, 128]);
testUnary2D(M1, "M");
testUnary2D(M1.hi(10, 10), "M.hi(10, 10)");
testUnary2D(M1.lo(100, 1), "M.lo(100,1)");
testUnary2D(M1.transpose(1, 0), "M.transpose(1,0)");
testUnary2D(M1.step(-1, 1), "M.step(-1, 1)");
testUnary2D(M1.step(-5, -2), "M.step(-5, -2)");
testUnary2D(M1.step(16, 3), "M.step(16, 3)");
const M2 = ndarray(new DumbStorage(128 * 128) as any, [128, 128]);
testUnary2D(M2, "DS; M");
testUnary2D(M2.hi(10, 10), "DS; M.hi(10, 10)");
testUnary2D(M2.lo(100, 1), "DS; M.lo(100,1)");
testUnary2D(M2.transpose(1, 0), "DS; M.transpose(1,0)");
testUnary2D(M2.step(-1, 1), "DS; M.step(-1, 1)");
testUnary2D(M2.step(-5, -2), "DS; M.step(-5, -2)");
testUnary2D(M2.step(16, 3), "DS; M.step(16, 3)");
t.end();
});

24
types/cwise/index.d.ts vendored Normal file
View File

@@ -0,0 +1,24 @@
// Type definitions for cwise 1.0
// Project: https://github.com/scijs/cwise#readme
// Definitions by: taoqf <https://github.com/taoqf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { ArgType } from "cwise-compiler";
import * as ndarray from "ndarray";
declare function cwise(a: string | cwise.UserArgs): cwise.Return;
declare namespace cwise {
type Arg = ndarray | ((row: number, col: number) => number) | number[] | any;
type Return = (a: ndarray, ...b: Arg[]) => void;
interface UserArgs {
args: ArgType[];
pre?(a: number, ...args: any[]): void;
body(a: number, ...args: any[]): void;
post?(a: number, ...args: any[]): void;
funcName?: string;
blockSize?: number;
printCode?: boolean;
}
}
export = cwise;

22
types/cwise/tsconfig.json Normal file
View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cwise-tests.ts"
]
}

3
types/cwise/tslint.json Normal file
View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -389,9 +389,13 @@ mergedArray = d3Array.shuffle(mergedArray, 1, 3);
numbersArray = d3Array.ticks(1, 10, 5);
// tickIncrement() ------------------------------------------------------------------
let numDiff: number = d3Array.tickIncrement(1, 10, 5);
// tickStep() ------------------------------------------------------------------
numbersArray = d3Array.tickStep(1, 10, 5);
numDiff = d3Array.tickStep(1, 10, 5);
// transpose() -----------------------------------------------------------------

View File

@@ -1,9 +1,9 @@
// Type definitions for D3JS d3-array module 1.1
// Type definitions for D3JS d3-array module 1.2
// Project: https://github.com/d3/d3-array
// Definitions by: Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>, Tom Wanzek <https://github.com/tomwanzek>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Last module patch version validated against: 1.1.0
// Last module patch version validated against: 1.2.0
// --------------------------------------------------------------------------
// Shared Types and Interfaces
@@ -246,14 +246,45 @@ export function shuffle<T>(array: T[], lo?: number, hi?: number): T[];
/**
* Generate an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive).
* Each value is a power of ten multiplied by 1, 2 or 5. See also d3.tickIncrement, d3.tickStep and linear.ticks.
*
* Ticks are inclusive in the sense that they may include the specified start and stop values if (and only if) they are exact,
* nicely-rounded values consistent with the inferred step. More formally, each returned tick t satisfies start ≤ t and t ≤ stop.
*
* @param start Start value for ticks
* @param stop Stop value for ticks
* @param count count + 1 is the approximate number of ticks to be returned by d3.ticks.
*/
export function ticks(start: number, stop: number, count: number): number[];
/**
* Generate an array of with the differences between adjecent ticks, had the same arguments
* been passed to ticks(start, stop, count)
* Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks:
* a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5.
*
* Like d3.tickStep, except requires that start is always less than or equal to step, and if the tick step for the given start,
* stop and count would be less than one, returns the negative inverse tick step instead.
*
* This method is always guaranteed to return an integer, and is used by d3.ticks to avoid guarantee that the returned tick values
* are represented as precisely as possible in IEEE 754 floating point.
*
* @param start Start value for ticks
* @param stop Stop value for ticks
* @param count count + 1 is the approximate number of ticks to be returned by d3.ticks.
*/
export function tickStep(start: number, stop: number, count: number): number[];
export function tickIncrement(start: number, stop: number, count: number): number;
/**
* Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks:
* a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5.
*
* Note that due to the limited precision of IEEE 754 floating point, the returned value may not be exact decimals;
* use d3-format to format numbers for human consumption.
*
* @param start Start value for ticks
* @param stop Stop value for ticks
* @param count count + 1 is the approximate number of ticks to be returned by d3.ticks.
*/
export function tickStep(start: number, stop: number, count: number): number;
/**
* Transpose a matrix provided in Array of Arrays format.
@@ -298,6 +329,9 @@ export interface HistogramGenerator<Datum, Value extends number | Date> {
* Divide the domain uniformly into approximately count bins. IMPORTANT: This threshold
* setting approach only works, when the materialized values are numbers!
*
* Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value,
* and the last bin.x1 is always equal to the maximum domain value.
*
* @param count The desired number of uniform bins.
*/
thresholds(count: number): this;
@@ -306,6 +340,9 @@ export interface HistogramGenerator<Datum, Value extends number | Date> {
* Divides the domain uniformly into approximately count bins. IMPORTANT: This threshold
* setting approach only works, when the materialized values are numbers!
*
* Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value,
* and the last bin.x1 is always equal to the maximum domain value.
*
* @param count A function which accepts as arguments the array of materialized values, and
* optionally the domain minimum and maximum. The function calcutates and returns the suggested
* number of bins.
@@ -313,6 +350,10 @@ export interface HistogramGenerator<Datum, Value extends number | Date> {
thresholds(count: ThresholdCountGenerator): this;
/**
* Set the array of values to be used as thresholds in determining the bins.
*
* Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value,
* and the last bin.x1 is always equal to the maximum domain value.
*
* @param thresholds Array of threshold values used for binning. The elements must
* be of the same type as the materialized values of the histogram.
*/
@@ -321,6 +362,9 @@ export interface HistogramGenerator<Datum, Value extends number | Date> {
* Set a threshold accessor function, which returns the array of values to be used as
* thresholds in determining the bins.
*
* Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value,
* and the last bin.x1 is always equal to the maximum domain value.
*
* @param thresholds A function which accepts as arguments the array of materialized values, and
* optionally the domain minimum and maximum. The function calcutates and returns the array of values to be used as
* thresholds in determining the bins.

View File

@@ -0,0 +1,189 @@
/**
* Typescript definition tests for d3/d3-contour module
*
* Note: These tests are intended to test the definitions only
* in the sense of typing and call signature consistency. They
* are not intended as functional tests.
*/
import * as d3Contour from 'd3-contour';
import {
range,
thresholdSturges,
ThresholdArrayGenerator,
ThresholdCountGenerator
} from 'd3-array';
import { geoPath } from 'd3-geo';
import { randomNormal } from 'd3-random';
// -----------------------------------------------------------------------------
// Preparatory Steps
// -----------------------------------------------------------------------------
// Some test setup is based on Contour Plot II Golstein-Price function at https://bl.ocks.org/mbostock/f48ff9c1af4d637c9a518727f5fdfef5
const n = 256;
const m = 256;
const values: number[] = new Array(n * m);
for (let j = 0.5, k = 0; j < m; ++j) {
for (let i = 0.5; i < n; ++i, ++k) {
values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3);
}
}
function goldsteinPrice(x: number, y: number) {
return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y))
* (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y));
}
let size: [number, number];
let boolFlag: boolean;
const thresholdArrayGen: ThresholdArrayGenerator<number> = (values: number[], min: number, max: number) => {
let thresholds: number[];
thresholds = [values[1], values[2], values[4]];
return thresholds;
};
let thresholdGenerator: ThresholdArrayGenerator<number> | ThresholdCountGenerator;
let pathStringMaybe: string | null;
let num: number;
const pathSolo = geoPath<any, d3Contour.ContourMultiPolygon>();
// -----------------------------------------------------------------------------
// Test Contour Generator
// -----------------------------------------------------------------------------
// Get contour generator -------------------------------------------------------
let contGen: d3Contour.Contours = d3Contour.contours();
// Configure contour generator =================================================
// size(...) -------------------------------------------------------------------
// set with chainability
contGen = contGen.size([n, m]);
size = contGen.size();
// smooth(...) -----------------------------------------------------------------
// set with chainability
contGen = contGen.smooth(true);
boolFlag = contGen.smooth();
// thresholds(...) -------------------------------------------------------------
// set with count
contGen = contGen.thresholds(10);
// set with array
const thresholds1 = range(1, 21)
.map(p => Math.pow(2, p));
contGen = contGen.thresholds(thresholds1);
// set with threshold array generator
contGen = contGen.thresholds(thresholdArrayGen); // mock
// set with threshold count generator
contGen = contGen.thresholds(thresholdSturges);
// get
thresholdGenerator = contGen.thresholds();
// Use contour generator =======================================================
pathStringMaybe = pathSolo(contGen(values)[0]);
// -----------------------------------------------------------------------------
// Test Contour Generator for Density Estimates
// -----------------------------------------------------------------------------
interface CustomDatum {
x: number;
y: number;
}
// Get contour generator -------------------------------------------------------
let contDensDefault: d3Contour.ContourDensity<[number, number]> = d3Contour.contourDensity();
let contDensCustom: d3Contour.ContourDensity<CustomDatum> = d3Contour.contourDensity<CustomDatum>();
// Configure contour generator =================================================
// x(...) ----------------------------------------------------------------------
// set with chainability
contDensCustom = contDensCustom.x((datum) => {
const d: CustomDatum = datum; // check passed in argument type
return d.x;
});
// get
const xAcc: (d: CustomDatum) => number = contDensCustom.x();
// y(...) ----------------------------------------------------------------------
// set with chainability
contDensCustom = contDensCustom.y((datum) => {
const d: CustomDatum = datum; // check passed in argument type
return d.y;
});
// get
const yAcc: (d: CustomDatum) => number = contDensCustom.y();
// size(...) -------------------------------------------------------------------
// set with chainability
contDensCustom = contDensCustom.size([900, 600]);
size = contDensCustom.size();
// cellSize(...) -----------------------------------------------------------------
// set with chainability
contDensCustom = contDensCustom.cellSize(3);
num = contDensCustom.cellSize();
// thresholds(...) -------------------------------------------------------------
// set with count
contDensCustom = contDensCustom.thresholds(10);
// set with array
contDensCustom = contDensCustom.thresholds([0.1, 0.25, 0.5, 0.75, 1]);
// set with threshold array generator
contDensCustom = contDensCustom.thresholds(thresholdArrayGen); // mock
// set with threshold count generator
contDensCustom = contDensCustom.thresholds(thresholdSturges);
// get
thresholdGenerator = contDensCustom.thresholds();
// bandwidth(...) --------------------------------------------------------------
// set with chainability
contDensCustom = contDensCustom.bandwidth(40);
// get
num = contDensCustom.bandwidth();
// Use contour generator =======================================================
const indNorm: CustomDatum[] = [];
const rX = randomNormal();
const rY = randomNormal(1, 2);
for (let i = 0; i < 1000; i++) {
indNorm.push({
x: rX(),
y: rY()
});
}
pathStringMaybe = pathSolo(contDensCustom(indNorm)[0]);

246
types/d3-contour/index.d.ts vendored Normal file
View File

@@ -0,0 +1,246 @@
// Type definitions for d3-contour 1.1
// Project: https://d3js.org/d3-contour/
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Hugues Stefanski <https://github.com/Ledragon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Last module patch version validated against: 1.1.0
import { MultiPolygon } from 'geojson';
import { ThresholdArrayGenerator, ThresholdCountGenerator } from 'd3-array';
/**
* An extended GeoJSON MultiPolygon representing a contour.
*/
export interface ContourMultiPolygon extends MultiPolygon {
/**
* Threshold value of the contour.
*/
value: number;
}
/**
* A contour generator which computes contour polygons by applying marching squares to a rectangular array of numeric values.
*
* For each threshold value, the contour generator constructs a GeoJSON MultiPolygon geometry object representing the area
* where the input values are greater than or equal to the threshold value.
* The geometry is in planar coordinates, where ⟨i + 0.5, j + 0.5⟩ corresponds to element i + jn in the input values array.
*
*/
export interface Contours {
/**
* Computes the contours for the given array of values, returning an array of GeoJSON MultiPolygon geometry objects.
* Each geometry object represents the area where the input values are greater than or equal to the corresponding threshold value;
* the threshold value for each geometry object is exposed as geometry.value.
*
* The returned geometry objects are typically passed to d3.geoPath to display,
* using null or d3.geoIdentity as the associated projection
*
* @param values Array of input values. The input values must be an array of length n×m where [n, m] is the contour generators size;
* furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩.
*/
(values: number[]): ContourMultiPolygon[];
/**
* Return the expected size of the input values grid, which defaults to [1,1].
*/
size(): [number, number];
/**
* Sets the expected size of the input values grid to the contour generator and returns the contour generator.
*
* @param size Size of the input values grid specified as an array [n, m]
* where n is the number of columns in the grid and m is the number of rows; n and m must be positive integers.
*/
size(size: [number, number]): this;
/**
* Returns the current smoothing flag, which defaults to true.
*/
smooth(): boolean;
/**
* Sets whether or not the generated contour polygons are smoothed using linear interpolation and returns the contour generator.
*
* @param smooth Flag to enable linear interpolation. The default is "true".
*/
smooth(smooth: boolean): this;
/**
* Returns the current threshold generator, which by default implements Sturges formula.
*/
thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator<number>;
/**
* Sets the threshold generator to use the specified count and returns this contour generator.
* The input values extent will be uniformly divided into approximately count bins.
*
* @param count Expected number of threshold bins.
*/
thresholds(count: number): this;
/**
* Sets the threshold generator to the specified array and returns this contour generator.
*
* Thresholds are defined as an array of values [x0, x1, …].
* The first generated contour corresponds to the area where the input values are greater than or equal to x0;
* the second contour corresponds to the area where the input values are greater than or equal to x1, and so on.
* Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value;
* the threshold value is exposed as geometry.value.
*
* @param thresholds Array of thresholds to use.
*/
thresholds(thresholds: number[]): this;
/**
* Sets the threshold generator to the specified function and returns this contour generator.
*
* Thresholds are defined as an array of values [x0, x1, …].
* The first generated contour corresponds to the area where the input values are greater than or equal to x0;
* the second contour corresponds to the area where the input values are greater than or equal to x1, and so on.
* Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value;
* the threshold value is exposed as geometry.value.
*
* @param thresholds A threshold generator function. The threshold generator function is passed the array of input values
* as its argument and returns either an array of calculated thresholds, or the count of thresholds to use.
*/
thresholds(thresholds: ThresholdCountGenerator | ThresholdArrayGenerator<number>): this;
}
/**
* Construct a new contour generator with the default settings.
*/
export function contours(): Contours;
/**
* A contour generator for density estimates.
*/
export interface ContourDensity<Datum> {
/**
* Estimates the density contours for the given array of data, returning an array of GeoJSON MultiPolygon geometry objects.
* Each geometry object represents the area where the estimated number of points per square pixel is greater than or equal to
* the corresponding threshold value; the threshold value for each geometry object is exposed as geometry.value.
* The returned geometry objects are typically passed to d3.geoPath to display, using null or d3.geoIdentity as the associated projection.
* See also d3.contours.
*
* The x- and y-coordinate for each data point are computed using density.x and density.y.
* The generated contours are only accurate within the estimators defined size.
*
* @param data Array of input data.
*/
(data: Datum[]): ContourMultiPolygon[];
/**
* Returns the current x-coordinate accessor.
* The default x-coordinate accessor is a functions which accepts as input a two-element array of numbers
* and returns the element at index 0.
*/
x(): (d: Datum) => number;
/**
* Sets the x-coordinate accessor and returns the density contour estimator.
*
* @param x An x-coordinate accessor function, which accepts as input an element of the input data array and returns the
* x-coordinate.
*/
x(x: (d: Datum) => number): this;
/**
* Returns the current y-coordinate accessor.
* The default y-coordinate accessor is a functions which accepts as input a two-element array of numbers
* and returns the element at index 1.
*/
y(): (d: Datum) => number;
/**
* Sets the y-coordinate accessor and returns the density contour estimator.
*
* @param y An y-coordinate accessor function, which accepts as input an element of the input data array and returns the
* y-coordinate.
*/
y(y: (d: Datum) => number): this;
/**
* Returns the current size, which defaults to [960, 500].
*/
size(): [number, number];
/**
* Sets the size of the density estimator to the specified bounds and returns the density contour estimator.
*
* @param size The size is specified as an array [width, height], where width is the maximum x-value and height is the maximum y-value.
*/
size(size: [number, number]): this;
/**
* Returns the current cell size, which defaults to 4.
*/
cellSize(): number;
/**
* Sets the size of individual cells in the underlying bin grid to the specified positive integer and returns the density contour estimator.
*
* The cell size is rounded down to the nearest power of two. Smaller cells produce more detailed contour polygons, but are more expensive to compute.
*
* @param cellSize Cell size, a positive integer.
*/
cellSize(cellSize: number): this;
/**
* Returns the current threshold generator, which by default generates about twenty nicely-rounded density thresholds.
*/
thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator<number>;
/**
* Sets the threshold generator to use the specified count and returns this density contour estimator.
* Approximately count uniformly-spaced nicely-rounded thresholds will be generated.
*
* @param count Expected number of thresholds.
*/
thresholds(count: number): this;
/**
* Sets the threshold generator to the specified array and returns this density contour estimator.
*
* Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area
* where the estimated density is greater than or equal to x0; the second contour corresponds to the area
* where the estimated density is greater than or equal to x1, and so on.
* Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value;
* the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero.
*
* @param thresholds Array of thresholds to use.
*/
thresholds(thresholds: number[]): this;
/**
* Sets the threshold generator to the specified function and returns this density contour estimator.
*
* Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area
* where the estimated density is greater than or equal to x0; the second contour corresponds to the area
* where the estimated density is greater than or equal to x1, and so on.
* Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value;
* the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero.
*
* @param thresholds A threshold generator function. The threshold generator function is passed the array of input values
* as its argument and returns either an array of calculated thresholds, or the count of thresholds to use.
*/
thresholds(thresholds: ThresholdCountGenerator | ThresholdArrayGenerator<number>): this;
/**
* Returns the current bandwidth, which defaults to 20.4939….
*/
bandwidth(): number;
/**
* Sets the bandwidth (the standard deviation) of the Gaussian kernel and returns the density contour estimator.
*
* @param bandwidth Bandwidth (the standard deviation) of the Gaussian kernel.
* The specified bandwidth is currently rounded to the nearest supported value by this implementation, and must be nonnegative.
*/
bandwidth(bandwidth: number): this;
}
/**
* Construct a new contour generator for density estimates with the default settings.
*
* The default settings assume that, the elements of the data array used
* with the density contour generator are two-element arrays. The first element
* corresponds to the x-dimension, the second to the y-dimension.
*/
export function contourDensity(): ContourDensity<[number, number]>;
/**
* Construct a new contour generator for density estimates.
*
* The generic refers to the data type of an element in the data array
* used with the density contour generator.
*
* Important: ensure that the x- and y-accessor functions are configured to
* match the data type used for the generic Datum.
*/
export function contourDensity<Datum>(): ContourDensity<Datum>;

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"d3-contour-tests.ts"
]
}

View File

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

View File

@@ -88,6 +88,12 @@ circleDrag = circleDrag
containerAccessor = circleDrag.container();
// clickDistance(...) ---------------------------------------------------------
circleDrag = circleDrag.clickDistance(5);
const distance: number = circleDrag.clickDistance();
// set and get filter ---------------------------------------------------------
let filterFn: (this: SVGCircleElement, datum: CircleDatum, index: number, group: SVGCircleElement[] | NodeListOf<SVGCircleElement>) => boolean;

View File

@@ -1,9 +1,9 @@
// Type definitions for D3JS d3-drag module 1.0
// Type definitions for D3JS d3-drag module 1.1
// Project: https://github.com/d3/d3-drag/
// 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
// Last module patch version validated against: 1.0.2
// Last module patch version validated against: 1.1.0
import { ArrayLike, Selection, ValueFn } from 'd3-selection';
@@ -164,6 +164,20 @@ export interface DragBehavior<GElement extends DraggedElementBaseType, Datum, Su
*/
subject(accessor: ValueFn<GElement, Datum, Subject>): this;
/**
* Return the current click distance threshold, which defaults to zero.
*/
clickDistance(): number;
/**
* Set the maximum distance that the mouse can move between mousedown and mouseup that will trigger
* a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to
* distance from its position on mousedown, the click event follwing mouseup will be suppressed.
*
* @param distance The distance threshold between mousedown and mouseup measured in client coordinates (event.clientX and event.clientY).
* The default is zero.
*/
clickDistance(distance: number): this;
/**
* Return the first currently-assigned listener matching the specified typenames, if any.
*

View File

@@ -87,7 +87,7 @@ export interface PolynomialEasingFactory {
*
* @param e Exponent for polynomial easing.
*/
exponent(e: number): PolynomialEasingFactory;
exponent(e: number): PolynomialEasingFactory;
}
/**
@@ -240,7 +240,7 @@ export interface BackEasingFactory {
*
* @param s Overshoot parameter
*/
overshoot(s: number): BackEasingFactory;
overshoot(s: number): BackEasingFactory;
}
/**
@@ -282,14 +282,14 @@ export interface ElasticEasingFactory {
*
* @param a Amplitude for elastic easing.
*/
amplitude(a: number): ElasticEasingFactory;
/**
* Returns a new elastic easing with the specified amplitude a.
* Defaults to 0.3,if not specified.
*
* @param p Period for elastic easing.
*/
period(p: number): ElasticEasingFactory;
amplitude(a: number): ElasticEasingFactory;
/**
* Returns a new elastic easing with the specified amplitude a.
* Defaults to 0.3,if not specified.
*
* @param p Period for elastic easing.
*/
period(p: number): ElasticEasingFactory;
}
/**

View File

@@ -48,7 +48,6 @@ let type: 'e' | 'f' | 'g' | 'r' | 's' | '%' | 'p' | 'b' | 'o' | 'd' | 'x' | 'X'
let formatString: string = specifier.toString();
// ----------------------------------------------------------------------
// Test Precision Suggestors
// ----------------------------------------------------------------------
@@ -76,13 +75,22 @@ localeDef = {
grouping: [3],
currency: ["", ""],
numerals : ["\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669"]
}
};
localeDef = {
decimal: "\u066b",
thousands: "\u066c",
grouping: [3],
currency: ["", ""],
percent : "\u202f%"
};
let decimal: string = localeDef.decimal;
let thousands: string = localeDef.thousands;
let grouping: Array<number> = localeDef.grouping;
let grouping: number[] = localeDef.grouping;
let currency: [string, string] = localeDef.currency;
let numerals: string[] | undefined = localeDef.numerals;
let percent: string | undefined = localeDef.percent;
localeObj = d3Format.formatLocale(localeDef);

View File

@@ -1,9 +1,9 @@
// Type definitions for D3JS d3-format module 1.1
// Type definitions for D3JS d3-format module 1.2
// Project: https://github.com/d3/d3-format/
// 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
// Last module patch version validated against: 1.1.0
// Last module patch version validated against: 1.2.0
/**
* Specification of locale to use when creating a new FormatLocaleObject
@@ -27,16 +27,19 @@ export interface FormatLocaleDefinition {
*/
currency: [string, string];
/**
* An array of ten strings to replace the numerals 0-9.
* An optional array of ten strings to replace the numerals 0-9.
*/
numerals?: string[];
/**
* An optional symbol to replace the `percent` suffix; the percent suffix (defaults to "%")
*/
percent?: string;
}
/**
* A Format Locale Object
*/
export interface FormatLocaleObject {
/**
* Returns a new format function for the given string specifier. The returned function
* takes a number as the only argument, and returns a string representing the formatted number.
@@ -219,7 +222,6 @@ export function precisionFixed(step: number): number;
*/
export function precisionPrefix(step: number, value: number): number;
/**
* Returns a suggested decimal precision for format types that round to significant digits
* given the specified numeric step and max values.

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -3,10 +3,10 @@
// Definitions by: Hugues Stefanski <https://github.com/Ledragon>, Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="geojson" />
// Last module patch version validated against: 1.6.1
import * as GeoJSON from 'geojson';
// ----------------------------------------------------------------------
// Shared Interfaces and Types
// ----------------------------------------------------------------------
@@ -926,7 +926,8 @@ export interface GeoPath<This, DatumObject extends GeoPermissibleObjects> {
*
* Any additional arguments are passed along to the pointRadius accessor.
*
* If the rendering context is null, the function returns an SVG Path string, otherwise the function renders to the current context.
* IMPORTANT: If the rendering context of the geoPath generator is null,
* then the geoPath is returned as an SVG path data string.
*
* Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover).
* Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction.
@@ -935,7 +936,36 @@ export interface GeoPath<This, DatumObject extends GeoPermissibleObjects> {
*
* @param object An object to be rendered.
*/
(this: This, object: DatumObject, ...args: any[]): string | undefined;
(this: This, object: DatumObject, ...args: any[]): string | null;
/**
* Renders the given object, which may be any GeoJSON feature or geometry object:
*
* + Point - a single position.
* + MultiPoint - an array of positions.
* + LineString - an array of positions forming a continuous line.
* + MultiLineString - an array of arrays of positions forming several lines.
* + Polygon - an array of arrays of positions forming a polygon (possibly with holes).
* + MultiPolygon - a multidimensional array of positions forming multiple polygons.
* + GeometryCollection - an array of geometry objects.
* + Feature - a feature containing one of the above geometry objects.
* + FeatureCollection - an array of feature objects.
*
* The type Sphere is also supported, which is useful for rendering the outline of the globe; a sphere has no coordinates.
*
*
* Any additional arguments are passed along to the pointRadius accessor.
*
* IMPORTANT: If the geoPath generator has been configured with a rendering context,
* then the geoPath is rendered to this context as a sequence of path method calls and this function returns void.
*
* Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover).
* Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction.
*
* The first generic type of the GeoPath generator used, must correspond to the "this" context bound to the function upon invocation.
*
* @param object An object to be rendered.
*/
(this: This, object: DatumObject, ...args: any[]): void;
/**
* Returns the projected planar area (typically in square pixels) for the specified GeoJSON object.

View File

@@ -7,7 +7,7 @@
*/
import * as d3Random from 'd3-random';
import * as seedrandom from 'seedrandom';
// ------------------------------------------------------------
// Preparatory Steps
@@ -19,40 +19,70 @@ let randomNumberGenerator: () => number;
// randomUniform
// ------------------------------------------------------------
randomNumberGenerator = d3Random.randomUniform();
randomNumberGenerator = d3Random.randomUniform(0.2);
randomNumberGenerator = d3Random.randomUniform(0.2, 5);
let prngUniform: d3Random.RandomUniform;
prngUniform = d3Random.randomUniform;
prngUniform = d3Random.randomUniform.source(seedrandom("Schroedinger's flea."));
randomNumberGenerator = prngUniform();
randomNumberGenerator = prngUniform(0.2);
randomNumberGenerator = prngUniform(0.2, 5);
// ------------------------------------------------------------
// randomNormal
// ------------------------------------------------------------
randomNumberGenerator = d3Random.randomNormal();
randomNumberGenerator = d3Random.randomNormal(3);
randomNumberGenerator = d3Random.randomNormal(3, 4);
let prngNormal: d3Random.RandomNormal;
prngNormal = d3Random.randomNormal;
prngNormal = d3Random.randomNormal.source(seedrandom("Schroedinger's flea."));
randomNumberGenerator = prngNormal();
randomNumberGenerator = prngNormal(3);
randomNumberGenerator = prngNormal(3, 4);
// ------------------------------------------------------------
// randomLogNormal
// ------------------------------------------------------------
randomNumberGenerator = d3Random.randomLogNormal();
randomNumberGenerator = d3Random.randomLogNormal(3);
randomNumberGenerator = d3Random.randomLogNormal(3, 4);
let prngLogNormal: d3Random.RandomLogNormal;
prngLogNormal = d3Random.randomLogNormal;
prngLogNormal = d3Random.randomLogNormal.source(seedrandom("Schroedinger's flea."));
randomNumberGenerator = prngLogNormal();
randomNumberGenerator = prngLogNormal(3);
randomNumberGenerator = prngLogNormal(3, 4);
// ------------------------------------------------------------
// randomBates
// ------------------------------------------------------------
randomNumberGenerator = d3Random.randomBates(3);
let prngBates: d3Random.RandomBates;
prngBates = d3Random.randomBates;
prngBates = d3Random.randomBates.source(seedrandom("Schroedinger's flea."));
randomNumberGenerator = prngBates(3);
// ------------------------------------------------------------
// randomIrwinHall
// ------------------------------------------------------------
randomNumberGenerator = d3Random.randomIrwinHall(3);
let prngIrwinHall: d3Random.RandomIrwinHall;
prngIrwinHall = d3Random.randomIrwinHall;
prngIrwinHall = d3Random.randomIrwinHall.source(seedrandom("Schroedinger's flea."));
randomNumberGenerator = prngIrwinHall(3);
// ------------------------------------------------------------
// randomExponential
// ------------------------------------------------------------
randomNumberGenerator = d3Random.randomExponential(1 / 40);
let prngExponential: d3Random.RandomExponential;
prngExponential = d3Random.randomExponential;
prngExponential = d3Random.randomExponential.source(seedrandom("Schroedinger's flea."));
randomNumberGenerator = prngExponential(1 / 40);

View File

@@ -1,55 +1,112 @@
// Type definitions for D3JS d3-random module v1.0.1
// Type definitions for D3JS d3-random module 1.1
// Project: https://github.com/d3/d3-random/
// 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
/**
* Returns a function for generating random numbers with a uniform distribution).
* The minimum allowed value of a returned number is min, and the maximum is max.
* If min is not specified, it defaults to 0; if max is not specified, it defaults to 1.
*
* @param min The minimum allowed value of a returned number, defaults to 0.
* @param max The maximum allowed value of a returned number, defaults to 1.
*/
export function randomUniform(min?: number, max?: number): () => number;
// Last module patch version validated against: 1.1.0
export interface RandomNumberGenerationSource {
/**
* Returns the same type of function for generating random numbers but where the given random number
* generator source is used as the source of randomness instead of Math.random.
* This is useful when a seeded random number generator is preferable to Math.random.
*
* @param source Source (pseudo-)random number generator implementing the Math.random interface.
* The given random number generator must implement the same interface as Math.random and
* only return values in the range [0, 1).
*/
source(source: () => number): this;
}
/**
* Returns a function for generating random numbers with a normal (Gaussian) distribution.
* The expected value of the generated numbers is mu, with the given standard deviation sigma.
* If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1.
*
* @param mu Expected value, defaults to 0.
* @param sigma Standard deviation, defaults to 1.
* A configurable random number generator for the uniform distribution.
*/
export function randomNormal(mu?: number, sigma?: number): () => number;
export interface RandomUniform extends RandomNumberGenerationSource {
/**
* Returns a function for generating random numbers with a uniform distribution).
* The minimum allowed value of a returned number is min, and the maximum is max.
* If min is not specified, it defaults to 0; if max is not specified, it defaults to 1.
*
* @param min The minimum allowed value of a returned number, defaults to 0.
* @param max The maximum allowed value of a returned number, defaults to 1.
*/
(min?: number, max?: number): () => number;
}
export const randomUniform: RandomUniform;
/**
* Returns a function for generating random numbers with a log-normal distribution. The expected value of the random variables natural logrithm is mu,
* with the given standard deviation sigma. If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1.
*
* @param mu Expected value, defaults to 0.
* @param sigma Standard deviation, defaults to 1.
* A configurable random number generator for the normal (Gaussian) distribution.
*/
export function randomLogNormal(mu?: number, sigma?: number): () => number;
export interface RandomNormal extends RandomNumberGenerationSource {
/**
* Returns a function for generating random numbers with a normal (Gaussian) distribution.
* The expected value of the generated numbers is mu, with the given standard deviation sigma.
* If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1.
*
* @param mu Expected value, defaults to 0.
* @param sigma Standard deviation, defaults to 1.
*/
(mu?: number, sigma?: number): () => number;
}
export const randomNormal: RandomNormal;
/**
* Returns a function for generating random numbers with a Bates distribution with n independent variables.
*
* @param n Number of independent random variables to use.
* A configurable random number generator for the log-normal distribution.
*/
export function randomBates(n: number): () => number;
export interface RandomLogNormal extends RandomNumberGenerationSource {
/**
* Returns a function for generating random numbers with a log-normal distribution. The expected value of the random variables natural logrithm is mu,
* with the given standard deviation sigma. If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1.
*
* @param mu Expected value, defaults to 0.
* @param sigma Standard deviation, defaults to 1.
*/
(mu?: number, sigma?: number): () => number;
}
export const randomLogNormal: RandomLogNormal;
/**
* Returns a function for generating random numbers with an IrwinHall distribution with n independent variables.
*
* @param n Number of independent random variables to use.
* A configurable random number generator for the Bates distribution.
*/
export function randomIrwinHall(n: number): () => number;
export interface RandomBates extends RandomNumberGenerationSource {
/**
* Returns a function for generating random numbers with a Bates distribution with n independent variables.
*
* @param n Number of independent random variables to use.
*/
(n: number): () => number;
}
export const randomBates: RandomBates;
/**
* Returns a function for generating random numbers with an exponential distribution with the rate lambda;
* equivalent to time between events in a Poisson process with a mean of 1 / lambda.
*
* @param lambda Expected time between events.
* A configurable random number generator for the IrwinHall distribution.
*/
export function randomExponential(lambda: number): () => number;
export interface RandomIrwinHall extends RandomNumberGenerationSource {
/**
* Returns a function for generating random numbers with an IrwinHall distribution with n independent variables.
*
* @param n Number of independent random variables to use.
*/
(n: number): () => number;
}
export const randomIrwinHall: RandomIrwinHall;
/**
* A configurable random number generator for the exponential distribution.
*/
export interface RandomExponential extends RandomNumberGenerationSource {
/**
* Returns a function for generating random numbers with an exponential distribution with the rate lambda;
* equivalent to time between events in a Poisson process with a mean of 1 / lambda.
*
* @param lambda Expected time between events.
*/
(lambda: number): () => number;
}
export const randomExponential: RandomExponential;

View File

@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -19,4 +19,4 @@
"index.d.ts",
"d3-random-tests.ts"
]
}
}

View File

@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"max-line-length": [false, 140]
}
}

View File

@@ -0,0 +1,258 @@
/**
* Typescript definition tests for d3/d3-sankey module
*
* Note: These tests are intended to test the definitions only
* in the sense of typing and call signature consistency. They
* are not intended as functional tests.
*/
import * as d3Sankey from 'd3-sankey';
import {select, Selection} from 'd3-selection';
// ---------------------------------------------------------------------------
// Preparatory Steps
// ---------------------------------------------------------------------------
// Create interfaces for the user-provided node/link attributes, which are NOT mandated or calculated by
// the Sankey layout generator. The latter are reflected in the SankeyNode and SankeyLink interfaces provided
// by the definitions file
interface SNodeExtra {
nodeId: number;
name: string;
}
interface SLinkExtra {
uom: string;
}
// For convenience
type SNode = d3Sankey.SankeyNode<SNodeExtra, SLinkExtra>;
type SLink = d3Sankey.SankeyLink<SNodeExtra, SLinkExtra>;
interface DAG {
nodes: SNode[];
links: SLink[];
}
const graph: DAG = {
nodes: [{
nodeId: 0,
name: "node0"
}, {
nodeId: 1,
name: "node1"
}, {
nodeId: 2,
name: "node2"
}, {
nodeId: 3,
name: "node3"
}, {
nodeId: 4,
name: "node4"
}],
links: [{
source: 0,
target: 2,
value: 2,
uom: 'Widget(s)'
}, {
source: 1,
target: 2,
value: 2,
uom: 'Widget(s)'
}, {
source: 1,
target: 3,
value: 2,
uom: 'Widget(s)'
}, {
source: 0,
target: 4,
value: 2,
uom: 'Widget(s)'
}, {
source: 2,
target: 3,
value: 2,
uom: 'Widget(s)'
}, {
source: 2,
target: 4,
value: 2,
uom: 'Widget(s)'
}, {
source: 3,
target: 4,
value: 4,
uom: 'Widget(s)'
}]
};
let sNodes: SNode[];
let sLinks: SLink[];
let num: number;
let numMaybe: number | undefined;
let str: string;
let size: [number, number];
const svgLinkPaths = select<SVGSVGElement, undefined>('svg').selectAll<SVGPathElement, SLink>('.linkPath'); // assume mock DOM
// ---------------------------------------------------------------------------
// Obtain SankeyLayout Generator
// ---------------------------------------------------------------------------
let slgDefault: d3Sankey.SankeyLayout<{}, {}> = d3Sankey.sankey();
let slgDAG: d3Sankey.SankeyLayout<SNodeExtra, SLinkExtra> = d3Sankey.sankey<SNodeExtra, SLinkExtra>();
// ---------------------------------------------------------------------------
// NodeWidth
// ---------------------------------------------------------------------------
// Set -----------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.nodeWidth(32);
// Get -----------------------------------------------------------------------
num = slgDAG.nodeWidth();
// ---------------------------------------------------------------------------
// NodePadding
// ---------------------------------------------------------------------------
// Set -----------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.nodePadding(8);
// Get -----------------------------------------------------------------------
num = slgDAG.nodePadding();
// ---------------------------------------------------------------------------
// Size
// ---------------------------------------------------------------------------
// Set -----------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.size([1200, 800]);
// Get -----------------------------------------------------------------------
size = slgDAG.size();
// ---------------------------------------------------------------------------
// Nodes
// ---------------------------------------------------------------------------
// Set -----------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.nodes(graph.nodes);
// Get -----------------------------------------------------------------------
sNodes = slgDAG.nodes();
// ---------------------------------------------------------------------------
// Links
// ---------------------------------------------------------------------------
// Set -----------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.links(graph.links);
// Get -----------------------------------------------------------------------
sLinks = slgDAG.links();
// ---------------------------------------------------------------------------
// Compute Layout
// ---------------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.layout(22);
// ---------------------------------------------------------------------------
// Relayout
// ---------------------------------------------------------------------------
// test return type for chainability
slgDAG = slgDAG.relayout();
// ---------------------------------------------------------------------------
// Obtain and Use Link SVG Path Generator
// ---------------------------------------------------------------------------
let pathGen: d3Sankey.SankeyLinkPathGenerator<SNodeExtra, SLinkExtra>;
pathGen = slgDAG.link();
// Adjust Link SVG Path Generator curvature ----------------------------------
// test return type
pathGen = pathGen.curvature(0.6);
num = pathGen.curvature();
// uses
let svgPathString: string = pathGen(slgDAG.links()[0]);
svgLinkPaths.attr('d', pathGen);
// ---------------------------------------------------------------------------
// Shape test Node/Link related interfaces and types
// ---------------------------------------------------------------------------
// Sankey Node --------------------------------------------------------------
let sNode = sNodes[0];
// User-specified extra properties:
num = sNode.nodeId;
str = sNode.name;
// Sankey Layout calculated (if layout has been run, otherwise undefined):
numMaybe = sNode.dx;
numMaybe = sNode.x;
numMaybe = sNode.dy;
numMaybe = sNode.y;
numMaybe = sNode.value;
let linksArrMaybe: SLink[] | undefined;
linksArrMaybe = sNode.sourceLinks;
linksArrMaybe = sNode.targetLinks;
// Sankey Link --------------------------------------------------------------
let sLink = sLinks[0];
// User-specified extra properties:
str = sLink.uom;
// Sankey Layout mandated link properties:
num = sLink.value;
// Node depending on initialization strategy and whether
// layout(...) was invoked, the source and target nodes may be numbers
// objects without the Sankey layout coordinates, or objects with calculated
// information
let numOrSankeyNode: number | SNode;
numOrSankeyNode = sLink.source;
numOrSankeyNode = sLink.target;
// Sankey Layout calculated (if layout has been run, otherwise undefined):
numMaybe = sLink.sy;
numMaybe = sLink.ty;
numMaybe = sLink.dy;

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