Merge pull request #1 from DefinitelyTyped/master

Update
This commit is contained in:
Julien Dufresne
2017-01-03 17:25:06 -05:00
committed by GitHub
99 changed files with 3789 additions and 1394 deletions
-35
View File
@@ -1,35 +0,0 @@
import { defaults, limits, hash, verify, generateSalt } from 'argon2';
main();
async function main() {
const defaultTimeCost: number = defaults.timeCost;
const defaultMemoryCost: number = defaults.memoryCost;
const defaultParallelism: number = defaults.parallelism;
const defaultArgon2d: boolean = defaults.argon2d;
const minMemoryCost: number = limits.memoryCost.min;
const maxMemoryCost: number = limits.memoryCost.max;
const minTimeCost: number = limits.timeCost.min;
const maxTimeCost: number = limits.timeCost.max;
const minParallelism: number = limits.parallelism.min;
const maxParallelism: number = limits.parallelism.max;
const options = {
timeCost: 4,
memoryCost: 13,
parallelism: 2,
argon2d: true,
};
const hash1: string = await hash('secret', new Buffer(''), options);
const hash2: string = await hash('secret', new Buffer(''), {});
const hash3: string = await hash('secret', new Buffer(''));
const verified: boolean = await verify('long-hash', 'secret');
const salt1: Buffer = await generateSalt();
const salt2: Buffer = await generateSalt(32);
}
-44
View File
@@ -1,44 +0,0 @@
// Type definitions for argon2 0.14
// Project: https://github.com/ranisalt/node-argon2#readme
// Definitions by: Peter Safranek <https://github.com/pe8ter>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare namespace argon2 {
export var defaults: {
timeCost: number;
memoryCost: number;
parallelism: number;
argon2d: boolean;
};
export var limits: {
memoryCost: {
min: number;
max: number;
};
timeCost: {
min: number;
max: number;
};
parallelism: {
min: number;
max: number;
};
};
export function hash(plain: string, salt: Buffer, options?: {
timeCost?: number;
memoryCost?: number;
parallelism?: number;
argon2d?: boolean;
}): Promise<string>;
export function verify(hash: string, plain: string): Promise<boolean>;
export function generateSalt(length?: number): Promise<Buffer>;
}
export = argon2;
+13
View File
@@ -29,3 +29,16 @@ function testFunctionReturningPromise() {
console.log("finally callback");
});
}
function testPromiseRejection() {
new Promise<string>((resolve, reject) => {
reject(new Error("problem occurred"));
})
.catch((error) => {
return "recovered from error";
})
.then((value) => {
return value.toUpperCase();
});
}
+113 -5
View File
@@ -27,6 +27,11 @@
* the Promise<T> and PromiseConstructor interfaces defined in the standard ts library.
* For various reasons this couldn't be done in The `bluebird` typings.
*
* 4. Contributors: After changing this file please manually test these cases (via altering ./tsconfig.json ):
* a. target es5, no `lib` key
* b. target es6, no `lib` key
* c. target es5, latest "es20xx", e.g. "es2017"
* d. target es6, latest "es20xx", e.g. "es2017"
*/
import * as Bluebird from "bluebird";
@@ -35,7 +40,78 @@ declare global {
/*
* Patch all instance method
*/
interface Promise<T> extends Bluebird<T> {}
interface Promise<T> {
all: typeof Bluebird.prototype.all;
any: typeof Bluebird.prototype.any;
asCallback: typeof Bluebird.prototype.asCallback;
bind: typeof Bluebird.prototype.bind;
call: typeof Bluebird.prototype.call;
cancel: typeof Bluebird.prototype.cancel;
// catch: typeof Bluebird.prototype.catch;
caught: typeof Bluebird.prototype.caught;
delay: typeof Bluebird.prototype.delay;
disposer: typeof Bluebird.prototype.disposer;
done: typeof Bluebird.prototype.done;
each: typeof Bluebird.prototype.each;
error: typeof Bluebird.prototype.error;
filter: typeof Bluebird.prototype.filter;
finally: typeof Bluebird.prototype.finally;
get: typeof Bluebird.prototype.get;
isCancelled: typeof Bluebird.prototype.isCancelled;
isFulfilled: typeof Bluebird.prototype.isFulfilled;
isPending: typeof Bluebird.prototype.isPending;
isRejected: typeof Bluebird.prototype.isRejected;
isResolved: typeof Bluebird.prototype.isResolved;
lastly: typeof Bluebird.prototype.lastly;
map: typeof Bluebird.prototype.map;
mapSeries: typeof Bluebird.prototype.mapSeries;
nodeify: typeof Bluebird.prototype.nodeify;
props: typeof Bluebird.prototype.props;
race: typeof Bluebird.prototype.race;
reason: typeof Bluebird.prototype.reason;
reduce: typeof Bluebird.prototype.reduce;
reflect: typeof Bluebird.prototype.reflect;
return: typeof Bluebird.prototype.return;
some: typeof Bluebird.prototype.some;
spread: typeof Bluebird.prototype.spread;
suppressUnhandledRejections: typeof Bluebird.prototype.suppressUnhandledRejections;
tap: typeof Bluebird.prototype.tap;
// then: typeof Bluebird.prototype.then;
thenReturn: typeof Bluebird.prototype.thenReturn;
thenThrow: typeof Bluebird.prototype.thenThrow;
throw: typeof Bluebird.prototype.throw;
timeout: typeof Bluebird.prototype.timeout;
toJSON: typeof Bluebird.prototype.toJSON;
toString: typeof Bluebird.prototype.toString;
value: typeof Bluebird.prototype.value;
/*
* Copy&paste ::then and ::catch from lib.es2015.promise.d.ts, because Bluebird's typings are not
* in line with the standard lib.
*
* This is only needed for es5 target, which doesn't include the lib.es2015.promise.d.ts typings.
*
* @todo Make Bluebird's typings be in line with the standard lib.
*/
then(onfulfilled?: ((value: T) => T | PromiseLike<T>) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike<T>) | undefined | null): Promise<T>;
then<TResult>(onfulfilled: ((value: T) => T | PromiseLike<T>) | undefined | null, onrejected: (reason: any) => TResult | PromiseLike<TResult>): Promise<T | TResult>;
then<TResult>(onfulfilled: (value: T) => TResult | PromiseLike<TResult>, onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<TResult>;
then<TResult1, TResult2>(onfulfilled: (value: T) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;
catch(onrejected?: ((reason: any) => T | PromiseLike<T>) | undefined | null): Promise<T>;
catch<TResult>(onrejected: (reason: any) => TResult | PromiseLike<TResult>): Promise<T | TResult>;
/*
* TypeScript disallows adding overrides via `catch: typeof Bluebird.prototype.catch`. Copy&paste them then.
*
* @todo Duplication of code is never ideal. See whether there's a better way of achieving this.
*/
catch(predicate: (error: any) => boolean, onReject: (error: any) => T | Bluebird.Thenable<T> | void | Bluebird.Thenable<void>): Bluebird<T>;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U | T>;
catch<E extends Error>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => T | Bluebird.Thenable<T> | void | Bluebird.Thenable<void>): Bluebird<T>;
catch<E extends Error, U>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable<U>): Bluebird<U | T>;
catch(predicate: Object, onReject: (error: any) => T | Bluebird.Thenable<T> | void | Bluebird.Thenable<void>): Bluebird<T>;
catch<U>(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U | T>;
}
/*
* Patch all static methods and the constructor
@@ -43,7 +119,7 @@ declare global {
interface PromiseConstructor {
new <T>(callback: (resolve: (thenableOrResult?: T | Bluebird.Thenable<T>) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void): Promise<T>;
all: typeof Bluebird.all;
// all: typeof Bluebird.all;
any: typeof Bluebird.any;
attempt: typeof Bluebird.attempt;
bind: typeof Bluebird.bind;
@@ -66,13 +142,45 @@ declare global {
promisify: typeof Bluebird.promisify;
promisifyAll: typeof Bluebird.promisifyAll;
props: typeof Bluebird.props;
race: typeof Bluebird.race;
// race: typeof Bluebird.race;
reduce: typeof Bluebird.reduce;
reject: typeof Bluebird.reject;
resolve: typeof Bluebird.resolve;
// reject: typeof Bluebird.reject;
// resolve: typeof Bluebird.resolve;
some: typeof Bluebird.some;
try: typeof Bluebird.try;
using: typeof Bluebird.using;
/*
* Copy&paste from lib.es2015.promise.d.ts, because Bluebird's typings are not in line with the standard lib.
*
* This is only needed for es5 target, which doesn't include the lib.es2015.promise.d.ts typings.
*
* @todo Make Bluebird's typings be in line with the standard lib.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]>;
race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>;
race<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;
race<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>;
race<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7>;
race<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<T1 | T2 | T3 | T4 | T5 | T6>;
race<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>]): Promise<T1 | T2 | T3 | T4 | T5>;
race<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>]): Promise<T1 | T2 | T3 | T4>;
race<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<T1 | T2 | T3>;
race<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<T1 | T2>;
race<T>(values: (T | PromiseLike<T>)[]): Promise<T>;
reject(reason: any): Promise<never>;
reject<T>(reason: any): Promise<T>;
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
resolve(): Promise<void>;
}
/*
+4
View File
@@ -9,6 +9,10 @@
"typeRoots": [
"../"
],
"lib": [
"es2017",
"dom"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
+4 -1
View File
@@ -1,6 +1,9 @@
{
"extends": "../tslint.json",
"rules": {
"no-empty-interface": false
"no-empty-interface": false,
"array-type": false,
"unified-signatures": false,
"forbidden-types": false
}
}
+1
View File
@@ -42,6 +42,7 @@ interface DatepickerOptions {
showOnFocus?: boolean;
immediateUpdates?: boolean;
title?: string;
container?: string;
}
interface DatepickerCustomFormatOptions {
@@ -0,0 +1,14 @@
/// <reference types="jquery" />
$('#myForm').validator();
$('#myForm').validator('update');
$('#myForm').validator('validate');
$('#myForm').validator('destroy');
$('#myForm').validator({
delay: 500,
html: false,
disable: false,
focus: true,
feedback: {},
custom: {}
});
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for bootstrap-validator 0.11
// Project: https://github.com/1000hz/bootstrap-validator
// Definitions by: Brady Liles <https://github.com/BradyLiles/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery"/>
interface ValidatorOptions {
delay?: number;
html?: boolean;
disable?: boolean;
focus?: boolean;
feedback?: any;
custom?: any;
}
interface JQuery {
validator(options?: ValidatorOptions): JQuery;
validator(command: string): JQuery;
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bootstrap-validator-tests.ts"
]
}
+3
View File
@@ -29,6 +29,8 @@ function test_containSubset() {
});
obj.should.containSubset({ a: 'b' });
assert.containSubset(obj, { a: 'b' });
}
function test_notContainSubset() {
@@ -52,6 +54,7 @@ function test_arrayContainSubset() {
expect(list).to.containSubset([{a:'a', b: 'b'}]);
list.should.containSubset([{a:'a', b: 'b'}]);
assert.containSubset(list, [{a:'a', b: 'b'}]);
}
function test_arrayNotContainSubset() {
+11 -8
View File
@@ -1,17 +1,20 @@
// Type definitions for chai-subset 1.0.0
// Type definitions for chai-subset 1.3
// Project: https://github.com/e-conomic/chai-subset
// Definitions by: Sam Noedel <https://github.com/delta62/>, Andrew Brown <https://github.com/AGBrown>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="chai" />
declare namespace Chai {
interface Assertion {
containSubset(obj: Object): Assertion;
declare global {
namespace Chai {
interface Assertion {
containSubset(expected: any): Assertion;
}
interface Assert {
containSubset(val: any, exp: any, msg?: string): void;
}
}
}
declare module "chai-subset" {
function chaiSubset(chai: any, utils: any): void;
export = chaiSubset;
}
declare function chaiSubset(chai: any, utils: any): void;
export = chaiSubset;
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+18 -12
View File
@@ -9,20 +9,25 @@ var watcher = chokidar.watch('file, dir, or glob', {
var log = console.log.bind(console);
let str: string;
let any: any;
let stats: fs.Stats;
watcher
.on('add', function(path:string) { log('File', path, 'has been added'); })
.on('addDir', function(path:string) { log('Directory', path, 'has been added'); })
.on('change', function(path:string) { log('File', path, 'has been changed'); })
.on('unlink', function(path:string) { log('File', path, 'has been removed'); })
.on('unlinkDir', function(path:string) { log('Directory', path, 'has been removed'); })
.on('error', function(error:any) { log('Error happened', error); })
.on('ready', function() { log('Initial scan complete. Ready for changes.'); })
.on('raw', function(event:Event, path:string, details:any) { log('Raw event info:', event, path, details); })
.on('add', path => { str = path; })
.on('addDir', path => { str = path; })
.on('change', path => { str = path; })
.on('unlink', path => { str = path; })
.on('unlinkDir', path => { str = path; })
.on('error', (error) => { any = error; })
.on('ready', () => { })
.on('raw', (event, path, details) => { str = event; str = path; any = details; })
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', function(path:string, stats:fs.Stats) {
if (stats) console.log('File', path, 'changed size to', stats.size);
watcher.on('change', (path, _stats) => {
str = path;
stats = _stats;
});
// Watch new files.
@@ -36,6 +41,7 @@ watcher.unwatch('new-file*');
watcher.close();
// One-liner
require('chokidar').watch('.', {ignored: /[\/\\]\./}).on('all', function(event:string, path:string) {
console.log(event, path);
chokidar.watch('.', {ignored: /[\/\\]\./}).on('all', (event, path) => {
str = event;
str = path;
});
+2 -1
View File
@@ -18,7 +18,8 @@ declare module "chokidar"
on(event: 'add', fn: (path: string, stats?: fs.Stats) => void): this;
on(event: 'change', fn: (path: string, stats?: fs.Stats) => void): this;
on(event: 'unlink', fn: (path: string) => void): this;
on(event: 'raw', fn: (event: Event, path:string, details:any) => void): this;
on(event: 'raw', fn: (event: string, path:string, details:any) => void): this;
on(event: 'all', fn: (event: string, path: string) => void): this;
on(event: string, fn: (path: string) => void): this;
close(): this;
}
+4 -3
View File
@@ -1,5 +1,6 @@
import cs = require('configstore');
import Configstore = require('configstore');
var cs = new Configstore('foo');
var value: any;
var key: string;
@@ -9,9 +10,9 @@ var object:Object;
cs.set(key, value);
value = cs.get(key);
cs.del(key);
cs.delete(key);
object = cs.all;
cs.all = object;
num = cs.size;
key = cs.path;
key = cs.path;
+63 -29
View File
@@ -1,37 +1,71 @@
// Type definitions for configstore 0.3.0
// Type definitions for configstore 2.1
// Project: https://github.com/yeoman/configstore
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions by: ArcticLight <https://github.com/ArcticLight>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = Configstore;
/*
Set an item
*/
export declare function set(key: string, val: any): void;
declare class Configstore {
constructor(packageName: string, defaults?: any, options?: Configstore.ConfigstoreOptions);
/*
Get an item
*/
export declare function get(key: string): any;
/**
* Get the path to the config file. Can be used to show the user
* where it is, or better, open it for them.
*/
path: string;
/*
Delete an item
*/
export declare function del(key: string): void;
/**
* Get all items as an object or replace the current config with an object.
*/
all: any;
/*
Get all items as an object or replace the current config with an object:
/**
* Get the item count
*/
size: number;
conf.all = {
hello: 'world'
};
*/
export declare var all: Object;
/*
Get the item count
*/
export declare var size: number;
/*
Get the path to the config file. Can be used to show the user where the config file is located or even better open it for them.
*/
export declare var path: string;
/**
* Get an item
* @param key The string key to get
* @return The contents of the config from key $key
*/
get(key: string): any;
/**
* Set an item
* @param key The string key
* @param val The value to set
*/
set(key: string, val: any): void;
/**
* Set all key/value pairs declared in $values
* @param values The values object.
*/
set(values: any): void;
/**
* Determines if a key is present in the config
* @param key The string key to test for
* @return True if the key is present
*/
has(key: string): boolean;
/**
* Delete an item.
* @param key The key to delete
*/
delete(key: string): void;
/**
* Clear the config.
* Equivalent to <code>Configstore.all = {};</code>
*/
clear(): void;
}
declare namespace Configstore {
export interface ConfigstoreOptions {
globalConfigPath?: boolean;
}
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+4
View File
@@ -92,6 +92,10 @@ cons.nunjucks(path);
cons.nunjucks(path, options);
cons.nunjucks(path, options, fn);
cons.pug(path);
cons.pug(path, options);
cons.pug(path, options, fn);
cons.qejs(path);
cons.qejs(path, options);
cons.qejs(path, options, fn);
+1
View File
@@ -48,6 +48,7 @@ interface Consolidate {
mote: RendererInterface;
mustache: RendererInterface;
nunjucks: RendererInterface;
pug: RendererInterface;
qejs: RendererInterface;
ractive: RendererInterface;
react: RendererInterface;
+23 -5
View File
@@ -1,23 +1,25 @@
import cucumber = require("cucumber");
import * as cucumber from "cucumber";
import * as assert from "power-assert";
function StepSample() {
type Callback = cucumber.CallbackStepDefinition;
type Table = cucumber.TableDefinition;
type HookScenario = cucumber.HookScenario;
type Hooks = cucumber.Hooks;
var step = <cucumber.StepDefinitions>this;
var hook = <cucumber.Hooks>this;
hook.Before(function(scenario, callback){
hook.Before(function(scenario: HookScenario, callback: Callback){
scenario.isFailed() && callback.pending();
})
});
hook.Around(function(scenario, runScenario) {
hook.Around(function(scenario: HookScenario, runScenario: (error:string, callback?:Function)=>void) {
scenario.isFailed() && runScenario(null, function(){
console.log('finish tasks');
});
});
hook.registerHandler('AfterFeatures', function (event, callback) {
hook.registerHandler('AfterFeatures', function (event:any, callback:Function) {
callback();
});
@@ -76,5 +78,21 @@ function StepSample() {
];
assert.deepEqual(table.hashes(), expected)
});
cucumber.defineSupportCode(function(step: cucumber.StepDefinitions){
step.Given( /^a variable set to (\d+)$/, (x:string) => {
console.log("the number is: " + x);
} );
});
cucumber.defineSupportCode(function(step: Hooks){
step.After((scenario: HookScenario, callback?: Callback) => {
console.log("After");
callback();
} )
});
let fns : cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns()
cucumber.clearSupportCodeFns();
}
+8
View File
@@ -71,4 +71,12 @@ declare namespace cucumber {
setDefaultTimeout(time:number): void;
registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void;
}
export interface SupportCodeConsumer {
(stepDefinitions:StepDefinitions | Hooks):void;
}
export function defineSupportCode(consumer:SupportCodeConsumer): void;
export function getSupportCodeFns(): SupportCodeConsumer[];
export function clearSupportCodeFns(): void;
}
+17 -56
View File
@@ -503,63 +503,24 @@ interface Selection<GElement extends BaseType, Datum, PElement extends BaseType,
*
* The generic refers to the type of the child element to be appended.
*
* @param type A string representing the tag name for the element type to be inserted. The specified name may have a namespace prefix,
* such as svg:text to specify a text attribute in the SVG namespace. If no namespace is specified, the namespace will be inherited
* from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used
* (for example, svg implies svg:svg)
* @param before A CSS selector string for the element before which the insertion should occur.
* @param type One of:
* * A string representing the tag name for the element type to be inserted. The specified name may have a namespace prefix,
* such as svg:text to specify a text attribute in the SVG namespace. If no namespace is specified, the namespace will be inherited
* from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used
* (for example, svg implies svg:svg)
* * A creator function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element. This function should return
* an element to be inserted. (The function typically creates a new element, but it may instead return an existing element.)
* @param before One of:
* * A CSS selector string for the element before which the insertion should occur.
* * A child selector function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element. This function should return the child element
* before which the element should be inserted.
*/
insert<ChildElement extends BaseType>(type: string, before: string): Selection<ChildElement, Datum, PElement, PDatum>;
/**
* Inserts a new element of the type provided by the element creator function before the element matching the specified "before"
* selector string for each selected element.
*
* This method returns a new selection containing the appended elements.
* Each new element inherits the data of the current elements, if any.
*
* The generic refers to the type of the child element to be appended.
*
* @param type A creator function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element. This function should return
* an element to be inserted. (The function typically creates a new element, but it may instead return an existing element.)
* @param before A CSS selector string for the element before which the insertion should occur.
*/
insert<ChildElement extends BaseType>(type: ValueFn<GElement, Datum, ChildElement>, before: string): Selection<ChildElement, Datum, PElement, PDatum>;
/**
* Inserts a new element of the specified type (tag name) before the element returned by the "before" child selector function
* for each selected element.
*
* This method returns a new selection containing the appended elements.
* Each new element inherits the data of the current elements, if any.
*
* The generic refers to the type of the child element to be appended.
*
* @param type A string representing the tag name for the element type to be inserted. The specified name may have a namespace prefix,
* such as svg:text to specify a text attribute in the SVG namespace. If no namespace is specified, the namespace will be inherited
* from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used
* (for example, svg implies svg:svg)
* @param before A child selector function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element. This function should return the child element
* before which the element should be inserted.
*/
insert<ChildElement extends BaseType>(type: string, before: ValueFn<GElement, Datum, BaseType>): Selection<ChildElement, Datum, PElement, PDatum>;
/**
* Inserts a new element of the type provided by the element creator function before the element returned by the "before" child selector function
* for each selected element.
*
* This method returns a new selection containing the appended elements.
* Each new element inherits the data of the current elements, if any.
*
* The generic refers to the type of the child element to be appended.
*
* @param type A creator function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element. This function should return
* an element to be inserted. (The function typically creates a new element, but it may instead return an existing element.)
* @param before A child selector function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element. This function should return the child element
* before which the element should be inserted.
*/
insert<ChildElement extends BaseType>(type: ValueFn<GElement, Datum, ChildElement>, before: ValueFn<GElement, Datum, BaseType>): Selection<ChildElement, Datum, PElement, PDatum>;
insert<ChildElement extends BaseType>(
type: string | ValueFn<GElement, Datum, ChildElement>,
before: string | ValueFn<GElement, Datum, BaseType>
): Selection<ChildElement, Datum, PElement, PDatum>;
/**
* Removes the selected elements from the document.
+5
View File
@@ -0,0 +1,5 @@
{
"dependencies": {
"immutable": "^3.8.1"
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Parser, Expression } from 'expr-eval';
const expr = Parser.parse('2^2');
Parser.evaluate('2^2');
Parser.evaluate('2^x', { x: 2 });
Parser.evaluate('x.toUpperCase()', { x: 'hello world' });
expr.evaluate({ x: 3 });
expr.simplify();
expr.simplify({ x: 2 });
expr.variables().forEach(str => str.toUpperCase());
expr.symbols().forEach(str => str.toUpperCase());
expr.toJSFunction('y, x');
expr.toJSFunction('y, z', { y: 2 })({ z: 3 });
+37
View File
@@ -0,0 +1,37 @@
// Type definitions for expr-eval 1.0
// Project: https://github.com/silentmatt/expr-eval#readme
// Definitions by: Connor Peet <https://github.com/connor4312>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace exprEval {
type Value = number
| string
| ((...args: Value[]) => Value)
| { [propertyName: string]: Value };
interface Values {
[propertyName: string]: Value;
}
export class Parser {
constructor(options?: { allowMemberAccess?: boolean });
parse(expression: string): Expression;
evaluate(expression: string, values?: Value): number;
// todo(connor4312): tslint is disabled on the following two lines, as
// thinks that the above instance methods are overloads for the static methods.
static parse(expression: string): Expression; // tslint:disable-line
static evaluate(expression: string, values?: Value): number; // tslint:disable-line
}
export interface Expression {
simplify(values?: Values): Expression;
evaluate(values?: Values): number;
substitute(values: Values): Expression;
symbols(): string[];
variables(): string[];
toJSFunction(params: string, values?: Values): (...args: Value[]) => number;
}
}
export = exprEval;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"expr-eval-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+20
View File
@@ -0,0 +1,20 @@
import * as extract from 'extract-zip';
let str = 'str';
let num = 0;
let options: extract.Options = {
dir: str,
};
options = {
dir: str,
defaultFileMode: num,
};
extract(str, options, (err) => {
if (err) {
console.error(err);
return;
}
console.log('done');
});
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for extract-zip 1.6
// Project: https://github.com/maxogden/extract-zip
// Definitions by: Mizunashi Mana <https://github.com/mizunashi-mana>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace extract {
export interface Options {
dir?: string;
defaultDirMode?: number;
defaultFileMode?: number;
onEntry?: (entry: any, zipfile: any) => void;
}
}
declare function extract(
zipPath: string,
opts: extract.Options,
cb: (err?: Error) => void,
): void;
export = extract;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"extract-zip-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+69
View File
@@ -39,3 +39,72 @@ FB.logout(function(response: fb.AuthResponse) {
console.log(response.status);
console.log(response.authResponse.accessToken);
});
/**
* Dialog samples from Facebook documentation:
*/
FB.ui({
display: 'popup',
method: 'live_broadcast',
phase: 'create',
}, response => {
if (!response.id) {
alert('dialog canceled');
return;
}
alert('stream url:' + response.secure_stream_url);
FB.ui({
display: 'popup',
method: 'live_broadcast',
phase: 'publish',
broadcast_data: response,
}, response => {
alert("video status: \n" + response.status);
});
});
FB.ui({
method: 'pay',
action: 'purchaseitem',
product: 'YOUR_PRODUCT_URL'
}, data => {
console.log(data.payment_id);
});
FB.ui({
method: 'pagetab',
redirect_uri: 'YOUR_URL'
}, response => {});
FB.ui({
method: 'send',
link: 'http://www.nytimes.com/interactive/2015/04/15/travel/europe-favorite-streets.html',
}, response => {});
FB.ui({
method: 'apprequests',
message: 'Take this bomb to blast your way to victory!',
to: 'USER_ID, USER_ID, INVITE_TOKEN',
action_type:'send',
object_id: 'YOUR_OBJECT_ID', // e.g. '191181717736427'
}, response => {
console.log(response);
});
FB.ui({
method: 'apprequests',
message: 'Friend Smash Request!',
filters: [
{ name:'GROUP_1_NAME', user_ids:['USER_ID','USER_ID','USER_ID'] },
{ name:'GROUP_2_NAME', user_ids: ['USER_ID','USER_ID','USER_ID'] },
]
}, response => {
console.log(response);
});
FB.ui({
method: 'share',
mobile_iframe: true,
href: 'https://developers.facebook.com/docs/',
}, response => {});
+119 -5
View File
@@ -1,4 +1,4 @@
// Type definitions for the Facebook Javascript SDK
// Type definitions for the Facebook Javascript SDK 2.8
// Project: https://developers.facebook.com/docs/javascript
// Definitions by: Amrit Kahlon <https://github.com/amritk/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -12,7 +12,7 @@ declare namespace facebook {
AppEvents: any;
Canvas: any;
Event: any;
/**
* The method FB.getAuthResponse() is a synchronous accessor for the current authResponse.
* The synchronous nature of this method is what sets it apart from the other login methods.
@@ -50,8 +50,33 @@ declare namespace facebook {
* @param callback function to handle the response
*/
logout(callback: (response: AuthResponse) => void): void;
ui: any;
/**
* @see https://developers.facebook.com/docs/sharing/reference/share-dialog
*/
ui(params: ShareDialogParams, callback: (response: ShareDialogResponse) => void): void;
/**
* @see https://developers.facebook.com/docs/games/services/gamerequests
*/
ui(params: GameRequestDialogParams, callback: (response: GameRequestDialogResponse) => void): void;
/**
* @see https://developers.facebook.com/docs/payments/reference/paydialog
*/
ui(params: PayDialogParams, callback: (response: PayDialogResponse) => void): void;
/**
* @see https://developers.facebook.com/docs/videos/live-video/exploring-live
*/
ui(params: LiveDialogParams, callback: (response: LiveDialogResponse) => void): void;
/**
* @see https://developers.facebook.com/docs/sharing/reference/send-dialog
* @see https://developers.facebook.com/docs/pages/page-tab-dialog
*/
ui(params: SendDialogParams | AddPageTabDialogParams, callback: (response: null) => void): void;
XFBML: any;
}
@@ -73,6 +98,68 @@ declare namespace facebook {
profile_selector_ids?: string;
}
////////////////////////
//
// DIALOGS
//
////////////////////////
interface DialogParams {
app_id?: string;
redirect_uri?: string;
display?: 'page' | 'iframe' | 'async' | 'popup';
}
interface ShareDialogParams extends DialogParams {
method: 'share';
href: string;
hashtag?: string;
quote?: string;
mobile_iframe?: boolean;
}
interface AddPageTabDialogParams extends DialogParams {
method: 'pagetab';
redirect_uri: string;
}
interface GameRequestDialogParams extends DialogParams {
method: 'apprequests';
message: string;
action_type?: 'send' | 'askfor' | 'turn';
data?: number;
exclude_ids?: string[];
filters?: 'app_users' | 'app_non_users' | Array<{ name: string, user_ids: string[] }>;
max_recipients?: number;
object_id?: string;
suggestions?: string[];
title?: number;
to?: string | number;
}
interface SendDialogParams extends DialogParams {
method: 'send';
to?: string;
link: string;
}
interface PayDialogParams extends DialogParams {
method: 'pay';
action: 'purchaseitem';
product: string;
quantity?: number;
quantity_min?: number;
quantity_max?: number;
request_id?: string;
test_currency?: string;
}
interface LiveDialogParams extends DialogParams {
method: 'live_broadcast';
display: 'popup' | 'iframe';
phase: 'create' | 'publish';
broadcast_data?: LiveDialogResponse;
}
////////////////////////
//
@@ -87,6 +174,33 @@ declare namespace facebook {
expiresIn: number;
signedRequest: string;
userID: string;
}
};
}
interface ShareDialogResponse {
post_id?: string;
error_message?: string;
}
interface GameRequestDialogResponse {
request: string;
to: string[];
}
interface PayDialogResponse {
payment_id: string;
amount: string;
currency: string;
quantity: string;
request_id: string;
status: string;
signed_request: string;
}
interface LiveDialogResponse {
id: string;
stream_url: string;
secure_stream_url: string;
status: string;
}
}
+2 -2
View File
@@ -62,7 +62,7 @@ $(window).load(function() {
var player = document.getElementById('player_1');
$(player).on('ready', ready);
function addEvent(element, eventName, callback) {
function addEvent(element:any, eventName:any, callback:any) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false)
} else {
@@ -70,7 +70,7 @@ $(window).load(function() {
}
}
function ready(player_id) {
function ready(player_id: any) {
var froogaloop = $(player_id);
froogaloop.on('play', function(data) {
$('.flexslider').flexslider("pause");
+6 -6
View File
@@ -18,11 +18,11 @@ interface SliderObject { //Object: The slider element itself
directionNav: Object; //Object: The slider directionNav
controlsContainer: Object; //Object: The controlsContainer element of the slider
manualControls: Object; //Object: The manualControls element of the slider
flexAnimate(target, pause?); //Function: Move slider - (target, pause) parameters
pause(); //Function: Pause slider slideshow interval
resume(); //Function: Resume slider slideshow interval
canAdvance(target); //Function: returns boolean if slider can advance - (target) parameter
getTarget(dir); //Function: get target given a direction - "next" or "prev" parameter
flexAnimate(target:any, pause?: any) :any; //Function: Move slider - (target, pause) parameters
pause(): any; //Function: Pause slider slideshow interval
resume(): any; //Function: Resume slider slideshow interval
canAdvance(target:any): boolean; //Function: returns boolean if slider can advance - (target) parameter
getTarget(dir: any): any; //Function: get target given a direction - "next" or "prev" parameter
}
interface FlexSliderOptions {
@@ -86,5 +86,5 @@ interface FlexSliderOptions {
interface JQuery {
flexslider(options?: FlexSliderOptions);
flexslider(options?: FlexSliderOptions): any;
}
+1 -1
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
+7 -1
View File
@@ -6,7 +6,13 @@ var dir: string;
var path: string;
var data: any;
var writeOptions: fs.WriteOptions;
var writeJsonOptions: fs.WriteJsonOptions;
var writeJsonOptions: fs.WriteJsonOptions = {
spaces: 2,
replacer(key, value) {
src = key;
return value;
}
};
var readJsonOptions: fs.ReadJsonOptions;
async function test() {
+1 -1
View File
@@ -15,7 +15,7 @@ export interface WriteOptions {
type JsonReplacerArray = Array<number | string>;
type JsonReplacerFunction = (key: any, value: any) => any;
type JsonReplacerFunction = (key: string, value: any) => any;
type JsonReplacer = JsonReplacerArray | JsonReplacerFunction;
+16
View File
@@ -0,0 +1,16 @@
import * as gaussian from ".";
const d = gaussian(0, 1);
const a = d.mean !== d.variance;
const b = d.mean * d.standardDeviation;
d.pdf(-2);
d.cdf(-1.28155);
d.ppf(0.1);
gaussian(0, 1).mul(gaussian(0, 1));
gaussian(1, 1).mul(2);
gaussian(1, 1).add(gaussian(1, 2));
gaussian(1, 1).sub(gaussian(1, 2));
gaussian(1, 1).div(gaussian(1, 2));
gaussian(1, 1).div(2);
gaussian(1, 1).scale(2);
+65
View File
@@ -0,0 +1,65 @@
// Type definitions for gaussian 1.1
// Project: https://github.com/errcw/gaussian
// Definitions by: Scott Cooper <https://github.com/scttcper>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function gaussian(mean: number, variance: number): gaussian.Gaussian;
export = gaussian;
export as namespace gaussian;
declare namespace gaussian {
export interface Gaussian {
/**
* the mean (μ) of the distribution
*/
mean: number;
/**
* the variance (σ^2) of the distribution
*/
variance: number;
/**
* the standard deviation (σ) of the distribution
*/
standardDeviation: number;
/**
* the probability density function, which describes the
* probability of a random variable taking on the value x
*/
pdf(x: number): number;
/**
* the cumulative distribution function, which describes the
* probability of a random variable falling in the interval (−∞, x]
*/
cdf(x: number): number;
/**
* the percent point function, the inverse of cdf
*/
ppf(x: number): number;
/**
* returns the product distribution of this and the given
* distribution; equivalent to scale(d) when d is a constant
*/
mul(x: number | Gaussian): number;
/**
* returns the quotient distribution of this and the given
* distribution; equivalent to scale(1/d) when d is a constant
*/
div(x: number | Gaussian): number;
/**
* returns the result of adding this and the given
* distribution's means and variances
*/
add(x: Gaussian): number;
/**
* returns the result of subtracting this and the given
* distribution's means and variances
*/
sub(x: Gaussian): number;
/**
* returns the result of scaling this distribution by the
* given constant
*/
scale(x: number): number;
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"gaussian-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+73 -79
View File
@@ -5,84 +5,78 @@
import * as react from "react";
export = Halogen;
declare namespace Halogen {
type VerticalAlign = "baseline" | "length" | "sub" | "super" | "top" | "text-top" | "middle" | "bottom" | "text-bottom" | "initial" | "inherit";
interface HalogenCommonProps {
loading?: boolean;
color?: string;
id?: string;
className?: string;
verticalAlign?: VerticalAlign;
}
interface SizeLoaderProps extends HalogenCommonProps {
size?: string;
}
interface MarginLoaderProps<T> extends HalogenCommonProps {
margin?: T;
size?: T;
}
interface RadiusLoaderProps extends MarginLoaderProps<string> {
height?: string;
width?: string;
radius?: string;
}
/**
* React components
*/
type PulseLoader = react.Component<MarginLoaderProps<string>, {}>;
export const PulseLoader: react.ComponentClass<MarginLoaderProps<string>>;
type RotateLoader = react.Component<MarginLoaderProps<string>, {}>;
export const RotateLoader: react.ComponentClass<MarginLoaderProps<string>>;
type BeatLoader = react.Component<MarginLoaderProps<string>, {}>;
export const BeatLoader: react.ComponentClass<MarginLoaderProps<string>>;
type RiseLoader = react.Component<MarginLoaderProps<string>, {}>;
export const RiseLoader: react.ComponentClass<MarginLoaderProps<string>>;
type SyncLoader = react.Component<MarginLoaderProps<string>, {}>;
export const SyncLoader: react.ComponentClass<MarginLoaderProps<string>>;
type GridLoader = react.Component<MarginLoaderProps<string>, {}>;
export const GridLoader: react.ComponentClass<MarginLoaderProps<string>>;
type ClipLoader = react.Component<SizeLoaderProps, {}>;
export const ClipLoader: react.ComponentClass<SizeLoaderProps>;
type SquareLoader = react.Component<SizeLoaderProps, {}>;
export const SquareLoader: react.ComponentClass<SizeLoaderProps>;
type DotLoader = react.Component<SizeLoaderProps, {}>;
export const DotLoader: react.ComponentClass<SizeLoaderProps>;
type PacmanLoader = react.Component<MarginLoaderProps<number>, {}>;
export const PacmanLoader: react.ComponentClass<MarginLoaderProps<number>>;
type MoonLoader = react.Component<SizeLoaderProps, {}>;
export const MoonLoader: react.ComponentClass<SizeLoaderProps>;
type RingLoader = react.Component<SizeLoaderProps, {}>;
export const RingLoader: react.ComponentClass<SizeLoaderProps>;
type BounceLoader = react.Component<SizeLoaderProps, {}>;
export const BounceLoader: react.ComponentClass<SizeLoaderProps>;
type SkewLoader = react.Component<SizeLoaderProps, {}>;
export const SkewLoader: react.ComponentClass<SizeLoaderProps>;
type FadeLoader = react.Component<RadiusLoaderProps, {}>;
export const FadeLoader: react.ComponentClass<RadiusLoaderProps>;
type ScaleLoader = react.Component<RadiusLoaderProps, {}>;
export const ScaleLoader: react.ComponentClass<RadiusLoaderProps>;
type VerticalAlign = "baseline" | "length" | "sub" | "super" | "top" | "text-top" | "middle" | "bottom" | "text-bottom" | "initial" | "inherit";
interface HalogenCommonProps {
loading?: boolean;
color?: string;
id?: string;
className?: string;
verticalAlign?: VerticalAlign;
}
interface SizeLoaderProps extends HalogenCommonProps {
size?: string;
}
interface MarginLoaderProps<T> extends HalogenCommonProps {
margin?: T;
size?: T;
}
interface RadiusLoaderProps extends MarginLoaderProps<string> {
height?: string;
width?: string;
radius?: string;
}
/**
* React components
*/
type PulseLoader = react.Component<MarginLoaderProps<string>, {}>;
export const PulseLoader: react.ComponentClass<MarginLoaderProps<string>>;
type RotateLoader = react.Component<MarginLoaderProps<string>, {}>;
export const RotateLoader: react.ComponentClass<MarginLoaderProps<string>>;
type BeatLoader = react.Component<MarginLoaderProps<string>, {}>;
export const BeatLoader: react.ComponentClass<MarginLoaderProps<string>>;
type RiseLoader = react.Component<MarginLoaderProps<string>, {}>;
export const RiseLoader: react.ComponentClass<MarginLoaderProps<string>>;
type SyncLoader = react.Component<MarginLoaderProps<string>, {}>;
export const SyncLoader: react.ComponentClass<MarginLoaderProps<string>>;
type GridLoader = react.Component<MarginLoaderProps<string>, {}>;
export const GridLoader: react.ComponentClass<MarginLoaderProps<string>>;
type ClipLoader = react.Component<SizeLoaderProps, {}>;
export const ClipLoader: react.ComponentClass<SizeLoaderProps>;
type SquareLoader = react.Component<SizeLoaderProps, {}>;
export const SquareLoader: react.ComponentClass<SizeLoaderProps>;
type DotLoader = react.Component<SizeLoaderProps, {}>;
export const DotLoader: react.ComponentClass<SizeLoaderProps>;
type PacmanLoader = react.Component<MarginLoaderProps<number>, {}>;
export const PacmanLoader: react.ComponentClass<MarginLoaderProps<number>>;
type MoonLoader = react.Component<SizeLoaderProps, {}>;
export const MoonLoader: react.ComponentClass<SizeLoaderProps>;
type RingLoader = react.Component<SizeLoaderProps, {}>;
export const RingLoader: react.ComponentClass<SizeLoaderProps>;
type BounceLoader = react.Component<SizeLoaderProps, {}>;
export const BounceLoader: react.ComponentClass<SizeLoaderProps>;
type SkewLoader = react.Component<SizeLoaderProps, {}>;
export const SkewLoader: react.ComponentClass<SizeLoaderProps>;
type FadeLoader = react.Component<RadiusLoaderProps, {}>;
export const FadeLoader: react.ComponentClass<RadiusLoaderProps>;
type ScaleLoader = react.Component<RadiusLoaderProps, {}>;
export const ScaleLoader: react.ComponentClass<RadiusLoaderProps>;
+9 -9
View File
@@ -1,4 +1,4 @@
import { createBrowserHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history'
import { createHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history'
import { getUserConfirmation } from 'history/lib/DOMUtils'
@@ -10,7 +10,7 @@ let doSomethingAsync: () => Promise<Function>;
let input = { value: "" };
{
let history = createBrowserHistory()
let history = createHistory()
// Listen for changes to the current location. The
// listener is called once immediately.
@@ -46,7 +46,7 @@ let input = { value: "" };
}
{
let history = createBrowserHistory()
let history = createHistory()
// Pushing a path string.
history.push('/the/path')
@@ -63,7 +63,7 @@ let input = { value: "" };
}
{
let history = createBrowserHistory()
let history = createHistory()
history.listenBefore(function(location) {
if (input.value !== '')
return 'Are you sure you want to leave this page?'
@@ -75,7 +75,7 @@ let input = { value: "" };
}
{
let history = createBrowserHistory({
let history = createHistory({
getUserConfirmation(message, callback) {
callback(window.confirm(message)) // The default behavior
}
@@ -83,7 +83,7 @@ let input = { value: "" };
}
{
let history = useBeforeUnload(createBrowserHistory)()
let history = useBeforeUnload(createHistory)()
history.listenBeforeUnload(function() {
return 'Are you sure you want to leave this page?'
@@ -91,7 +91,7 @@ let input = { value: "" };
}
{
let history = useQueries(createBrowserHistory)()
let history = useQueries(createHistory)()
history.listen(function(location) {
console.log(location.query)
@@ -99,7 +99,7 @@ let input = { value: "" };
}
{
let history = useQueries(createBrowserHistory)({
let history = useQueries(createHistory)({
parseQueryString: function(queryString) {
// TODO: return a parsed version of queryString
return {};
@@ -116,7 +116,7 @@ let input = { value: "" };
{
// Run our app under the /base URL.
let history = useBasename(createBrowserHistory)({
let history = useBasename(createHistory)({
basename: '/base'
})
+1 -1
View File
@@ -127,7 +127,7 @@ export interface Module {
};
}
export { default as createBrowserHistory } from "./lib/createBrowserHistory";
export { default as createHistory } from "./lib/createBrowserHistory";
export { default as createHashHistory } from "./lib/createHashHistory";
export { default as createMemoryHistory } from "./lib/createMemoryHistory";
export { default as createLocation } from "./lib/createLocation";
@@ -0,0 +1,65 @@
import HtmlWebpackPlugin = require('html-webpack-plugin');
import template = require('html-webpack-template');
const configs: Array<template.Config> = [
{
// Required
inject: false,
template,
// template: 'node_modules/html-webpack-template/index.ejs',
// Optional
appMountId: 'app',
appMountIds: [
'root0',
'root1',
],
baseHref: 'http://example.com/awesome',
devServer: 'http://localhost:3001',
googleAnalytics: {
trackingId: 'UA-XXXX-XX',
pageViewOnLoad: true,
},
links: [
'https://fonts.googleapis.com/css?family=Roboto',
{
href: '/apple-touch-icon.png',
rel: 'apple-touch-icon',
sizes: '180x180',
},
{
href: '/favicon-32x32.png',
rel: 'icon',
sizes: '32x32',
type: 'image/png',
},
],
meta: [
{
description: 'A better default template for html-webpack-plugin.',
},
],
mobile: true,
inlineManifestWebpackName: 'webpackManifest',
scripts: [
'http://example.com/somescript.js',
{
src: '/myModule.js',
type: 'module',
},
],
window: {
env: {
apiHost: 'http://myapi.com/api/v1',
},
},
// And any other config options from html-webpack-plugin:
// https://github.com/ampedandwired/html-webpack-plugin#configuration
title: 'My App',
},
];
const plugins: Array<HtmlWebpackPlugin> = configs.map(config =>
new HtmlWebpackPlugin(config)
);
+96
View File
@@ -0,0 +1,96 @@
// Type definitions for html-webpack-template 6.0
// Project: https://github.com/jaketrent/html-webpack-template
// Definitions by: Benjamin Lim <https://github.com/bumbleblym>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Config as HtmlWebpackPluginConfig } from 'html-webpack-plugin';
export = HtmlWebpackTemplate;
declare const HtmlWebpackTemplate: string;
declare namespace HtmlWebpackTemplate {
export interface GoogleAnalyticsConfig {
trackingId: string;
// Log a pageview event after the analytics code loads.
pageViewOnLoad?: boolean;
}
export interface Attributes {
[name: string]: any;
}
type Resource = string | Attributes;
/**
* string: value is assigned to the href attribute and the rel attribute is
* set to "stylesheet"
*
* object: properties and values are used as the attribute names and values,
* respectively:
*/
export type Link = Resource;
/**
* string: value is assigned to the src attribute and the type attribute is
* set to "text/javascript";
*
* object: properties and values are used as the attribute names and values,
* respectively.
*/
export type Script = Resource;
export interface Config extends HtmlWebpackPluginConfig {
/**
* Set to false. Controls asset addition to the template. This template
* takes care of that.
*/
inject: false;
// Specify this module's index.ejs file.
template: string;
// The <div> element id on which you plan to mount a JavaScript app.
appMountId?: string;
// An array of application element ids.
appMountIds?: string[];
/**
* Adjust the URL for relative URLs in the document (MDN).
* https://developer.mozilla.org/en/docs/Web/HTML/Element/base
*/
baseHref?: string;
/**
* Insert the webpack-dev-server hot reload script at this
* host:port/path; e.g., http://localhost:3000.
*/
devServer?: string;
// Track usage of your site via Google Analytics.
googleAnalytics?: GoogleAnalyticsConfig;
// Array of <link> elements.
links?: Link[];
// Array of objects containing key value pairs to be included as meta tags.
meta?: Attributes[];
// Sets appropriate meta tag for page scaling.
mobile?: boolean;
/**
* For use with inline-manifest-webpack-plugin.
*
* https://github.com/szrenwei/inline-manifest-webpack-plugin
*/
inlineManifestWebpackName?: string;
// Array of external script imports to include on page.
scripts?: Script[];
// Object that defines data you need to bootstrap a JavaScript app.
window?: {};
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"html-webpack-template-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+142
View File
@@ -0,0 +1,142 @@
// Type definitions for jalaali-js 1.1
// Project: https://github.com/jalaali/jalaali-js
// Definitions by: Ali Taheri Moghaddar <https://github.com/alitaheri>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Jalaali date parts
*/
export interface JalaaliDateObject {
/** Jalaali year */
jy: number;
/** Jalaali month */
jm: number;
/** Jalaali day */
jd: number;
}
/**
* Gregorian date parts
*/
export interface GregorianDateObject {
/** Gregorian year */
gy: number;
/** Gregorian month */
gm: number;
/** Gregorian day */
gd: number;
}
/**
* Object returned by jalCal function
*/
export interface JalCalResult {
/** Number of years since the last leap year (0 to 4) */
leap: number;
/** Gregorian year of the beginning of Jalaali year */
gy: number;
/** The March day of Farvardin the 1st (1st day of jy) */
march: number;
}
/**
* Converts a Gregorian date to Jalaali.
* @param gy Gregorian Calendar year (years BC numbered 0, -1, -2, ...)
* @param gm Gregorian Calendar month (1 to 12)
* @param gd Gregorian Calendar day of the month (1 to 28/29/30/31)
*/
export function toJalaali(gy: number, gm: number, gd: number): JalaaliDateObject;
/**
* Converts a Gregorian Date object to Jalaali.
* @param date Gregorian Date object
*/
export function toJalaali(date: Date): JalaaliDateObject;
/**
* Converts a Jalaali date to Gregorian.
* @param jy Jalaali Calendar year (years BC numbered 0, -1, -2, ...)
* @param jm Jalaali Calendar month (1 to 12)
* @param jd Jalaali Calendar day of the month (1 to 28/29/30/31)
*/
export function toGregorian(jy: number, jm: number, jd: number): GregorianDateObject;
/**
* Checks whether a Jalaali date is valid or not.
* @param jy Jalaali Calendar year (years BC numbered 0, -1, -2, ...)
* @param jm Jalaali Calendar month (1 to 12)
* @param jd Jalaali Calendar day of the month (1 to 28/29/30/31)
*/
export function isValidJalaaliDate(jy: number, jm: number, jd: number): boolean;
/**
* Check if this is a leap year.
* @param jy Jalaali Calendar year (years BC numbered 0, -1, -2, ...)
*/
export function isLeapJalaaliYear(jy: number): boolean;
/**
* Number of days in a given month in a Jalaali year.
* @param jy Jalaali Calendar year (years BC numbered 0, -1, -2, ...)
* @param jm Jalaali Calendar month (1 to 12)
*/
export function jalaaliMonthLength(jy: number, jm: number): number;
/**
* This function determines if the Jalaali (Persian) year is
* leap (366-day long) or is the common year (365 days), and
* finds the day in March (Gregorian calendar) of the first
* day of the Jalaali year (jy).
* @param jy Jalaali calendar year (-61 to 3177)
* @return
* leap: number of years since the last leap year (0 to 4)
* gy: Gregorian year of the beginning of Jalaali year
* march: the March day of Farvardin the 1st (1st day of jy)
* @see: http://www.astro.uni.torun.pl/~kb/Papers/EMP/PersianC-EMP.htm
* @see: http://www.fourmilab.ch/documents/calendar/
*/
export function jalCal(jy: number): JalCalResult;
/**
* Converts a date of the Jalaali calendar to the Julian Day number.
* @param jy Jalaali year (1 to 3100)
* @param jm Jalaali month (1 to 12)
* @param jd Jalaali day (1 to 29/31)
* @return Julian Day number
*/
export function j2d(jy: number, jm: number, jd: number): number;
/**
* Converts the Julian Day number to a date in the Jalaali calendar.
* @param jdn Julian Day number
* @return
* jy: Jalaali Calendar year (1 to 3100)
* jm: Jalaali Calendar month (1 to 12)
* jd: Jalaali Calendar day (1 to 29/31)
*/
export function d2j(jdn: number): JalaaliDateObject;
/**
* Calculates the Julian Day number from Gregorian or Julian
* calendar dates. This integer number corresponds to the noon of
* the date (i.e. 12 hours of Universal Time).
* The procedure was tested to be good since 1 March, -100100 (of both
* calendars) up to a few million years into the future.
* @param gy Gregorian Calendar year (years BC numbered 0, -1, -2, ...)
* @param gm Gregorian Calendar month (1 to 12)
* @param gd Gregorian Calendar day of the month (1 to 28/29/30/31)
* @return Julian Day number
*/
export function g2d(gy: number, gm: number, gd: number): number;
/**
* Calculates Gregorian and Julian calendar dates from the Julian Day number
* (jdn) for the period since jdn=-34839655 (i.e. the year -100100 of both
* calendars) to some millions years ahead of the present.
* @param jdn Julian Day number
* @return
* gy: Gregorian Calendar year (years BC numbered 0, -1, -2, ...)
* gm: Gregorian Calendar month (1 to 12)
* gd: Gregorian Calendar day of the month M (1 to 28/29/30/31)
*/
export function d2g(jdn: number): GregorianDateObject;
+42
View File
@@ -0,0 +1,42 @@
import {
toJalaali,
toGregorian,
isValidJalaaliDate,
isLeapJalaaliYear,
jalaaliMonthLength,
jalCal,
j2d,
d2j,
g2d,
d2g,
} from 'jalaali-js';
toJalaali(2016, 4, 11); // { jy: 1395, jm: 1, jd: 23 }
toJalaali(new Date(2016, 3, 11)); // { jy: 1395, jm: 1, jd: 23 }
toGregorian(1395, 1, 23); // { gy: 2016, gm: 4, gd: 11 }
isValidJalaaliDate(1394, 12, 30); // false
isValidJalaaliDate(1395, 12, 30); // true
isLeapJalaaliYear(1394); // false
isLeapJalaaliYear(1395); // true
jalaaliMonthLength(1394, 12); // 29
jalaaliMonthLength(1395, 12); // 30
jalCal(1390); // { leap: 3, gy: 2011, march: 21 }
jalCal(1391); // { leap: 0, gy: 2012, march: 20 }
jalCal(1392); // { leap: 1, gy: 2013, march: 21 }
jalCal(1393); // { leap: 2, gy: 2014, march: 21 }
jalCal(1394); // { leap: 3, gy: 2015, march: 21 }
jalCal(1395); // { leap: 0, gy: 2016, march: 20 }
j2d(1395, 1, 23); // 2457490
d2j(2457490); // { jy: 1395, jm: 1, jd: 23 }
g2d(2016, 4, 11); // 2457490
d2g(2457490); // { gy: 2016, gm: 4, gd: 11 }
@@ -15,6 +15,6 @@
},
"files": [
"index.d.ts",
"argon2-tests.ts"
"jalaali-js-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+13 -1
View File
@@ -213,6 +213,18 @@ interface JQueryFileInputOptions {
progress?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void;
send?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void;
// Validation
/**
* The maximum allowed file size in bytes.
* Type: integer
* Default: undefined
* Example: 10000000 // 10 MB
* Note: This option has only an effect for browsers supporting the File API.
* @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize
*/
maxFileSize?: number;
// Other callbacks:
submit?: Function;
done?: (e: JQueryEventObject, data: JQueryFileUploadDone) => void;
@@ -289,4 +301,4 @@ interface JQueryFileUploadProgressObject extends JQueryFileInputOptions, JQueryF
}
interface JQueryFileUploadDone extends JQueryFileInputOptions, JQueryFileUploadXhr {
}
}
+741 -220
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -575,6 +575,7 @@ function test_appendTo() {
function test_attr() {
var title = $("em").attr("title");
$("em").attr("title", null); // Delete an attribute.
$("div").text(title);
$('#greatphoto').attr('alt', 'Beijing Brush Seller');
$('#greatphoto')
+14 -3
View File
@@ -526,8 +526,8 @@ declare namespace mathjs {
* to manipulate the data in the matrix, like getting the size and getting or setting values in the matrix. Supported
* storage formats are 'dense' and 'sparse'.
*/
matrix(format?: string): Matrix;
matrix(data: MathArray|Matrix, format?: string, dataType?:string): Matrix;
matrix(format?: 'sparse'|'dense'): Matrix;
matrix(data: MathArray|Matrix, format?: 'sparse'|'dense', dataType?: string): Matrix;
/**
* Create a number or convert a string, boolean, or unit to a number. When value is a matrix, all elements will be converted to number.
@@ -1292,10 +1292,21 @@ declare namespace mathjs {
}
export interface Matrix {
size(): number[];
type: string;
storage(): string;
datatype(): string;
density(): number;
subset(index: Index, replacement?: any, defaultValue?: any): Matrix;
get(index: number[]): any;
set(index: number[], value: any, defaultValue?: number|string): Matrix;
resize(size: MathArray|Matrix, defaultValue?: number|string): Matrix;
clone(): Matrix;
size(): number[];
map(callback: (a: any, b: number, c: Matrix) => any, skipZeros?: boolean): Matrix;
forEach(callback: (a: any, b: number, c: Matrix) => void, skipZeros?: boolean): void;
toJSON(): any;
diagonal(k?: number|BigNumber): any[];
swapRows(i: number, j: number): Matrix;
}
export interface BigNumber {
+1 -1
View File
@@ -22,7 +22,7 @@ declare namespace meow {
flags: { [name: string]: any };
pkg: any;
help: string;
showHelp(code: number): void;
showHelp(code?: number): void;
}
}
+73 -77
View File
@@ -5,89 +5,85 @@
import { StateNavigator } from 'navigation';
import { Component, HTMLProps } from 'react';
export = NavigationReact;
declare namespace NavigationReact {
/**
* Defines the Link Props contract
*/
interface LinkProps extends HTMLProps<HTMLAnchorElement> {
/**
* Defines the Link Props contract
* Indicates whether Links listen for navigate events
*/
interface LinkProps extends HTMLProps<HTMLAnchorElement> {
/**
* Indicates whether Links listen for navigate events
*/
lazy?: boolean;
/**
* Determines the effect on browser history
*/
historyAction?: 'add' | 'replace' | 'none';
/**
* Handles Link click events
*/
navigating?: (e: MouseEvent, domId: string, link: string) => boolean;
/**
* The State Navigator
*/
stateNavigator?: StateNavigator;
}
lazy?: boolean;
/**
* Defines the Refresh Link Props contract
* Determines the effect on browser history
*/
interface RefreshLinkProps extends LinkProps {
/**
* The NavigationData to pass
*/
navigationData?: any;
/**
* Indicates whether to include all the current NavigationData
*/
includeCurrentData?: boolean;
/**
* The data to add from the current NavigationData
*/
currentDataKeys?: string;
/**
* The Css Class to display when the Link is active
*/
activeCssClass?: string;
/**
* Indicates whether the Link is disabled when active
*/
disableActive?: boolean;
}
historyAction?: 'add' | 'replace' | 'none';
/**
* Hyperlink Component the navigates to the current State
* Handles Link click events
*/
class RefreshLink extends Component<RefreshLinkProps, any> { }
navigating?: (e: MouseEvent, domId: string, link: string) => boolean;
/**
* Defines the Navigation Link Props contract
* The State Navigator
*/
interface NavigationLinkProps extends RefreshLinkProps {
/**
* The key of the State to navigate to
*/
stateKey: string;
}
/**
* Hyperlink Component the navigates to a State
*/
class NavigationLink extends Component<NavigationLinkProps, any> { }
/**
* Defines the Navigation Back Link Props contract
*/
interface NavigationBackLinkProps extends RefreshLinkProps {
/**
* Starting at 1, The number of Crumb steps to go back
*/
distance: number;
}
/**
* Hyperlink Component the navigates back along the crumb trail
*/
class NavigationBackLink extends Component<NavigationBackLinkProps, any> { }
stateNavigator?: StateNavigator;
}
/**
* Defines the Refresh Link Props contract
*/
interface RefreshLinkProps extends LinkProps {
/**
* The NavigationData to pass
*/
navigationData?: any;
/**
* Indicates whether to include all the current NavigationData
*/
includeCurrentData?: boolean;
/**
* The data to add from the current NavigationData
*/
currentDataKeys?: string;
/**
* The Css Class to display when the Link is active
*/
activeCssClass?: string;
/**
* Indicates whether the Link is disabled when active
*/
disableActive?: boolean;
}
/**
* Hyperlink Component the navigates to the current State
*/
export class RefreshLink extends Component<RefreshLinkProps, any> { }
/**
* Defines the Navigation Link Props contract
*/
interface NavigationLinkProps extends RefreshLinkProps {
/**
* The key of the State to navigate to
*/
stateKey: string;
}
/**
* Hyperlink Component the navigates to a State
*/
export class NavigationLink extends Component<NavigationLinkProps, any> { }
/**
* Defines the Navigation Back Link Props contract
*/
interface NavigationBackLinkProps extends RefreshLinkProps {
/**
* Starting at 1, The number of Crumb steps to go back
*/
distance: number;
}
/**
* Hyperlink Component the navigates back along the crumb trail
*/
export class NavigationBackLink extends Component<NavigationBackLinkProps, any> { }
+19 -1
View File
@@ -3961,7 +3961,25 @@ declare module "v8" {
space_available_size: number;
physical_space_size: number;
}
export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number };
const enum DoesZapCodeSpaceFlag {
Disabled = 0,
Enabled = 1
}
interface HeapInfo {
total_heap_size: number;
total_heap_size_executable: number;
total_physical_size: number;
total_available_size: number;
used_heap_size: number;
heap_size_limit: number;
malloced_memory: number;
peak_malloced_memory: number;
does_zap_garbage: DoesZapCodeSpaceFlag;
}
export function getHeapStatistics(): HeapInfo;
export function getHeapSpaceStatistics(): HeapSpaceInfo[];
export function setFlagsFromString(flags: string): void;
}
+6
View File
@@ -268,6 +268,12 @@
"typingsPackageName": "inversify-restify-utils",
"sourceRepoURL": "https://github.com/inversify/inversify-restify-utils",
"asOfVersion": "2.0.0"
},
{
"libraryName": "Argon2",
"typingsPackageName": "argon2",
"sourceRepoURL": "https://github.com/ranisalt/node-argon2",
"asOfVersion": "0.15.0"
}
]
}
+14 -12
View File
@@ -6669,20 +6669,13 @@ declare module ol {
* the {@link ol.layer.Layer layer} of the feature and will be null for
* unmanaged layers. To stop detection, callback functions can return a
* truthy value.
* @param {S=} opt_this Value to use as `this` when executing `callback`.
* @param {(function(this: U, ol.layer.Layer): boolean)=} opt_layerFilter Layer
* filter function. The filter function will receive one argument, the
* {@link ol.layer.Layer layer-candidate} and it should return a boolean
* value. Only layers which are visible and for which this function returns
* `true` will be tested for features. By default, all visible layers will
* be tested.
* @param {U=} opt_this2 Value to use as `this` when executing `layerFilter`.
* @param {olx.AtPixelOptions=} opt_options Optional options.
* @return {T|undefined} Callback result, i.e. the return value of last
* callback execution, or the first truthy callback return value.
* @template S,T,U
* @template S,T
* @api stable
*/
forEachFeatureAtPixel<S, T, U>(pixel: ol.Pixel, callback: ((feature: (ol.Feature | ol.render.Feature), layer: ol.layer.Layer) => T), opt_this?: S, opt_layerFilter?: ((layer: ol.layer.Layer) => boolean), opt_this2?: U): (T);
forEachFeatureAtPixel<S, T>(pixel: ol.Pixel, callback: ((feature: (ol.Feature | ol.render.Feature), layer: ol.layer.Layer) => T), opt_options?: olx.AtPixelOptions): (T);
/**
* Detect layers that have a color value at a pixel on the viewport, and
@@ -11778,7 +11771,6 @@ declare module olx {
easing?: ((t: number) => number);
}
}
/**
@@ -13779,7 +13771,17 @@ declare module olx {
zoom?: number;
zoomFactor?: number;
}
/**
* Object literal with options for the {@link ol.Map#forEachFeatureAtPixel} and
* {@link ol.Map#hasFeatureAtPixel} methods.
* @typedef {{layerFilter: ((function(ol.layer.Layer): boolean)|undefined),
* hitTolerance: (number|undefined)}}
*/
interface AtPixelOptions {
layerFilter?: ((layer: ol.layer.Layer) => boolean)
hitTolerance?: number
}
/**
* @typedef {{animate: boolean,
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for react-intl 2.1.5
// Type definitions for react-intl 2.2.0
// Project: http://formatjs.io/react/
// Definitions by: Bruno Grieder <https://github.com/bgrieder>, Christian Droulers <https://github.com/cdroulers>, Fedor Nezhivoi <https://github.com/gyzerok>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+173
View File
@@ -0,0 +1,173 @@
// Type definitions for react-joyride 1.6
// Project: https://github.com/gilbarbara/react-joyride
// Definitions by: Daniel Rosenwasser <https://github.com/DanielRosenwasser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import React = require("react");
export default class Joyride extends React.Component<Props, State> {
constructor(props: Props);
addTooltip(data: Step): void;
start(autorun?: boolean): void;
next(): void;
back(): void;
stop(): void;
reset(restart: boolean): void;
getProgress(): Progress;
parseSteps(steps: Step | Step[]): Step[];
static defaultProps: Props;
}
export interface Progress {
index: number;
percentageComplete: number;
step: Step;
}
interface Locale {
back?: string;
close?: string;
last?: string;
next?: string;
skip?: string;
}
interface Props {
/**
* The tour's steps. Defaults to []
*/
steps?: any[];
/**
* Run/stop the tour.
*/
run?: boolean;
/**
* Toggle keyboard navigation (esc, space bar, return). Defaults to true
*/
keyboardNavigation?: boolean;
/**
* The strings used in the tooltip. Defaults to `{ back: 'Back', close: 'Close', last: 'Last', next: 'Next', skip: 'Skip' }`
*/
locale?: Locale;
/**
* Delay the reposition of the current step while the window is being resized. Defaults to false
*/
resizeDebounce?: boolean;
/**
* The amount of delay for the resizeDebounce callback. Defaults to 200
*/
resizeDebounceDelay?: number;
/**
* The gap around the target inside the hole. Defaults to 5
*/
holePadding?: number;
/**
* The scrollTop offset used in scrollToSteps. Defaults to 20
*/
scrollOffset?: number;
/**
* Scroll the page to the next step if needed. Defaults to true
*/
scrollToSteps?: boolean;
/**
* Scroll the page for the first step. Defaults to false
*/
scrollToFirstStep?: boolean;
/**
* Display a back button. Defaults to true
*/
showBackButton?: boolean;
/**
* Display an overlay with holes above your steps (for tours only). Defaults to true
*/
showOverlay?: boolean;
/**
* Display a link to skip the tour. Defaults to false
*/
showSkipButton?: boolean;
/**
* Display the tour progress in the next button e.g. 2/5 in continuous tours. Defaults to false
*/
showStepsProgress?: boolean;
/**
* The tooltip offset from the target. Defaults to 30
*/
tooltipOffset?: number;
/**
* The type of your presentation. It can be continuous (played sequencially with the Next button) or single. Defaults to single
*/
type?: "continuous" | "single";
/**
* Don't close the tooltip on clicking the overlay. Defaults to false
*/
disableOverlay?: boolean;
/**
* Console.log Joyride's inner actions. Defaults to false
*/
debug?: boolean;
/**
* It will be called when the tour's state changes.
*/
callback?: (options: any) => void;
}
export interface Step {
title?: string;
text: string;
selector: string;
position?: "top" | "top-left" | "top-right" | "bottom" | "bottom-left" | "bottom-right" | "right" | "left";
type?: "click" | "hover";
style?: StepStyles;
[prop: string]: any;
}
export interface StepStyles {
backgroundColor?: string;
borderRadius?: string;
color?: string;
mainColor?: string;
textAlign?: string;
width?: string;
beacon?: BeaconStyles;
[style: string]: any;
}
export interface BeaconStyles {
offsetX?: number;
offsetY?: number;
inner?: string;
outer?: string;
}
export interface State {
action: string;
index: number;
play: boolean;
redraw: boolean;
shouldPlay: boolean;
showTooltip: boolean;
xPos: number;
yPos: number;
skipped: boolean;
}
+55
View File
@@ -0,0 +1,55 @@
import React = require("react");
import Joyride from "react-joyride";
class NewComponent extends React.Component<undefined, undefined> {
j: Joyride;
render() {
return <Joyride ref="j" run holePadding={4} resizeDebounceDelay={100} />;
}
doStuff() {
this.j.start(/*autorun*/ true);
this.j.next();
this.j.reset(true);
this.j.reset(false);
const { title, position } = this.j.getProgress().step;
this.j.parseSteps({
title: "Title",
text: "Hurray",
selector: ".selectable",
position: "top-right",
type: "click",
style: {
backgroundColor: "#000",
borderRadius: "0",
color: "#000",
mainColor: "#fff",
textAlign: "left",
width: "2px",
beacon: {
offsetX: 10,
offsetY: 10,
inner: "#000",
outer: "#000"
},
button: {
display: "block"
},
skip: {
color: "#000"
},
hole: {
backgroundColor: "#000",
}
},
name: "my-name",
parent: "MyParent"
})
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"jsx": "preserve",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"react-joyride-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+177 -181
View File
@@ -5,186 +5,182 @@
/// <reference types="react-native" />
declare namespace RNFS {
interface ReadDirItem {
// The name of the item
name: string;
// The absolute path to the item
path: string;
// Size in bytes
size: string;
// Is the file just a file?
isFile(): boolean;
// Is the file a directory?
isDirectory(): boolean;
}
interface StatResult {
// The name of the item
name: string;
// The absolute path to the item
path: string;
// Size in bytes
size: string;
// UNIX file mode
mode: number;
// Is the file just a file?
isFile(): boolean;
// Is the file a directory?
isDirectory(): boolean;
}
interface Headers {
[index: string]: string;
}
type Fields = Headers;
interface MkdirOptions {
// iOS only
NSURLIsExcludedFromBackupKey?: boolean;
}
interface DownloadResult {
// The download job ID, required if one wishes to cancel the download. See `stopDownload`.
jobId: number;
// The HTTP status code
statusCode: number;
// The number of bytes written to the file
bytesWritten: number;
}
type DownloadCallbackBegin = (res: DownloadBeginCallbackResult) => void;
type DownloadCallbackProgress = (res: DownloadProgressCallbackResult) => void;
interface DownloadFileOptions {
// URL to download file from
fromUrl: string;
// Local filesystem path to save the file to
toFile: string;
// An object of headers to be passed to the server
headers?: Headers;
background?: boolean;
progressDivider?: number;
begin?: DownloadCallbackBegin;
progress?: DownloadCallbackProgress;
}
interface DownloadProgressCallbackResult {
// The download job ID, required if one wishes to cancel the download. See `stopDownload`.
jobId: number;
// The total size in bytes of the download resource
contentLength: number;
// The number of bytes written to the file so far
bytesWritten: number;
}
interface DownloadBeginCallbackResult {
// The download job ID, required if one wishes to cancel the download. See `stopDownload`.
jobId: number;
// The HTTP status code
statusCode: number;
// The total size in bytes of the download resource
contentLength: number;
// The HTTP response headers from the server
headers: Headers;
}
type UploadCallbackBegin = (res: UploadBeginCallbackResult) => void;
type UploadCallbackProgress = (res: UploadProgressCallbackResult) => void;
interface UploadFileOptions {
// URL to upload file to
toUrl: string;
// An array of objects with the file information to be uploaded.
files: UploadFileItem[];
// An object of headers to be passed to the server
headers?: Headers;
// An object of fields to be passed to the server
fields?: Fields;
// Default is 'POST', supports 'POST' and 'PUT'
method?: string;
begin?: UploadCallbackBegin;
progress?: UploadCallbackProgress;
}
interface UploadResult {
// The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
jobId: number;
// The HTTP status code
statusCode: number;
// The HTTP response headers from the server
headers: Headers;
// The HTTP response body
body: string;
}
interface UploadFileItem {
// Name of the file, if not defined then filename is used
name: string;
// Name of file
filename: string;
// Path to file
filepath: string;
// The mimetype of the file to be uploaded, if not defined it will get mimetype from `filepath` extension
filetype: string;
}
interface UploadBeginCallbackResult {
// The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
jobId: number;
}
interface UploadProgressCallbackResult {
// The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
jobId: number;
// The total number of bytes that will be sent to the server
totalBytesExpectedToSend: number;
// The number of bytes sent to the server
totalBytesSent: number;
}
interface FSInfoResult {
// The total amount of storage space on the device (in bytes).
totalSpace: number;
// The amount of available storage space on the device (in bytes).
freeSpace: number;
}
interface JobReturnValue<Result> {
jobId: number;
promise: Promise<Result>;
}
// The absolute path to the main bundle directory
export const MainBundlePath: string;
// The absolute path to the caches directory
export const CachesDirectoryPath: string;
// The absolute path to the document directory
export const DocumentDirectoryPath: string;
// The absolute path to the temporary directory (iOS only)
export const TemporaryDirectoryPath: string;
// The absolute path to the external files, shared directory (android only)
export const ExternalDirectoryPath: string;
// The absolute path to the external storage, shared directory (android only)
export const ExternalStorageDirectoryPath: string;
export function readDir(path: string): Promise<ReadDirItem[]>;
export function readdir(path: string): Promise<string[]>;
export function stat(filepath: string): Promise<StatResult>;
export function readFile(filepath: string, encoding?: string): Promise<string>;
export function unlink(filepath: string): Promise<void>;
export function writeFile(filepath: string, contents: string, encoding?: string): Promise<void>;
export function appendFile(filepath: string, contents: string, encoding?: string): Promise<void>;
export function moveFile(filepath: string, destPath: string): Promise<void>;
export function copyFile(filepath: string, destPath: string): Promise<void>;
export function exists(filepath: string): Promise<boolean>;
export function hash(filepath: string, algorithm: string): Promise<string>;
export function mkdir(filepath: string, options?: MkdirOptions): Promise<void>;
export function downloadFile(options: DownloadFileOptions): JobReturnValue<DownloadResult>;
export function stopDownload(jobId: number): Promise<void>;
export function uploadFiles(options: UploadFileOptions): JobReturnValue<UploadResult>;
export function stopUpload(jobId: number): Promise<void>;
export function getFSInfo(): Promise<FSInfoResult>;
interface ReadDirItem {
// The name of the item
name: string;
// The absolute path to the item
path: string;
// Size in bytes
size: string;
// Is the file just a file?
isFile(): boolean;
// Is the file a directory?
isDirectory(): boolean;
}
export = RNFS;
interface StatResult {
// The name of the item
name: string;
// The absolute path to the item
path: string;
// Size in bytes
size: string;
// UNIX file mode
mode: number;
// Is the file just a file?
isFile(): boolean;
// Is the file a directory?
isDirectory(): boolean;
}
interface Headers {
[index: string]: string;
}
type Fields = Headers;
interface MkdirOptions {
// iOS only
NSURLIsExcludedFromBackupKey?: boolean;
}
interface DownloadResult {
// The download job ID, required if one wishes to cancel the download. See `stopDownload`.
jobId: number;
// The HTTP status code
statusCode: number;
// The number of bytes written to the file
bytesWritten: number;
}
type DownloadCallbackBegin = (res: DownloadBeginCallbackResult) => void;
type DownloadCallbackProgress = (res: DownloadProgressCallbackResult) => void;
interface DownloadFileOptions {
// URL to download file from
fromUrl: string;
// Local filesystem path to save the file to
toFile: string;
// An object of headers to be passed to the server
headers?: Headers;
background?: boolean;
progressDivider?: number;
begin?: DownloadCallbackBegin;
progress?: DownloadCallbackProgress;
}
interface DownloadProgressCallbackResult {
// The download job ID, required if one wishes to cancel the download. See `stopDownload`.
jobId: number;
// The total size in bytes of the download resource
contentLength: number;
// The number of bytes written to the file so far
bytesWritten: number;
}
interface DownloadBeginCallbackResult {
// The download job ID, required if one wishes to cancel the download. See `stopDownload`.
jobId: number;
// The HTTP status code
statusCode: number;
// The total size in bytes of the download resource
contentLength: number;
// The HTTP response headers from the server
headers: Headers;
}
type UploadCallbackBegin = (res: UploadBeginCallbackResult) => void;
type UploadCallbackProgress = (res: UploadProgressCallbackResult) => void;
interface UploadFileOptions {
// URL to upload file to
toUrl: string;
// An array of objects with the file information to be uploaded.
files: UploadFileItem[];
// An object of headers to be passed to the server
headers?: Headers;
// An object of fields to be passed to the server
fields?: Fields;
// Default is 'POST', supports 'POST' and 'PUT'
method?: string;
begin?: UploadCallbackBegin;
progress?: UploadCallbackProgress;
}
interface UploadResult {
// The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
jobId: number;
// The HTTP status code
statusCode: number;
// The HTTP response headers from the server
headers: Headers;
// The HTTP response body
body: string;
}
interface UploadFileItem {
// Name of the file, if not defined then filename is used
name: string;
// Name of file
filename: string;
// Path to file
filepath: string;
// The mimetype of the file to be uploaded, if not defined it will get mimetype from `filepath` extension
filetype: string;
}
interface UploadBeginCallbackResult {
// The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
jobId: number;
}
interface UploadProgressCallbackResult {
// The upload job ID, required if one wishes to cancel the upload. See `stopUpload`.
jobId: number;
// The total number of bytes that will be sent to the server
totalBytesExpectedToSend: number;
// The number of bytes sent to the server
totalBytesSent: number;
}
interface FSInfoResult {
// The total amount of storage space on the device (in bytes).
totalSpace: number;
// The amount of available storage space on the device (in bytes).
freeSpace: number;
}
interface JobReturnValue<Result> {
jobId: number;
promise: Promise<Result>;
}
// The absolute path to the main bundle directory
export const MainBundlePath: string;
// The absolute path to the caches directory
export const CachesDirectoryPath: string;
// The absolute path to the document directory
export const DocumentDirectoryPath: string;
// The absolute path to the temporary directory (iOS only)
export const TemporaryDirectoryPath: string;
// The absolute path to the external files, shared directory (android only)
export const ExternalDirectoryPath: string;
// The absolute path to the external storage, shared directory (android only)
export const ExternalStorageDirectoryPath: string;
export function readDir(path: string): Promise<ReadDirItem[]>;
export function readdir(path: string): Promise<string[]>;
export function stat(filepath: string): Promise<StatResult>;
export function readFile(filepath: string, encoding?: string): Promise<string>;
export function unlink(filepath: string): Promise<void>;
export function writeFile(filepath: string, contents: string, encoding?: string): Promise<void>;
export function appendFile(filepath: string, contents: string, encoding?: string): Promise<void>;
export function moveFile(filepath: string, destPath: string): Promise<void>;
export function copyFile(filepath: string, destPath: string): Promise<void>;
export function exists(filepath: string): Promise<boolean>;
export function hash(filepath: string, algorithm: string): Promise<string>;
export function mkdir(filepath: string, options?: MkdirOptions): Promise<void>;
export function downloadFile(options: DownloadFileOptions): JobReturnValue<DownloadResult>;
export function stopDownload(jobId: number): Promise<void>;
export function uploadFiles(options: UploadFileOptions): JobReturnValue<UploadResult>;
export function stopUpload(jobId: number): Promise<void>;
export function getFSInfo(): Promise<FSInfoResult>;
+1 -1
View File
@@ -1223,7 +1223,7 @@ declare module "react" {
/**
* Callback that is called when the text input selection is changed.
*/
onSelectionChange?: () => void
onSelectionChange?: (event: { nativeEvent: { selection: { start: number, end: number }, target: number } }) => void
/**
* Callback that is called when the text input's submit button is pressed.
+1
View File
@@ -444,4 +444,5 @@ declare class ReactSelectClass extends React.Component<ReactSelectClass.ReactSel
declare module ReactSelectClass {
class Creatable extends React.Component<ReactCreatableSelectProps, {}> { }
class Async extends React.Component<ReactAsyncSelectProps, {}> { }
class AsyncCreatable extends React.Component<ReactAsyncSelectProps & ReactCreatableSelectProps, {}> { }
}
+46
View File
@@ -223,3 +223,49 @@ class SelectCreatableTest extends React.Component<React.Props<{}>, {}> {
}
}
class SelectAsyncCreatableTest extends React.Component<React.Props<{}>, {}> {
render() {
const getOptions = (input: string, callback: Function) => {
setTimeout(function() {
callback(null, options);
}, 500);
};
const options: Option[] = [{ label: "Foo", value: "bar" }];
const onChange = (value: any) => console.log(value);
const asyncCreatableSelectProps: ReactCreatableSelectProps & ReactAsyncSelectProps = {
name: "test-select-async-creatable",
className: "test-select-async-creatable",
key: "1",
matchPos: "any",
matchProp: "any",
multi: true,
onValueClick: onChange,
valueKey: "github",
labelKey: "name",
onChange: onChange,
simpleValue: undefined,
value: options,
loadOptions: getOptions,
cache: {},
ignoreAccents: false,
ignoreCase: true,
isLoading: false,
minimumInput: 5,
searchPromptText: "search...",
searchingText: "searching...",
isOptionUnique: () => { return true; },
isValidNewOption: () => { return true; },
newOptionCreator: () => { return { label: "NewFoo", value: "newBar" }; },
promptTextCreator: () => { return ""; },
shouldKeyDownEventCreateNewOption: () => { return true; }
};
return <div>
<Select.AsyncCreatable {...asyncCreatableSelectProps} />
</div>
}
}
+14 -17
View File
@@ -4,21 +4,18 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { ReactElement } from "react";
declare namespace ReactTestRenderer {
export interface Renderer {
toJSON(): ReactTestRendererJSON;
}
export interface ReactTestRendererJSON {
type: string;
props: { [propName: string]: string };
children: null | Array<string | ReactTestRendererJSON>;
$$typeof?: any;
}
export interface TestRendererOptions {
createNodeMock: (element: ReactElement<any>) => any;
}
// https://github.com/facebook/react/blob/master/src/renderers/testing/ReactTestMount.js#L155
export function create(nextElement: ReactElement<any>, options?: TestRendererOptions): Renderer;
}
export = ReactTestRenderer;
interface Renderer {
toJSON(): ReactTestRendererJSON;
}
interface ReactTestRendererJSON {
type: string;
props: { [propName: string]: string };
children: null | Array<string | ReactTestRendererJSON>;
$$typeof?: any;
}
interface TestRendererOptions {
createNodeMock: (element: ReactElement<any>) => any;
}
// https://github.com/facebook/react/blob/master/src/renderers/testing/ReactTestMount.js#L155
export function create(nextElement: ReactElement<any>, options?: TestRendererOptions): Renderer;
+87
View File
@@ -0,0 +1,87 @@
// Type definitions for readline-sync 1.4
// Project: https://github.com/anseki/readline-sync
// Definitions by: Tristan Jones <https://github.com/jonestristand>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type OptionType = string | number | RegExp | ((input: string) => boolean);
interface BasicOptions {
prompt?: any;
hideEchoBack?: boolean;
mask?: string;
limit?: OptionType | OptionType[];
limitMessage?: string;
defaultInput?: string;
trueValue?: OptionType | OptionType[];
falseValue?: OptionType | OptionType[];
caseSensitive?: boolean;
keepWhitespace?: boolean;
encoding?: string;
bufferSize?: number;
print?: (display: string, encoding: string) => void;
history?: boolean;
cd?: boolean;
charlist?: string;
min?: any;
max?: any;
confirmMessage?: any;
unmatchMessage?: any;
exists?: any;
isFile?: boolean;
isDirectory?: boolean;
validate?: (path: string) => boolean | string;
create?: boolean;
guide?: boolean;
}
// Basic Functions
export function question(query?: any, options?: BasicOptions): string;
export function prompt(options?: BasicOptions): string;
export function keyIn(query?: any, options?: BasicOptions): string;
export function setDefaultOptions(options?: BasicOptions): BasicOptions;
// Utility Functions
export function questionEMail(query?: any, options?: BasicOptions): string;
export function questionNewPassword(query?: any, options?: BasicOptions): string;
export function questionInt(query?: any, options?: BasicOptions): number;
export function questionFloat(query?: any, options?: BasicOptions): number;
export function questionPath(query?: any, options?: BasicOptions): string;
export function promptCL(commandHandler?: { [id: string]: (...args: string[]) => void } | ((command: string, ...args: string[]) => void), options?: BasicOptions): string[];
export function promptLoop(inputHandler: (value: string) => boolean, options?: BasicOptions): void;
export function promptCLLoop(commandHandler?: { [id: string]: (...args: string[]) => boolean | void } | ((command: string, ...args: string[]) => boolean | void), options?: BasicOptions): void;
export function promptSimShell(options?: BasicOptions): string;
export function keyInYN(query?: any, options?: BasicOptions): boolean | string;
export function keyInYNStrict(query?: any, options?: BasicOptions): boolean;
export function keyInPause(query?: any, options?: BasicOptions): void;
export function keyInSelect(items: string[], query?: any, options?: BasicOptions): number;
export function getRawInput(): string;
// Deprecated
/**
* @deprecated Use the bufferSize option instead: readlineSync.setDefaultOptions({bufferSize: value});
*/
export function setBufferSize(value: number): void;
/**
* @deprecated Use the encoding option instead: readlineSync.setDefaultOptions({encoding: value});
*/
export function setEncoding(value: string): void;
/**
* @deprecated Use the mask option instead: readlineSync.setDefaultOptions({mask: value});
*/
export function setMask(value: string): void;
/**
* @deprecated Use the print option instead: readlineSync.setDefaultOptions({print: value});
*/
export function setPrint(value: (display: string, encoding: string) => void): void;
/**
* @deprecated Use the prompt option instead: readlineSync.setDefaultOptions({prompt: value});
*/
export function setPrompt(value: any): void;
+109
View File
@@ -0,0 +1,109 @@
import readlineSync = require('readline-sync');
let result:string = readlineSync.question('Which program starts do you want? ', {
defaultInput: 'firefox'
});
let result2:string = readlineSync.prompt({prompt: '$$'});
let result3:string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' });
let result4:{} = readlineSync.setDefaultOptions({
prompt: '$$',
hideEchoBack: true,
mask: '*',
limit: [ /^a|b$/, /[a-zA-Z]+/],
limitMessage: 'Limit reached',
defaultInput: 'English',
trueValue: 2,
falseValue: (value:string) => { return true; },
caseSensitive: true,
keepWhitespace: true,
encoding: 'utf-8',
bufferSize: 12,
print: (display:string, encoding:string) => { console.log(display)},
history: false,
cd: true,
charlist: 'abc',
min: 0,
max: 10,
confirmMessage: 'Yes',
unmatchMessage: new Date(),
exists: false,
isFile: true,
isDirectory: false,
validate: (path:string) => { return (path === '/usr/local/bin'); },
create: true,
guide: false,
});
let result5:string = readlineSync.questionEMail('Enter email');
let result6:string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$<a-z>#$@%'});
let result7:number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' });
let result8:number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' });
let result9:string = readlineSync.questionPath('Save to: ', {
isDirectory: true,
exists: null,
create: true
});
readlineSync.promptCL((command:string, arg1:string, arg2:string) => {
if (command === 'add') {
console.log(arg1 + ' is added.');
} else if (command === 'copy') {
console.log(arg1 + ' is copied to ' + arg2 + '.');
}
});
readlineSync.promptCL({
add: (element:string) => { // It's called by also "ADD", "Add", "aDd", etc..
console.log(element + ' is added.');
},
copy: (from:string, to:string) => {
console.log(from + ' is copied to ' + to + '.');
}
});
readlineSync.promptLoop((input:string) => {
console.log('-- You said "' + input + '"');
return input === 'bye';
});
readlineSync.promptCLLoop({
add: (element:string) => {
console.log(element + ' is added.');
},
copy: (from:string, to:string) => {
console.log(from + ' is copied to ' + to + '.');
},
bye: () => { return true; }
});
let result10:string = readlineSync.promptSimShell();
let result11:(boolean | string) = readlineSync.keyInYN('Do you want to install this?');
let result12:boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true });
readlineSync.keyInPause({ guide:true });
let frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive'];
let result13:number = readlineSync.keyInSelect(frameworks, 'Which framework?');
let result14:string = readlineSync.getRawInput();
readlineSync.setPrint((display:string, encoding:string) => { console.log(display) });
readlineSync.setPrompt(new Date());
readlineSync.setEncoding('utf-16');
readlineSync.setMask('%');
readlineSync.setBufferSize(128);
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"readline-sync-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+106 -109
View File
@@ -3,115 +3,112 @@
// Definitions by: Jack Hsu <https://github.com/jaysoo>, Alex Gorbatchev <https://github.com/alexgorbatchev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = ReduxActions;
export as namespace ReduxActions;
declare namespace ReduxActions {
// FSA-compliant action.
// See: https://github.com/acdlite/flux-standard-action
interface BaseAction {
type: string;
}
export interface Action<Payload> extends BaseAction {
payload?: Payload;
error?: boolean;
}
export interface ActionMeta<Payload, Meta> extends Action<Payload> {
meta: Meta;
}
interface ReducerMap<State, Payload> {
[actionType: string]: Reducer<State, Payload> | ReducerNextThrow<State, Payload>;
}
interface ReducerMapMeta<State, Payload, Meta> {
[actionType: string]: Reducer<State, Payload> | ReducerNextThrow<State, Payload>;
}
interface ReducerNextThrow<State, Payload> {
next?(state: State, action: Action<Payload>): State;
throw?(state: State, action: Action<Payload>): State;
}
interface ReducerNextThrowMeta<State, Payload, Meta> {
next?(state: State, action: ActionMeta<Payload, Meta>): State;
throw?(state: State, action: ActionMeta<Payload, Meta>): State;
}
type ActionFunctions<Payload> = ActionFunction0<Action<Payload>> | ActionFunction1<any, Action<Payload>> | ActionFunction2<any, any, Action<Payload>> | ActionFunction3<any, any, any, Action<Payload>> | ActionFunction4<any, any, any, any, Action<Payload>> | ActionFunctionAny<Action<Payload>>;
type Reducer<State, Payload> = (state: State, action: Action<Payload>) => State;
type ReducerMeta<State, Payload, Meta> = (state: State, action: ActionMeta<Payload, Meta>) => State;
/** argument inferring borrowed from lodash definitions */
type ActionFunction0<R> = () => R;
type ActionFunction1<T1, R> = (t1: T1) => R;
type ActionFunction2<T1, T2, R> = (t1: T1, t2: T2) => R;
type ActionFunction3<T1, T2, T3, R> = (t1: T1, t2: T2, t3: T3) => R;
type ActionFunction4<T1, T2, T3, T4, R> = (t1: T1, t2: T2, t3: T3, t4: T4) => R;
type ActionFunctionAny<R> = (...args: any[]) => R;
export function createAction<Payload>(
actionType: string,
payloadCreator: ActionFunction0<Payload>
): ActionFunction0<Action<Payload>>;
export function createAction<Payload, Arg1>(
actionType: string,
payloadCreator: ActionFunction1<Arg1, Payload>
): ActionFunction1<Arg1, Action<Payload>>;
export function createAction<Payload, Arg1, Arg2>(
actionType: string,
payloadCreator: ActionFunction2<Arg1, Arg2, Payload>
): ActionFunction2<Arg1, Arg2, Action<Payload>>;
export function createAction<Payload, Arg1, Arg2, Arg3>(
actionType: string,
payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>
): ActionFunction3<Arg1, Arg2, Arg3, Action<Payload>>;
export function createAction<Payload, Arg1, Arg2, Arg3, Arg4>(
actionType: string,
payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>
): ActionFunction4<Arg1, Arg2, Arg3, Arg4, Action<Payload>>;
export function createAction<Payload>(
actionType: string
): ActionFunctionAny<Action<Payload>>;
export function createAction<Payload, Meta>(
actionType: string,
payloadCreator: (...args: any[]) => Payload,
metaCreator: (...args: any[]) => Meta
): (...args: any[]) => ActionMeta<Payload, Meta>;
export function handleAction<State, Payload>(
actionType: string | ActionFunctions<Payload>,
reducer: Reducer<State, Payload> | ReducerNextThrow<State, Payload>,
initialState: State
): Reducer<State, Payload>;
export function handleAction<State, Payload, Meta>(
actionType: { toString(): string },
reducer: ReducerMeta<State, Payload, Meta> | ReducerNextThrowMeta<State, Payload, Meta>,
initialState: State
): Reducer<State, Payload>;
export function handleActions<StateAndPayload>(
reducerMap: ReducerMap<StateAndPayload, StateAndPayload>,
initialState: StateAndPayload
): Reducer<StateAndPayload, StateAndPayload>;
export function handleActions<State, Payload>(
reducerMap: ReducerMap<State, Payload>,
initialState: State
): Reducer<State, Payload>;
export function combineActions(
...actionTypes: Array<ActionFunctions<any>>
): Array<ActionFunctions<any>>;
// FSA-compliant action.
// See: https://github.com/acdlite/flux-standard-action
interface BaseAction {
type: string;
}
interface Action<Payload> extends BaseAction {
payload?: Payload;
error?: boolean;
}
interface ActionMeta<Payload, Meta> extends Action<Payload> {
meta: Meta;
}
interface ReducerMap<State, Payload> {
[actionType: string]: Reducer<State, Payload> | ReducerNextThrow<State, Payload>;
}
interface ReducerMapMeta<State, Payload, Meta> {
[actionType: string]: Reducer<State, Payload> | ReducerNextThrow<State, Payload>;
}
interface ReducerNextThrow<State, Payload> {
next?(state: State, action: Action<Payload>): State;
throw?(state: State, action: Action<Payload>): State;
}
interface ReducerNextThrowMeta<State, Payload, Meta> {
next?(state: State, action: ActionMeta<Payload, Meta>): State;
throw?(state: State, action: ActionMeta<Payload, Meta>): State;
}
type ActionFunctions<Payload> = ActionFunction0<Action<Payload>> | ActionFunction1<any, Action<Payload>> | ActionFunction2<any, any, Action<Payload>> | ActionFunction3<any, any, any, Action<Payload>> | ActionFunction4<any, any, any, any, Action<Payload>> | ActionFunctionAny<Action<Payload>>;
type Reducer<State, Payload> = (state: State, action: Action<Payload>) => State;
type ReducerMeta<State, Payload, Meta> = (state: State, action: ActionMeta<Payload, Meta>) => State;
/** argument inferring borrowed from lodash definitions */
type ActionFunction0<R> = () => R;
type ActionFunction1<T1, R> = (t1: T1) => R;
type ActionFunction2<T1, T2, R> = (t1: T1, t2: T2) => R;
type ActionFunction3<T1, T2, T3, R> = (t1: T1, t2: T2, t3: T3) => R;
type ActionFunction4<T1, T2, T3, T4, R> = (t1: T1, t2: T2, t3: T3, t4: T4) => R;
type ActionFunctionAny<R> = (...args: any[]) => R;
export function createAction<Payload>(
actionType: string,
payloadCreator: ActionFunction0<Payload>
): ActionFunction0<Action<Payload>>;
export function createAction<Payload, Arg1>(
actionType: string,
payloadCreator: ActionFunction1<Arg1, Payload>
): ActionFunction1<Arg1, Action<Payload>>;
export function createAction<Payload, Arg1, Arg2>(
actionType: string,
payloadCreator: ActionFunction2<Arg1, Arg2, Payload>
): ActionFunction2<Arg1, Arg2, Action<Payload>>;
export function createAction<Payload, Arg1, Arg2, Arg3>(
actionType: string,
payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>
): ActionFunction3<Arg1, Arg2, Arg3, Action<Payload>>;
export function createAction<Payload, Arg1, Arg2, Arg3, Arg4>(
actionType: string,
payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>
): ActionFunction4<Arg1, Arg2, Arg3, Arg4, Action<Payload>>;
export function createAction<Payload>(
actionType: string
): ActionFunctionAny<Action<Payload>>;
export function createAction<Payload, Meta>(
actionType: string,
payloadCreator: (...args: any[]) => Payload,
metaCreator: (...args: any[]) => Meta
): (...args: any[]) => ActionMeta<Payload, Meta>;
export function handleAction<State, Payload>(
actionType: string | ActionFunctions<Payload>,
reducer: Reducer<State, Payload> | ReducerNextThrow<State, Payload>,
initialState: State
): Reducer<State, Payload>;
export function handleAction<State, Payload, Meta>(
actionType: { toString(): string },
reducer: ReducerMeta<State, Payload, Meta> | ReducerNextThrowMeta<State, Payload, Meta>,
initialState: State
): Reducer<State, Payload>;
export function handleActions<StateAndPayload>(
reducerMap: ReducerMap<StateAndPayload, StateAndPayload>,
initialState: StateAndPayload
): Reducer<StateAndPayload, StateAndPayload>;
export function handleActions<State, Payload>(
reducerMap: ReducerMap<State, Payload>,
initialState: State
): Reducer<State, Payload>;
export function combineActions(
...actionTypes: Array<ActionFunctions<any>>
): Array<ActionFunctions<any>>;
+1 -1
View File
@@ -1,4 +1,4 @@
import ReduxActions = require("redux-actions");
import * as ReduxActions from "redux-actions";
let state: number;
const minimalAction: ReduxActions.BaseAction = { type: 'INCREMENT' };
+12 -15
View File
@@ -3,21 +3,18 @@
// Definitions by: Chad Burggraf <https://github.com/ChadBurggraf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = ReduxBatchedActions;
export as namespace ReduxBatchedActions;
import { Action, Reducer } from 'redux';
declare namespace ReduxBatchedActions {
/**
* Batching action creator that creates a higher-order
* action from an array of actions.
*/
export function batchActions<A extends Action>(actions: A[]): Action;
export as namespace ReduxBatchedActions;
/**
* Creates a higher-order reducer that enables batching
* actions for the given reducer.
*/
export function enableBatching<S>(reducer: Reducer<S>): Reducer<S>;
}
/**
* Batching action creator that creates a higher-order
* action from an array of actions.
*/
export function batchActions<A extends Action>(actions: A[]): Action;
/**
* Creates a higher-order reducer that enables batching
* actions for the given reducer.
*/
export function enableBatching<S>(reducer: Reducer<S>): Reducer<S>;
+264 -424
View File
@@ -1,244 +1,10 @@
// Type definitions for service_worker_api
// Type definitions for service_worker_api 0.0
// Project: https://developer.mozilla.org/fr/docs/Web/API/ServiceWorker_API
// Definitions by: Tristan Caron <https://github.com/tristancaron>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// TypeScript Version: 2.1
// <reference path="../es6-promise/es6-promise.d.ts" /> // REMOVED third "/" so this doesn't fire. Problem with duplicate Promises
// between es6 and typescript - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/5015
/**
* Provides methods relating to the body of the response/request, allowing you
* to declare what its content type is and how it should be handled.
*/
interface Body {
/**
* Contains a Boolean that indicates whether the body has been read.
* @readonly
*/
bodyUsed: boolean;
/**
* Takes a Response stream and reads it to completion.
* It returns a promise that resolves with an ArrayBuffer.
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Takes a Response stream and reads it to completion.
* It returns a promise that resolves with a Blob.
*/
blob(): Promise<Blob>;
/**
* Takes a Response stream and reads it to completion.
* It returns a promise that resolves with a FormData object.
*/
formData(): Promise<FormData>;
/**
* Takes a Response stream and reads it to completion.
* It returns a promise that resolves with a JSON object.
*/
json(): Promise<JSON>;
/**
* Takes a Response stream and reads it to completion.
* It returns a promise that resolves with a USVString (text).
*/
text(): Promise<Text>;
}
/**
* Represents response/request headers, allowing you to query them and take
* different actions depending on the results.
*/
interface Header {
new(): Header;
/**
* Appends a new value onto an existing header inside a Headers object, or
* adds the header if it does not already exist.
*
* @param name The name of the HTTP header you want to add to the Headers
* object.
* @param value The value of the HTTP header you want to add.
*/
append(name: string, value: string): void;
/**
* Deletes a header from a Headers object.
*
* @param name The name of the HTTP header you want to delete from the
* Headers object.
*/
delete(name: string): void;
/**
* Returns the first value of a given header from within a Headers object.
*
* @param name The name of the HTTP header whose value you want to retrieve
* from the Headers object. If the given name is not the name of an
* HTTP header, this method throws a TypeError.
*/
get(name: string): string;
/**
* Returns an array of all the values of a header within a Headers object
* with a given name.
*
* @param name The name of the HTTP header whose values you want to retrieve
* from the Headers object. If the given name is not the name of an
* HTTP header, this method throws a TypeError.
*/
getAll(name:string): Array<string>;
/**
* Returns a boolean stating whether a Headers object contains a
* certain header.
*
* @param name The name of the HTTP header you want to test for. If the
* given name is not the name of an HTTP header, this method throws
* a TypeError.
*/
has(name: string): boolean;
/**
* Sets a new value for an existing header inside a Headers object, or
* adds the header if it does not already exist.
*
* @param name The name of the HTTP header you want to set to a new value.
* If the given name is not the name of an HTTP header, this method throws
* a TypeError.
* @param value The new value you want to set.
*/
set(name: string, value: string): void;
}
/**
* Represents the response to a request.
*/
interface Response extends Body {
new(): Response;
/**
* Contains the type of the response (e.g., basic, cors).
* @readonly
*/
type: string;
/**
* Contains the URL of the response.
* @readonly
*/
url: string;
/**
* Contains a boolean stating whether this is the final URL of the response.
*/
useFinalURL: boolean;
/**
* Contains the status code of the response (e.g., 200 for a success).
* @readonly
*/
status: number;
/**
* Contains a boolean stating whether the response was successful
* (status in the range 200-299) or not.
* @readonly
*/
ok: boolean;
/**
* Contains the status message corresponding to the status code
* (e.g., OK for 200).
* @readonly
*/
statusText: string;
/**
* Contains the Headers object associated with the response.
* @readonly
*/
headers: Header;
/**
* Creates a clone of a Response object.
*/
clone(): Response;
/**
* Returns a new Response object associated with a network error.
*/
error(): Response;
/**
* Creates a new response with a different URL.
*/
redirect(): Response;
}
/**
* Represents a resource request.
*/
interface Request extends Body {
new(): Request;
/**
* Contains the request's method (GET, POST, etc.).
* @readonly
*/
method: string;
/**
* Contains the URL of the request.
* @readonly
*/
url: string;
/**
* Contains the associated Headers object of the request.
* @readonly
*/
headers: Header;
/**
* Contains the context of the request (e.g., audio, image, iframe, etc.).
* @readonly
*/
context: string;
/**
* Contains the referrer of the request (e.g., client).
* @readonly
*/
referrer: string;
/**
* Contains the mode of the request (e.g., cors, no-cors, same-origin).
* @readonly
*/
mode: string;
/**
* Contains the credentials of the request (e.g., omit, same-origin).
* @readonly
*/
credentials: string;
/**
* Contains the cache mode of the request (e.g., default, reload, no-cache).
* @readonly
*/
cache: string;
/**
* Creates a copy of the current Request object.
*/
clone(): Request;
}
/// <reference types="whatwg-fetch" />
/**
* An CacheOptions object allowing you to set specific control options for the
@@ -278,7 +44,7 @@ interface Cache {
* matching request in the Cache object.
*
* @param request The Request you are attempting to find in the Cache.
* @param {CacheOptions} options
* @param [options] An object that sets options for the match operation.
*/
match(request: Request | string, options?: CacheOptions): Promise<Response>;
@@ -287,9 +53,9 @@ interface Cache {
* the Cache object.
*
* @param request The Request you are attempting to find in the Cache.
* @param {CacheOptions} options
* @param [options] An object that sets options for the match operation.
*/
matchAll(request: Request | string, options?: CacheOptions): Promise<Array<Response>>;
matchAll(request: Request | string, options?: CacheOptions): Promise<Response[]>;
/**
* Returns a Promise that resolves to a new Cache entry whose key
@@ -321,7 +87,7 @@ interface Cache {
* entry is found, it returns false.
*
* @param request The Request you are looking to delete.
* @param {CacheOptions} options
* @param [options] An object that sets options for the match operation.
*/
delete(request: Request | string, options?: CacheOptions): Promise<boolean>;
@@ -329,9 +95,9 @@ interface Cache {
* Returns a Promise that resolves to an array of Cache keys.
*
* @param request The Request want to return, if a specific key is desired.
* @param {CacheOptions} options
* @param [options] An object that sets options for the match operation.
*/
keys(request?: Request, options?: CacheOptions): Promise<Array<Request>>;
keys(request?: Request, options?: CacheOptions): Promise<Request[]>;
}
/**
@@ -346,7 +112,7 @@ interface CacheStorage {
* to that match.
*
* @param request The Request you are looking for a match for in the CacheStorage.
* @param {CacheOptions} options
* @param [options] An object that sets options for the match operation.
*/
match(request: Request | string, options?: CacheOptions): Promise<Response>;
@@ -382,7 +148,7 @@ interface CacheStorage {
* CacheStorage. Use this method to iterate over a list of all the
* Cache objects.
*/
keys(): Promise<Array<string>>;
keys(): Promise<string[]>;
}
/**
@@ -398,26 +164,23 @@ interface ServiceWorkerClient {
* @param [transfer] A transferable object such as, for example, a reference
* to a port.
*/
postMessage(message: string, transfer?: Object): void;
postMessage(message: any, transfer?: any): void;
/**
* Indicates the type of browsing context of the current client.
* This value can be one of auxiliary, top-level, nested, or none.
* @readonly
*/
frameType: string;
readonly frameType: string;
/**
* Returns the id of the Client object.
* @readonly
*/
id: string;
readonly id: string;
/**
* The URL of the current service worker client.
* @readonly
*/
url: string;
readonly url: string;
}
interface WindowClient extends ServiceWorkerClient {
@@ -428,16 +191,14 @@ interface WindowClient extends ServiceWorkerClient {
/**
* A boolean that indicates whether the current client has focus.
* @readonly
*/
focused: boolean;
readonly focused: boolean;
/**
* Indicates the visibility of the current client. This value can be one of
* hidden, visible, prerender, or unloaded.
* @readonly
*/
visibilityState: string;
readonly visibilityState: string;
}
interface ServiceWorkerClientsMatchOptions {
@@ -450,6 +211,12 @@ interface ServiceWorkerClientsMatchOptions {
* the active service worker clients at the current origin.
*/
interface ServiceWorkerClients {
/**
* Gets a service worker client matching a given id and returns it in a Promise.
* @param clientId The ID of the client you want to get.
*/
get(clientId: string): Promise<ServiceWorkerClient>;
/**
* Gets a list of service worker clients and returns them in a Promise.
* Include the options parameter to return all service worker clients whose
@@ -457,9 +224,9 @@ interface ServiceWorkerClients {
* are not included, the method returns only the service worker clients
* controlled by the service worker.
*
* @param options
* @param [options] An options object allowing you to set options for the matching operation.
*/
matchAll(options: ServiceWorkerClientsMatchOptions): Promise<Array<ServiceWorkerClient>>;
matchAll(options?: ServiceWorkerClientsMatchOptions): Promise<ServiceWorkerClient[]>;
/**
* Opens a service worker Client in a new browser window.
@@ -476,62 +243,6 @@ interface ServiceWorkerClients {
claim(): Promise<void>;
}
/**
* Extends the lifetime of the install and activate events dispatched on the
* ServiceWorkerGlobalScope as part of the service worker lifecycle. This
* ensures that any functional events (like FetchEvent) are not dispatched to
* the ServiceWorker until it upgrades database schemas, deletes outdated cache
* entries, etc.
*/
interface ExtendableEvent extends Event {
/**
* Extends the lifetime of the event.
* It is intended to be called in the install EventHandler for the
* installing worker and on the active EventHandler for the active worker.
*
* @param all
*/
waitUntil(all: any): any;
}
/**
* The parameter passed into the ServiceWorkerGlobalScope.onfetch handler,
* FetchEvent represents a fetch action that is dispatched on the
* ServiceWorkerGlobalScope of a ServiceWorker. It contains information about
* the request and resulting response, and provides the FetchEvent.respondWith()
* method, which allows us to provide an arbitrary response back to the
* controlled page.
*/
interface FetchEvent extends Event {
/**
* Returns a Boolean that is true if the event was dispatched with the
* user's intention for the page to reload, and false otherwise. Typically,
* pressing the refresh button in a browser is a reload, while clicking a
* link and pressing the back button is not.
* @readonly
*/
isReload: boolean;
/**
* Returns the Request that triggered the event handler.
* @readonly
*/
request: Request;
/**
* Returns the Client that the current service worker is controlling.
* @readonly
*/
client: ServiceWorkerClient;
/**
* Resolves by returning a Response or a network error to Fetch.
*
* @param all
*/
respondWith(all: any): Response;
}
/**
* Represents a service worker. Multiple browsing contexts (e.g. pages, workers,
* etc.) can be associated with the same ServiceWorker object.
@@ -541,24 +252,47 @@ interface ServiceWorker extends Worker {
* Returns the ServiceWorker serialized script URL defined as part of
* ServiceWorkerRegistration. The URL must be on the same origin as the
* document that registers the ServiceWorker.
* @readonly
*/
scriptURL: string;
readonly scriptURL: string;
/**
* Returns the state of the service worker. It returns one of the following
* values: installing, installed, activating, activated, or redundant.
* @readonly
*/
state: string;
readonly state: string;
/**
* An EventListener property called whenever an event of type statechange
* is fired; it is basically fired anytime the ServiceWorker.state changes.
*
* @param [statechangeevent]
*/
onstatechange: (statechangeevent?: any) => void;
onstatechange: (statechangeevent: Event) => void;
}
/**
* The PushMessageData interface of the Push API provides
* methods which let you retrieve the push data sent by a server in various formats.
*/
interface PushMessageData {
/**
* Extracts the data as an ArrayBuffer object.
*/
arrayBuffer(): ArrayBuffer;
/**
* Extracts the data as a Blob object.
*/
blob(): Blob;
/**
* Extracts the data as a JSON object.
*/
json(): any;
json<T>(): T;
/**
* Extracts the data as a plain text string.
*/
text(): string;
}
/**
@@ -568,15 +302,13 @@ interface ServiceWorker extends Worker {
interface PushSubscription {
/**
* The endpoint associated with the push subscription.
* @readonly
*/
endpoint: any;
readonly endpoint: any;
/**
* The subscription ID associated with the push subscription.
* @readonly
*/
subscriptionId: any;
readonly subscriptionId: any;
}
/**
@@ -586,17 +318,15 @@ interface PushSubscriptionOptions {
/**
* A boolean indicating that the returned push subscription will only be used for
* messages whose effect is made visible to the user.
* @readonly
*/
userVisibleOnly: boolean;
readonly userVisibleOnly: boolean;
/**
* A public key your push server will use to send messages to client apps via a push server.
* This value is part of a signing key pair generated by your application server and usable
* with elliptic curve digital signature (ECDSA) over the P-256 curve.
* @readonly
*/
applicationServerKey?: Uint8Array;
readonly applicationServerKey?: Uint8Array;
}
/**
@@ -609,6 +339,8 @@ interface PushManager {
/**
* Returns a promise that resolves to a PushSubscription with details of a
* new push subscription.
*
* @param [options] An object containing optional configuration parameters.
*/
subscribe(options?: PushSubscriptionOptions): Promise<PushSubscription>;
@@ -625,6 +357,168 @@ interface PushManager {
hasPermission(): Promise<any>;
}
/////// Service Worker Events ///////
/**
* Extends the lifetime of the install and activate events dispatched on the
* ServiceWorkerGlobalScope as part of the service worker lifecycle. This
* ensures that any functional events (like FetchEvent) are not dispatched to
* the ServiceWorker until it upgrades database schemas, deletes outdated cache
* entries, etc.
*/
interface ExtendableEvent extends Event {
/**
* Extends the lifetime of the event.
* It is intended to be called in the install EventHandler for the
* installing worker and on the active EventHandler for the active worker.
*
* @param promise
*/
waitUntil(promise: Promise<any>): void;
}
/**
* The parameter passed into the ServiceWorkerGlobalScope.onfetch handler,
* FetchEvent represents a fetch action that is dispatched on the
* ServiceWorkerGlobalScope of a ServiceWorker. It contains information about
* the request and resulting response, and provides the FetchEvent.respondWith()
* method, which allows us to provide an arbitrary response back to the
* controlled page.
*/
interface FetchEvent extends Event {
/**
* Returns a Boolean that is true if the event was dispatched with the
* user's intention for the page to reload, and false otherwise. Typically,
* pressing the refresh button in a browser is a reload, while clicking a
* link and pressing the back button is not.
*/
readonly isReload: boolean;
/**
* Returns the Request that triggered the event handler.
*/
readonly request: Request;
/**
* Returns the Client that the current service worker is controlling.
*/
readonly client: ServiceWorkerClient;
/**
* Returns the id of the client that the current service worker is controlling.
*/
readonly clientId: string;
/**
* Resolves by returning a Response or a network error to Fetch.
*
* @param all Any custom response-generating code.
*/
respondWith(all: any): Response;
}
/**
* The ExtendableMessageEvent interface of the ServiceWorker API represents
* the event object of a message event fired on
* a service worker (when a channel message is received on
* the ServiceWorkerGlobalScope from another context)
* — extends the lifetime of such events.
*/
interface ExtendableMessageEvent extends ExtendableEvent {
/**
* Returns the event's data. It can be any data type.
*/
readonly data: any;
/**
* Returns the origin of the ServiceWorkerClient that sent the message
*/
readonly origin: string;
/**
* Represents, in server-sent events, the last event ID of the event source.
*/
readonly lastEventId: string;
/**
* Returns a reference to the service worker that sent the message.
*/
readonly source: ServiceWorkerClient;
/**
* Returns the array containing the MessagePort objects
* representing the ports of the associated message channel.
*/
readonly ports: MessagePort[];
}
/**
* The parameter passed into the oninstall handler, the InstallEvent interface
* represents an install action that is dispatched on the
* ServiceWorkerGlobalScope of a ServiceWorker. As a child of ExtendableEvent,
* it ensures that functional events such as FetchEvent are not dispatched
* during installation.
*/
interface InstallEvent extends ExtendableEvent {
/**
* Returns the ServiceWorker that is currently actively controlling the page.
*/
readonly activeWorker: ServiceWorker;
}
/**
* The parameter passed into the onnotificationclick handler,
* the NotificationEvent interface represents
* a notification click event that is dispatched on
* the ServiceWorkerGlobalScope of a ServiceWorker.
*/
interface NotificationEvent extends ExtendableEvent {
/**
* Returns a Notification object representing
* the notification that was clicked to fire the event.
*/
notification: any; // need to be replaced with `Notification` when possible
/**
* Returns the string ID of the notification button the user clicked.
* This value returns undefined if the user clicked
* the notification somewhere other than an action button,
* or the notification does not have a button.
*/
action: string;
}
/**
* The PushEvent interface of the Push API represents
* a push message that has been received.
* This event is sent to the global scope of a ServiceWorker.
* It contains the information sent from an application server to a PushSubscription.
*/
interface PushEvent extends ExtendableEvent {
/**
* Returns a reference to a PushMessageData object containing
* data sent to the PushSubscription.
*/
readonly data: PushMessageData;
}
interface ServiceWorkerContainerEventMap {
"message": MessageEvent;
"error": ErrorEvent;
"controllerchange": Event;
}
interface ServiceWorkerEventMap {
"activate": ExtendableEvent;
"fetch": FetchEvent;
"install": InstallEvent;
// "message": ExtendableMessageEvent;
"message": MessageEvent;
"notificationclick": NotificationEvent;
"push": PushEvent;
"pushsubscriptionchang": PushEvent;
}
/**
* Represents a service worker registration.
*/
@@ -633,23 +527,20 @@ interface ServiceWorkerRegistration extends EventTarget {
* Returns a unique identifier for a service worker registration.
* This must be on the same origin as the document that registers
* the ServiceWorker.
* @readonly
*/
scope: any;
readonly scope: any;
/**
* Returns a service worker whose state is installing. This is initially
* set to null.
* @readonly
*/
installing: ServiceWorker;
readonly installing: ServiceWorker;
/**
* Returns a service worker whose state is installed. This is initially
* set to null.
* @readonly
*/
waiting: ServiceWorker;
readonly waiting: ServiceWorker;
/**
* Returns a service worker whose state is either activating or activated.
@@ -657,17 +548,15 @@ interface ServiceWorkerRegistration extends EventTarget {
* ServiceWorkerClient if the client's URL falls within the scope of the
* registration (the scope option set when ServiceWorkerContainer.register
* is first called).
* @readonly
*/
active: ServiceWorker;
readonly active: ServiceWorker;
/**
* Returns an interface to for managing push subscriptions, including
* subcribing, getting an anctive subscription, and accessing push
* permission status.
* @readonly
*/
pushManager: PushManager;
readonly pushManager: PushManager;
/**
* An EventListener property called whenever an event of type updatefound
@@ -699,49 +588,41 @@ interface ServiceWorkerRegisterOptions {
* service workers, and access the state of service workers
* and their registrations.
*/
interface ServiceWorkerContainer {
interface ServiceWorkerContainer extends EventTarget {
/**
* Returns a ServiceWorker object if its state is activated (the same object
* returned by ServiceWorkerRegistration.active). This property returns null
* if the request is a force refresh (Shift + refresh) or if there is no
* active worker.
* @readonly
*/
controller: ServiceWorker;
readonly controller: ServiceWorker;
/**
* Defines whether a service worker is ready to control a page or not.
* It returns a Promise that will never reject, which resolves to a
* ServiceWorkerRegistration with an ServiceWorkerRegistration.active worker.
* @readonly
*/
ready: Promise<ServiceWorkerRegistration>;
readonly ready: Promise<ServiceWorkerRegistration>;
/**
* An event handler fired whenever a controllerchange event occurs — when
* the document's associated ServiceWorkerRegistration acquires a new
* ServiceWorkerRegistration.active worker.
*
* @param [controllerchangeevent]
*/
oncontrollerchange: (controllerchangeevent?: Event) => void;
oncontrollerchange: (controllerchangeevent: Event) => void;
/**
* An event handler fired whenever an error event occurs in the associated
* service workers.
*
* @param [errorevent]
*/
onerror: (errorevent?: ErrorEvent) => void;
onerror: (errorevent: ErrorEvent) => void;
/**
* An event handler fired whenever a message event occurs — when incoming
* messages are received to the ServiceWorkerContainer object (e.g. via a
* MessagePort.postMessage() call.)
*
* @param [messageevent]
*/
onmessage: (messageevent?: MessageEvent) => void;
onmessage: (messageevent: MessageEvent) => void;
/**
* Creates or updates a ServiceWorkerRegistration for the given scriptURL.
@@ -771,82 +652,50 @@ interface ServiceWorkerContainer {
* ServiceWorkerContainer in an array. If the method can't return
* ServiceWorkerRegistrations, it returns a Promise.
*/
getRegistrations(): Promise<Array<ServiceWorkerRegistration>>;
getRegistrations(): Promise<ServiceWorkerRegistration[]>;
addEventListener<K extends keyof ServiceWorkerContainerEventMap>(
type: K,
listener: (event: ServiceWorkerContainerEventMap[K]) => any,
useCapture?: boolean
): void;
}
/**
* The parameter passed into the oninstall handler, the InstallEvent interface
* represents an install action that is dispatched on the
* ServiceWorkerGlobalScope of a ServiceWorker. As a child of ExtendableEvent,
* it ensures that functional events such as FetchEvent are not dispatched
* during installation.
*/
interface InstallEvent extends ExtendableEvent {
interface ServiceWorkerGlobalScope extends EventTarget {
/**
* Returns the ServiceWorker that is currently actively controlling the page.
* @readonly
* Contains the CacheStorage object associated with the service worker.
*/
activeWorker: ServiceWorker;
}
interface ServiceWorkerGlobalScope {
readonly caches: CacheStorage;
/**
* Contains the Clients object associated with the service worker.
* @readonly
*/
clients: ServiceWorkerClients;
readonly clients: ServiceWorkerClients;
/**
* Contains the ServiceWorkerRegistration object that represents the
* service worker's registration.
* @readonly
*/
registration: ServiceWorkerRegistration;
readonly registration: ServiceWorkerRegistration;
/**
* An event handler fired whenever an activate event occurs — when a
* ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.active
* worker.
*
* @param [activateevent]
*/
onactivate: (activateevent?: ExtendableEvent) => void;
/**
* Not defined in the spec yet, but it looks like this will be fired when
* the device is nearly out of storage space, prompting the UA to start
* claiming back some space from web apps that are using client-side storage,
* and the current app is targeted.
*
* @param [beforeevictedevent]
*/
onbeforeevicted: (beforeevictedevent?: Event) => void;
/**
* Not defined in the spec yet, but it looks like this will be fired when
* the device is out of storage space, and the UA claims back some space
* from the current app.
*
* @param [evictedevent]
*/
onevicted: (evictedevent?: Event) => void;
onactivate: (activateevent: ExtendableEvent) => void;
/**
* An event handler fired whenever a fetch event occurs — when a fetch()
* is called.
*
* @param [fetchevent]
*/
onfetch: (fetchevent?: FetchEvent) => void;
onfetch: (fetchevent: FetchEvent) => void;
/**
* An event handler fired whenever an install event occurs — when a
* ServiceWorkerRegistration acquires a new
* ServiceWorkerRegistration.installing worker.
*
* @param [installevent]
*/
oninstall: (installevent?: InstallEvent) => void;
oninstall: (installevent: InstallEvent) => void;
/**
* An event handler fired whenever a message event occurs — when incoming
@@ -856,34 +705,31 @@ interface ServiceWorkerGlobalScope {
* MessagePort exposed in event.data.port, corresponding to the controlled
* page.
*
* @param [messageevent]
* `onmessage` is actually fired with `ExtendableMessageEvent`, but
* since we are merging the interface into `Window`, we should
* make sure it's compatible with `window.onmessage`
*/
onmessage: (messageevent?: MessageEvent) => void;
// onmessage: (messageevent: ExtendableMessageEvent) => void;
onmessage: (messageevent: MessageEvent) => void;
/**
* An event handler fired whenever a notificationclick event occurs — when
* a user clicks on a displayed notification.
*
* @param [notificationclickevent]
*/
onnotificationclick: (notificationclickevent?: NotificationEvent) => void;
onnotificationclick: (notificationclickevent: NotificationEvent) => void;
/**
* An event handler fired whenever a push event occurs — when a server
* push notification is received.
*
* @param [onpushevent]
*/
onpush: (onpushevent?: Event) => void;
onpush: (onpushevent: PushEvent) => void;
/**
* An event handler fired whenever a pushsubscriptionchange event occurs —
* when a push subscription has been invalidated, or is about to be
* invalidated (e.g. when a push service sets an expiration time).
*
* @param [pushsubscriptionchangeevent]
*/
onpushsubscriptionchange: (pushsubscriptionchangeevent?: Event) => void;
onpushsubscriptionchange: (pushsubscriptionchangeevent: PushEvent) => void;
/**
* Allows the current service worker registration to progress from waiting
@@ -891,12 +737,11 @@ interface ServiceWorkerGlobalScope {
*/
skipWaiting(): Promise<void>;
/**
* TODO GlobalFetch
* @param url
* @param init
*/
fetch(url: string | Request, init?: Object): Promise<Response>;
addEventListener<K extends keyof ServiceWorkerEventMap>(
type: K,
listener: (event: ServiceWorkerEventMap[K]) => any,
useCapture?: boolean
): void;
}
interface Navigator {
@@ -908,10 +753,5 @@ interface Navigator {
serviceWorker: ServiceWorkerContainer;
}
interface Window extends ServiceWorkerGlobalScope {
caches: CacheStorage;
}
interface NotificationEvent extends Event, ExtendableEvent {
notification: any;
}
// tslint:disable-next-line no-empty-interface
interface Window extends ServiceWorkerGlobalScope {}
+20 -15
View File
@@ -17,7 +17,7 @@ self.addEventListener('fetch', function(event: FetchEvent) {
});
self.caches.open('v1').then(function(cache: Cache) {
cache.matchAll('/images/').then(function(response: Array<Response>) {
cache.matchAll('/images/').then(function(response: Response[]) {
response.forEach(function(element, index, array) {
cache.delete(element.url);
});
@@ -86,7 +86,7 @@ self.caches.open('v1').then(function(cache: Cache) {
self.caches.has('v1').then(function() {
self.caches.delete('v1').then(function() {
console.log('done');
});
});
@@ -95,16 +95,16 @@ self.addEventListener('activate', function(event: ExtendableEvent) {
event.waitUntil(
self.caches.keys().then(function(keyList) {
for(var i = 0; i < keyList.length; i++) {
if (cacheWhitelist.indexOf(keyList[i]) === -1) {
return self.caches.delete(keyList[i]);
for (var item of keyList) {
if (cacheWhitelist.indexOf(item) === -1) {
return self.caches.delete(item);
}
}
})
);
});
function sendMessage(message: string) {
function sendMessage(message: any) {
return new Promise(function(resolve, reject) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event) {
@@ -118,10 +118,18 @@ function sendMessage(message: string) {
});
}
self.addEventListener('message', function(evt: ExtendableMessageEvent) {
evt.ports[0].postMessage(evt.source.id);
});
sendMessage('test').then(function(clientId: string) {
console.log(clientId);
});
self.clients.matchAll({type: "test"}).then(function(clients) {
for(var i = 0 ; i < clients.length ; i++) {
if(clients[i].url === 'index.html') {
self.clients.openWindow(clients[i].url);
for (var cli of clients) {
if(cli.url === 'index.html') {
self.clients.openWindow(cli.url);
// or do something else involving the matching client
}
}
@@ -157,11 +165,11 @@ navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(functi
});
navigator.serviceWorker.getRegistration('/app').then(function(registration: ServiceWorkerRegistration) {
console.log(registration);
});
navigator.serviceWorker.getRegistrations().then(function(registrations: Array<ServiceWorkerRegistration>) {
navigator.serviceWorker.getRegistrations().then(function(registrations: ServiceWorkerRegistration[]) {
console.log(registrations);
});
self.registration.unregister();
@@ -179,9 +187,6 @@ self.addEventListener('notificationclick', function(event: NotificationEvent) {
event.waitUntil(self.clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
}
if (self.clients.openWindow)
return self.clients.openWindow('/');
}));
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+113
View File
@@ -0,0 +1,113 @@
// Type definitions for simple-oauth2 1.0
// Project: https://github.com/lelylan/simple-oauth2
// Definitions by: [Michael Müller] <https://github.com/mad-mike>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import Bluebird = require("bluebird");
/** Creates a new simple-oauth2 client with the passed configuration */
export function create(options: ModuleOptions): OAuthClient;
interface ModuleOptions {
client: {
/** Service registered client id. Required. */
id: string,
/** Service registered client secret. Required. */
secret: string,
/** Parameter name used to send the client secret. Default to client_secret. */
secretParamName?: string,
/** Parameter name used to send the client id. Default to client_id. */
idParamName?: string
};
auth: {
/** String used to set the host to request the tokens to. Required. */
tokenHost: string,
/** String path to request an access token. Default to /oauth/token. */
tokenPath?: string,
/** String path to revoken an access token. Default to /oauth/revoke. */
revokePath?: string,
/** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */
authorizeHost?: string,
/** String path to request an authorization code. Default to /oauth/authorize. */
authorizePath?: string
};
/** optional object used to set global options to the internal http library (request-js). */
http?: {};
options?: {
/** Wheather or not the client.id/client.secret params are sent in the request body. Defaults to true. */
useBodyAuth?: boolean,
useBasicAuthorizationHeader?: boolean
};
}
type TokenType = "access_token" | "refresh_token";
interface AccessToken {
token: {};
/** Check if the access token is expired or not */
expired(): boolean;
/** Refresh the access token */
refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird<AccessToken>;
refresh(callback?: (error: any, result: AccessToken) => void): Bluebird<AccessToken>;
/** Revoke access or refresh token */
revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird<void>;
}
interface Token {
[x: string]: any;
}
type AuthorizationCode = string;
interface AuthorizationTokenConfig {
code: AuthorizationCode;
redirect_uri: string;
}
interface PasswordTokenConfig {
/** A string that represents the registered username */
username: string;
/** A string that represents the registered password. */
password: string;
/** A string that represents the application privileges */
scope: string;
}
interface ClientCredentialTokenConfig {
/** A string that represents the application privileges */
scope?: string;
}
export interface OAuthClient {
authorizationCode: {
/**
* Redirect the user to the autorization page
* @return {string} the absolute authorization url
*/
authorizeURL(params?: {
/** A string that represents the registered application URI where the user is redirected after authentication */
redirect_uri?: string,
/** A String that represents the application privileges */
scope?: string,
/** A String that represents an option opaque value used by the client to main the state between the request and the callback */
state?: string
}): string,
/** Returns the Access Token object */
getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird<Token>;
};
ownerPassword: {
/** Returns the Access Token Object */
getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird<Token>;
};
clientCredentials: {
/** Returns the Access Token Object */
getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird<Token>;
};
accessToken: {
/** Creates an OAuth2.AccessToken instance */
create(tokenToUse: Token): AccessToken;
};
}
+162
View File
@@ -0,0 +1,162 @@
// off https://github.com/lelylan/simple-oauth2/blob/master/README.md
// slightly changed to remove external dependencies
// Set the configuration settings
const credentials = {
client: {
id: '<client-id>',
secret: '<client-secret>'
},
auth: {
tokenHost: 'https://api.oauth.com'
}
};
// Initialize the OAuth2 Library
//const oauth2 = require('simple-oauth2').create(credentials);
import oauth2lib = require("simple-oauth2");
const oauth2 = oauth2lib.create(credentials);
// #Authorization Code flow
(function () {
// Authorization oauth2 URI
const authorizationUri = oauth2.authorizationCode.authorizeURL({
redirect_uri: 'http://localhost:3000/callback',
scope: '<scope>',
state: '<state>'
});
// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
//res.redirect(authorizationUri);
// Get the access token object (the authorization code is given from the previous step).
const tokenConfig = {
code: '<code>',
redirect_uri: 'http://localhost:3000/callback'
};
// Callbacks
// Save the access token
oauth2.authorizationCode.getToken(tokenConfig, (error, result) => {
if (error) {
return console.log('Access Token Error', error.message);
}
const token = oauth2.accessToken.create(result);
});
// Promises
// Save the access token
oauth2.authorizationCode.getToken(tokenConfig)
.then((result) => {
const token = oauth2.accessToken.create(result);
})
.catch((error) => {
console.log('Access Token Error', error.message);
});
})();
// #Client Credentials Flow
(function () {
const tokenConfig = {};
// Callbacks
// Get the access token object for the client
oauth2.clientCredentials.getToken(tokenConfig, (error, result) => {
if (error) {
return console.log('Access Token Error', error.message);
}
const token = oauth2.accessToken.create(result);
});
// Promises
// Get the access token object for the client
oauth2.clientCredentials
.getToken(tokenConfig)
.then((result) => {
const token = oauth2.accessToken.create(result);
})
.catch((error) => {
console.log('Access Token error', error.message);
});
})();
// #Access Token object
(function () {
// Sample of a JSON access token (you got it through previous steps)
const tokenObject = {
'access_token': '<access-token>',
'refresh_token': '<refresh-token>',
'expires_in': '7200'
};
// Create the access token wrapper
var token = oauth2.accessToken.create(tokenObject);
// Check if the token is expired. If expired it is refreshed.
if (token.expired()) {
// Callbacks
token.refresh((error, result) => {
token = result;
})
// Promises
token.refresh()
.then((result) => {
token = result;
});
}
// Callbacks
// Revoke only the access token
token.revoke('access_token', (error) => {
// Session ended. But the refresh_token is still valid.
// Revoke the refresh_token
token.revoke('refresh_token', (error) => {
console.log('token revoked.');
});
});
// Promises
// Revoke only the access token
token.revoke('access_token')
.then(() => {
// Revoke the refresh token
return token.revoke('refresh_token');
})
.then(() => {
console.log('Token revoked');
})
.catch((error) => {
console.log('Error revoking token.', error.message);
});
})();
// #Errors
// not applicable, as those errors about missing authentication codes are already found by the typescript compiler
// (function () {
// // Callbacks
// oauth2.authorizationCode.getToken({}, (error, token) => {
// if (error) {
// return console.log(error.message);
// }
// });
// // Promises
// oauth2.authorizationCode
// .getToken({})
// .catch((error) => {
// console.log(error.message);
// });
// // => { "status": "401", "message": "Unauthorized" }
// })();
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"simple-oauth2-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+2 -1
View File
@@ -34,6 +34,7 @@ import { Express, NextFunction } from "express";
import { Spec } from "swagger-schema-official";
import { EventEmitter } from "events";
import * as Hapi from "hapi";
import * as Restify from "restify";
/**
* Config object for SwaggerNodeRunner
@@ -258,7 +259,7 @@ export interface HapiMiddleware extends Middleware {
/** Restify specific Middleware */
export interface RestifyMiddleware extends Middleware {
/** Register this Middleware with `app` */
register: (app: any) => void;
register: (app: Restify.Server) => void;
}
@@ -1,6 +1,9 @@
import * as SwaggerNodeRunner from "swagger-node-runner";
import * as express from "express";
import * as connect from "connect";
import * as Hapi from "hapi";
import * as restify from "restify";
import * as sails from "sails.io.js";
let config: SwaggerNodeRunner.Config = {
appRoot: __dirname
@@ -20,6 +23,30 @@ SwaggerNodeRunner.create(config, (err, runner) => {
});
//Connect middleware
let connectApp = connect();
SwaggerNodeRunner.create(config, (err, runner) => {
if (err) { throw err; }
let conncetMiddleware = runner.connectMiddleware();
conncetMiddleware.register(connectApp);
var port = process.env.PORT || 10010;
connectApp.listen(port);
});
// Sails Middleware (chain) test
SwaggerNodeRunner.create(config, (err, runner) => {
if (err) { throw err; }
let sailsMw = runner.sailsMiddleware();
if(typeof sailsMw.chain !== 'function' || !sailsMw.runner) {
// do nothing
}
});
//Hapi Middleware
var hapiapp = new Hapi.Server();
SwaggerNodeRunner.create(config, function(err, runner) {
@@ -45,6 +72,20 @@ SwaggerNodeRunner.create(config, function(err, runner) {
});
// Restify Middelware
let app = restify.createServer();
SwaggerNodeRunner.create(config, function(err, runner) {
if (err) { throw err; }
let restifyMiddelware = runner.restifyMiddleware()
restifyMiddelware.register(app);
let port = process.env.PORT || 10010;
app.listen(port);
});
let swaggerSecurityHandlerCb = (err: Error) => {
//do nothing
};
+47
View File
@@ -0,0 +1,47 @@
// Type definitions for swagger-restify-mw 0.7
// Project: https://github.com/apigee-127/swagger-restify#readme
// Definitions by: Michael Mrowetz <https://github.com/micmro/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/* =================== USAGE ===================
import * as SwaggerRestify from "swagger-restify-mw";
import * as restify from "restify";
let app = restify.createServer();
let config = {
appRoot: __dirname // required config
} as SwaggerRestify.Config;
SwaggerRestify.create(config, function(err, swaggerRestify) {
if (err) { throw err; }
swaggerRestify.register(app);
let port = process.env.PORT || 10010;
app.listen(port);
if (swaggerRestify.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});
=============================================== */
import { Config, RestifyMiddleware } from "swagger-node-runner";
/** export interfaces */
export { Config, RestifyMiddleware } from "swagger-node-runner";
/**
* Create a new instance of a Restify specific `SwaggerNodeRunner` middleware
*
* The `swagger-node-runner` module has the following config priority:
* 1. `swagger_*` environment vars
* 2. `config` passed to `create()`
* 3. read from swagger node in `default.yaml` in config directory
* 4. module defaults
*
* @see @link{https://github.com/apigee-127/swagger-express|Github}
*/
export function create(config: Config, cb: (err: Error | undefined, middleware: RestifyMiddleware) => void): void;
@@ -0,0 +1,39 @@
import * as SwaggerRestify from "swagger-restify-mw";
import * as restify from "restify";
let app = restify.createServer();
let config = {
appRoot: __dirname // required config
} as SwaggerRestify.Config;
SwaggerRestify.create(config, function(err, swaggerRestify) {
if (err) { throw err; }
swaggerRestify.register(app);
let port = process.env.PORT || 10010;
app.listen(port);
});
let swaggerSecurityHandlerCb = (err: Error) => {
//do nothing
};
let configComplex: SwaggerRestify.Config = {
appRoot: __dirname,
configDir: "some/directory",
controllersDirs: ["some/directory"],
fittingsDirs: ["some/directory"],
mockMode: true,
swaggerControllerPipe: 'swagger_controllers',
swaggerSecurityHandlers: {
// did not manage to research the typings of first 3 arguments
someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => {
//do nothing
}
},
validateResponse: true
};
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"swagger-restify-mw-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+55
View File
@@ -0,0 +1,55 @@
// Type definitions for swagger-sails-hook 0.7
// Project: https://github.com/apigee-127/swagger-sails#readme
// Definitions by: Michael Mrowetz <https://github.com/micmro/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/* =================== USAGE ===================
// Registers itself as sails hook, when added to the project via `npm install swagger-sails-hook`.
// see http://sailsjs.com/documentation/concepts/extending-sails/hooks
=============================================== */
import { Config, SailsMiddleware } from "swagger-node-runner";
export = SwaggerHook;
/**
* Create a new `swagger-sails-hook` sails hook and register it with `sails`
* @param {any} sails - reference to the running sails instance
* @returns SailsHook - `swagger-sails-hook` object implementing the Sails' hook specification.
*/
declare function SwaggerHook(sails: any): SwaggerHook.SailsHook;
declare namespace SwaggerHook {
/**
* `swagger-sails-hook` object implementing the Sails' hook specification.
*
* @see {@link http://sailsjs.com/documentation/concepts/extending-sails/hooks/hook-specification|Sails Hook Docs}
* @see {@link http://sailsjs.com/documentation/anatomy/api/hooks/my-hook/index-js|Sails Hook Example}
*/
export interface SailsHook {
/**
* Perform startup tasks.
* All Sails configuration is guaranteed to be completed before a hook’s initialize function runs.
* @param {Function} done - called when `swagger-sails-hook`'s startup tasks have finished.
*/
initialize: (done: () => any) => void;
/**
* `swagger-sails-hook` specific route bound to a Sails app at load time.
*
* It handles any unhandled requests (any routes that aren't bound in the app via a
* custom route configuration or a blueprint) via the swagger middleware.
*/
routes: {
/** routes specified in the `after` object will be bound after custom and blueprint routes */
after: {
/**
* This route will match any routes that aren't bound in the app via a custom route configuration
* or a blueprint.
*/
"/*": (req: any, res: any, next: () => any) => any
}
};
}
}
@@ -0,0 +1,21 @@
import swaggerSailsHook = require("swagger-sails-hook");
import * as express from "express";
const mockSailsApp = {
models: {},
conf: {},
sockets: {},
hooks: {},
lift: () => { /* do nothing */ }
};
// create and register hook
let swaggerHookRef = swaggerSailsHook(mockSailsApp);
if(typeof swaggerHookRef.routes.after['/*'] === 'function') {
// right type
}
swaggerHookRef.initialize(() => {
// do something, when initialized
});
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"swagger-sails-hook-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+5 -9
View File
@@ -5,12 +5,8 @@
/// <reference types="node" />
declare namespace XsdSchemaValidator {
export function validateXML(xml: string|NodeJS.ReadableStream|{file: string}, pathToXsd: string, callback: (err: Error, result: {
valid: boolean;
messages: string[];
result: string;
}) => void): void;
}
export = XsdSchemaValidator;
export function validateXML(xml: string|NodeJS.ReadableStream|{file: string}, pathToXsd: string, callback: (err: Error, result: {
valid: boolean;
messages: string[];
result: string;
}) => void): void;