This commit is contained in:
Zak
2017-04-11 16:14:26 -04:00
127 changed files with 66796 additions and 63608 deletions
+1380
View File
File diff suppressed because it is too large Load Diff
+388
View File
@@ -0,0 +1,388 @@
/*
* Test file for node-jose. At this time these tests were taken verbatim
* from the documentation on the NPM page at
* https://www.npmjs.com/package/node-jose
* This file definitely needs to be cleaned up and more tests added to
* test the entirety of the definition file.
*/
import * as jose from 'node-jose';
let keystore = jose.JWK.createKeyStore();
let buf = new Buffer('a');
jose.JWK.asKeyStore("{key: somekey}").
then(function (result) {
// {result} is a jose.JWK.KeyStore
keystore = result;
});
let output = keystore.toJSON();
output = keystore.toJSON(true);
// by 'kid'
let kid: string = "someID";
let key = keystore.get(kid);
// ... and by 'kty'
key = keystore.get(kid, { kty: 'RSA' });
// ... and by 'use'
key = keystore.get(kid, { use: 'enc' });
// ... and by 'alg'
key = keystore.get(kid, { use: 'RSA-OAEP' });
// ... and by 'kty' and 'use'
key = keystore.get(kid, { kty: 'RSA', use: 'enc' });
// same as above, but with a single {props} argument
key = keystore.get({ kid: kid, kty: 'RSA', use: 'enc' });
// searching for keys
let everything = keystore.all();
// filter by 'kid'
everything = keystore.all({ kid: kid });
// filter by 'kty'
everything = keystore.all({ kty: 'RSA' });
// filter by 'use'
everything = keystore.all({ use: 'enc' });
// filter by 'alg'
everything = keystore.all({ alg: 'RSA-OAEP' });
// filter by 'kid' + 'kty' + 'alg'
everything = keystore.all({ kid: kid, kty: 'RSA', alg: 'RSA-OAEP' });
// input is either a:
// * jose.JWK.Key to copy from; or
// * JSON object representing a JWK; or
keystore.add({}).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// input is either a:
// * String serialization of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// * Buffer of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// form is either a:
// * "json" for a JSON stringified JWK
// * "private" for a DER encoded 'raw' private key
// * "pkcs8" for a DER encoded (unencrypted!) PKCS8 private key
// * "public" for a DER encoded SPKI public key (alternate to 'spki')
// * "spki" for a DER encoded SPKI public key
// * "pkix" for a DER encoded PKIX X.509 certificate
// * "x509" for a DER encoded PKIX X.509 certificate
// * "pem" for a PEM encoded of PKCS8 / SPKI / PKIX
keystore.add(buf, "json").
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// first argument is the key type (kty)
// second is the key size (in bits) or named curve ('crv') for "EC"
keystore.generate("oct", 256).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// ... with properties
var props = {
kid: 'gBdaS-G8RLax2qgObTD94w',
alg: 'A256GCM',
use: 'enc'
};
keystore.generate("oct", 256, props).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
keystore.remove(key);
// NOTE: key.keystore does not change!!
// where input is either a:
// * jose.JWK.Key instance
// * JSON Object representation of a JWK
jose.JWK.asKey({}).
then(function (result) {
// {result} is a jose.JWK.Key
// {result.keystore} is a unique jose.JWK.KeyStore
key = result;
});
// where input is either a:
// * String serialization of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// * Buffer of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// form is either a:
// * "json" for a JSON stringified JWK
// * "pkcs8" for a DER encoded (unencrypted!) PKCS8 private key
// * "spki" for a DER encoded SPKI public key
// * "pkix" for a DER encoded PKIX X.509 certificate
// * "x509" for a DER encoded PKIX X.509 certificate
// * "pem" for a PEM encoded of PKCS8 / SPKI / PKIX
jose.JWK.asKey({}, 'json').
then(function (result) {
// {result} is a jose.JWK.Key
// {result.keystore} is a unique jose.JWK.KeyStore
key = result;
});
output = key.toJSON();
output = key.toJSON(true);
// where hash is a supported algorithm, currently one of:
// * SHA-1
// * SHA-256
// * SHA-384
// * SHA-512
key.thumbprint('SHA-1').
then(function (print) {
// {print} is a Buffer containing the thumbprint binary value
});
// {input} is a Buffer
jose.JWS.createSign(key).
update(buf).
final().
then(function (result) {
// {result} is a JSON object -- JWS using the JSON General Serialization
});
jose.JWS.createSign({ format: 'flattened' }, key).
update(buf).
final().
then(function (result) {
// {result} is a JSON object -- JWS using the JSON Flattened Serialization
});
jose.JWS.createSign({ format: 'compact' }, key).
update(buf).
final().
then(function (result) {
// {result} is a String -- JWS using the Compact Serialization
});
jose.JWS.createSign({ alg: 'PS256' }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createSign({ fields: { cty: 'jwk+json' } }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createSign(key).
update(buf, "utf8").
final().
then(function (result) {
// ....
});
// {keys} is an Array of jose.JWK.Key instances
jose.JWS.createSign([key, key]).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createVerify(keystore).
verify("some.jws.object").
then(function (result) {
// {result} is a Object with:
// * header: the combined 'protected' and 'unprotected' header members
// * payload: Buffer of the signed content
// * signature: Buffer of the verified signature
// * key: The key used to verify the signature
});
// {key} can be:
// * jose.JWK.Key
// * JSON object representing a JWK
jose.JWS.createVerify(key).
verify('some.jws.object').
then(function (result) {
// ...
});
jose.JWS.createVerify().
verify('some.jws.key').
then(function (result) {
// ...
});
var opts = {
handlers: {
"exp": true
}
};
jose.JWS.createVerify(key, opts).
verify('some.jws.key').
then(function (result) {
// ...
});
var opts2 = {
handlers: {
"exp": function (jws: any) {
// {jws} is the JWS verify output, pre-verification
jws.header.exp = new Date(jws.header.exp);
}
}
};
jose.JWS.createVerify(key, opts2).
verify('some.jws.key').
then(function (result) {
// ...
});
var opts3 = {
handlers: {
"exp": {
complete: function (jws: any) {
// {jws} is the JWS verify output, post-verification
jws.header.exp = new Date(jws.header.exp);
}
}
}
};
jose.JWS.createVerify(key, opts3).
verify('some.jws.key').
then(function (result) {
// ...
});
//Encryption
// {input} is a Buffer
jose.JWE.createEncrypt(key).
update(buf).
final().
then(function (result) {
// {result} is a JSON Object -- JWE using the JSON General Serialization
});
jose.JWE.createEncrypt({ format: 'compact' }, key).
update(buf).
final().
then(function (result) {
// {result} is a String -- JWE using the Compact Serialization
});
jose.JWE.createEncrypt({ format: 'flattened' }, key).
update(buf).
final().
then(function (result) {
// {result} is a JSON Object -- JWE using the JSON Flattened Serialization
});
jose.JWE.createEncrypt({ zip: true }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWE.createEncrypt({ fields: { cty: 'jwk+json' } }, key).
update(buf).
final().
then(function (result) {
// ....
});
// {keys} is an Array of jose.JWK.Key instances
jose.JWE.createEncrypt([key, key]).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWE.createDecrypt(keystore).
decrypt('some.jwe').
then(function (result) {
// {result} is a Object with:
// * header: the combined 'protected' and 'unprotected' header members
// * protected: an array of the member names from the "protected" member
// * key: Key used to decrypt
// * payload: Buffer of the decrypted content
// * plaintext: Buffer of the decrypted content (alternate)
});
jose.JWE.createDecrypt(key).
decrypt('some.jwe').
then(function (result) {
// ....
});
var opts4 = {
handlers: {
"exp": true
}
};
jose.JWE.createDecrypt(key, opts4).
decrypt('some.jwe').
then(function (result) {
// ...
});
//To perform additional (pre-decrypt) processing on a crit header member:
var opts5 = {
handlers: {
"exp": function (jwe: any) {
// {jwe} is the JWE decrypt output, pre-decryption
jwe.header.exp = new Date(jwe.header.exp);
}
}
};
jose.JWE.createDecrypt(key, opts5).
decrypt('some.jwe').
then(function (result) {
// ...
});
//To perform additional (post-decrypt) processing on a crit header member:
var opts6 = {
handlers: {
"exp": {
complete: function (jwe: any) {
// {jwe} is the JWE decrypt output, post-decryption
jwe.header.exp = new Date(jwe.header.exp);
}
}
}
};
jose.JWE.createDecrypt(key, opts6).
decrypt('some.jwe').
then(function (result) {
// ...
});
var buff = jose.util.asBuffer('input');
var output2 = jose.util.base64url.encode(buf);
// explicit encoding
output2 = jose.util.base64url.encode(buf, "utf8");
// implied "utf8" encoding
output2 = jose.util.base64url.encode(buf);
var output3 = jose.util.base64url.decode('input');
// argument is size (in bytes)
var rnd = jose.util.randomBytes(32);
@@ -17,6 +17,6 @@
},
"files": [
"index.d.ts",
"xml-js-tests.ts"
"node-jose-tests.ts"
]
}
}
+46 -4
View File
@@ -24,6 +24,12 @@
"sourceRepoURL": "https://github.com/mzabriskie/axios",
"asOfVersion": "0.14.0"
},
{
"libraryName": "Bugsnag Browser",
"typingsPackageName": "bugsnag-js",
"sourceRepoURL": "https://github.com/bugsnag/bugsnag-js",
"asOfVersion": "3.1.0"
},
{
"libraryName": "camel-case",
"typingsPackageName": "camel-case",
@@ -36,6 +42,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/change-case",
"asOfVersion": "2.3.1"
},
{
"libraryName": "cheap-ruler",
"typingsPackageName": "cheap-ruler",
"sourceRepoURL": "https://github.com/mapbox/cheap-ruler",
"asOfVersion": "2.5.0"
},
{
"libraryName": "constant-case",
"typingsPackageName": "constant-case",
@@ -72,6 +84,12 @@
"sourceRepoURL": "https://github.com/bterlson/ecmarkup",
"asOfVersion": "3.4.0"
},
{
"libraryName": "FastSimplexNoise",
"typingsPackageName": "fast-simplex-noise",
"sourceRepoURL": "https://www.npmjs.com/package/fast-simplex-noise",
"asOfVersion": "3.0.0"
},
{
"libraryName": "FineUploader",
"typingsPackageName": "fine-uploader",
@@ -84,6 +102,12 @@
"sourceRepoURL": "https://github.com/ascoders/gaea-model",
"asOfVersion": "0.0.0"
},
{
"libraryName": "github",
"typingsPackageName": "github",
"sourceRepoURL": "https://github.com/mikedeboer/node-github",
"asOfVersion": "7.1.0"
},
{
"libraryName": "Facebook's Immutable",
"typingsPackageName": "immutable",
@@ -157,10 +181,10 @@
"asOfVersion": "1.0.0"
},
{
"libraryName": "localforage",
"typingsPackageName": "localforage",
"sourceRepoURL": "https://github.com/localForage/localForage",
"asOfVersion": "0.0.34"
"libraryName": "localforage",
"typingsPackageName": "localforage",
"sourceRepoURL": "https://github.com/localForage/localForage",
"asOfVersion": "0.0.34"
},
{
"libraryName": "lower-case",
@@ -174,6 +198,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/lower-case-first",
"asOfVersion": "1.0.1"
},
{
"libraryName": "maquette",
"typingsPackageName": "maquette",
"sourceRepoURL": "http://maquettejs.org/",
"asOfVersion": "2.1.6"
},
{
"libraryName": "mobservable",
"typingsPackageName": "mobservable",
@@ -336,6 +366,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/title-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "TsMonad",
"typingsPackageName": "tsmonad",
"sourceRepoURL": "https://github.com/cbowdon/TsMonad",
"asOfVersion": "0.5.0"
},
{
"libraryName": "TypeScript",
"typingsPackageName": "typescript",
@@ -378,6 +414,12 @@
"sourceRepoURL": "https://code.google.com/p/x2js/",
"asOfVersion": "3.1.0"
},
{
"libraryName": "xml-js",
"typingsPackageName": "xml-js",
"sourceRepoURL": "https://github.com/nashwaan/xml-js",
"asOfVersion": "1.0.0"
},
{
"libraryName": "@xmpp/jid",
"typingsPackageName": "xmpp-jid",
+1 -1
View File
@@ -12,7 +12,7 @@
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"engines": {
"node": ">= 6.9.1"
"node": ">=7.8.0"
},
"scripts": {
"compile-scripts": "tsc -p scripts",
+1 -1
View File
@@ -17,7 +17,7 @@ rmdirRecursive(path.join("types", typingsPackageName));
const notNeededPackages = JSON.parse(fs.readFileSync("notNeededPackages.json", "utf-8"));
notNeededPackages.packages.push({ libraryName, typingsPackageName, sourceRepoURL, asOfVersion });
notNeededPackages.packages.sort((x, y) => x.typingsPackageName < y.typingsPackageName ? -1 : 1);
fs.writeFileSync("notNeededPackages.json", JSON.stringify(notNeededPackages, undefined, 4), "utf-8");
fs.writeFileSync("notNeededPackages.json", JSON.stringify(notNeededPackages, undefined, 4) + "\n", "utf-8");
function rmdirRecursive(dir) {
for (let entry of fs.readdirSync(dir)) {
+1 -1
View File
@@ -63,7 +63,7 @@ declare namespace acorn {
class SourceLocation implements ESTree.SourceLocation {
start: Position;
end: Position;
source?: string;
source?: string | null;
constructor(p: Parser, start: Position, end: Position);
}
+54
View File
@@ -5,12 +5,17 @@ var num: number = 5;
var error: Error = new Error();
var b: boolean = true;
var apiGwEvt: AWSLambda.APIGatewayEvent;
var customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent;
var clientCtx: AWSLambda.ClientContext;
var clientContextEnv: AWSLambda.ClientContextEnv;
var clientContextClient: AWSLambda.ClientContextClient;
var context: AWSLambda.Context;
var identity: AWSLambda.CognitoIdentity;
var proxyResult: AWSLambda.ProxyResult;
var authResponse: AWSLambda.AuthResponse;
var policyDocument: AWSLambda.PolicyDocument;
var statement: AWSLambda.Statement;
var authResponseContext: AWSLambda.AuthResponseContext;
var snsEvt: AWSLambda.SNSEvent;
var snsEvtRecs: AWSLambda.SNSEventRecord[];
var snsEvtRec: AWSLambda.SNSEventRecord;
@@ -87,6 +92,11 @@ str = apiGwEvt.requestContext.resourceId;
str = apiGwEvt.requestContext.resourcePath;
str = apiGwEvt.resource;
/* API Gateway CustomAuthorizer Event */
str = customAuthorizerEvt.type;
str = customAuthorizerEvt.authorizationToken;
str = customAuthorizerEvt.methodArn;
/* SNS Event */
snsEvtRecs = snsEvt.Records;
@@ -119,6 +129,41 @@ proxyResult.headers["example"] = b;
proxyResult.headers["example"] = num;
str = proxyResult.body;
/* API Gateway CustomAuthorizer AuthResponse */
authResponseContext = {
stringKey: str,
numberKey: num,
booleanKey: b
};
statement = {
Action: str,
Effect: str,
Resource: str
};
statement = {
Action: [str, str],
Effect: str,
Resource: [str, str]
};
policyDocument = {
Version: str,
Statement: [statement]
};
authResponse = {
principalId: str,
policyDocument: policyDocument,
context: authResponseContext
};
authResponse = {
principalId: str,
policyDocument: policyDocument
};
/* Context */
b = context.callbackWaitsForEmptyEventLoop;
str = context.functionName;
@@ -170,6 +215,14 @@ function proxyCallback(cb: AWSLambda.ProxyCallback) {
cb(null, proxyResult);
}
/* CustomAuthorizerCallback */
function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) {
cb();
cb(null);
cb(error);
cb(null, authResponse);
}
/* Compatibility functions */
context.done();
context.done(error);
@@ -183,3 +236,4 @@ context.fail(str);
/* Handler */
let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { };
let CustomAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { };
+46
View File
@@ -39,6 +39,13 @@ interface APIGatewayEvent {
resource: string;
}
// API Gateway CustomAuthorizer "event"
interface CustomAuthorizerEvent {
type: string;
authorizationToken: string;
methodArn: string;
}
// SNS "event"
interface SNSMessageAttribute {
Type: string;
@@ -180,6 +187,43 @@ interface ProxyResult {
body: string;
}
/**
* API Gateway CustomAuthorizer AuthResponse.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
*/
interface AuthResponse {
principalId: string;
policyDocument: PolicyDocument;
context?: AuthResponseContext;
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
*/
interface PolicyDocument {
Version: string;
Statement: [Statement];
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
*/
interface Statement {
Action: string | [string];
Effect: string;
Resource: string | [string];
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
*/
interface AuthResponseContext {
[name: string]: string | number | boolean;
}
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -190,6 +234,7 @@ interface ProxyResult {
*/
export type Handler = (event: any, context: Context, callback?: Callback) => void;
export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?: ProxyCallback) => void;
export type CustomAuthorizerHandler = (event: CustomAuthorizerEvent, context: Context, callback?: CustomAuthorizerCallback) => void;
/**
* Optional callback parameter.
@@ -200,5 +245,6 @@ export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?:
*/
export type Callback = (error?: Error, result?: any) => void;
export type ProxyCallback = (error?: Error, result?: ProxyResult) => void;
export type CustomAuthorizerCallback = (error?: Error, result?: AuthResponse) => void;
export as namespace AWSLambda;
+36 -3
View File
@@ -1,8 +1,41 @@
import Boom = require('boom');
var bo = Boom.wrap(new Error('test'), 400, 'some message');
var a: string = bo.output.headers['some header'];
Boom.create(500, 'Internal server error', { timestamp: Date.now() });
Boom.wrap(new Error('test'), 400);
Boom.badRequest('Invalid cookies');
Boom.badRequest('message', {some: 'data'});
Boom.unauthorized('message', <string | string[]> 'scheme', {some: 'data'});
Boom.unauthorized(null, <string | string[]> 'scheme', 'data');
Boom.paymentRequired('message', {some: 'data'});
Boom.forbidden('message', {some: 'data'});
Boom.notFound('message', {some: 'data'});
Boom.methodNotAllowed('message', {some: 'data'});
Boom.notAcceptable('message', {some: 'data'});
Boom.proxyAuthRequired('message', {some: 'data'});
Boom.clientTimeout('message', {some: 'data'});
Boom.conflict('message', {some: 'data'});
Boom.resourceGone('message', {some: 'data'});
Boom.lengthRequired('message', {some: 'data'});
Boom.preconditionFailed('message', {some: 'data'});
Boom.entityTooLarge('message', {some: 'data'});
Boom.uriTooLong('message', {some: 'data'});
Boom.unsupportedMediaType('message', {some: 'data'});
Boom.rangeNotSatisfiable('message', {some: 'data'});
Boom.expectationFailed('message', {some: 'data'});
Boom.teapot('message', {some: 'data'});
Boom.badData('message', {some: 'data'});
Boom.locked('message', {some: 'data'});
Boom.preconditionRequired('message', {some: 'data'});
Boom.tooManyRequests('message', {some: 'data'});
Boom.illegal('message', {some: 'data'});
Boom.badImplementation('message', {some: 'data'});
Boom.notImplemented('message', {some: 'data'});
Boom.badGateway('message', {some: 'data'});
Boom.serverUnavailable('message', {some: 'data'});
Boom.gatewayTimeout('message', {some: 'data'});
Boom.unauthorized() as Error;
+251 -10
View File
@@ -1,6 +1,6 @@
// Type definitions for boom
// Type definitions for boom 4.3
// Project: http://github.com/hapijs/boom
// Definitions by: Igor Rogatty <http://github.com/rogatty>
// Definitions by: Igor Rogatty <http://github.com/rogatty>, AJP <http://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
@@ -9,53 +9,294 @@ export = Boom;
declare namespace Boom {
export interface BoomError {
data: any;
reformat: () => void;
/**
* boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties:
* @see {@link https://github.com/hapijs/boom#boom}
*/
export interface BoomError extends Error {
/** isBoom - if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** isServer - convenience bool indicating status code >= 500. */
isServer: boolean;
/** message - the error message. */
message: string;
/** output - the formatted response. Can be directly manipulated after object construction to return a custom error response. Allowed root keys: */
output: Output;
name: string;
/** reformat() - rebuilds error.output using the other object properties. */
reformat: () => string;
}
export interface Output {
/** statusCode - the HTTP status code (typically 4xx or 5xx). */
statusCode: number;
headers: any;
payload: any;
/** headers - an object containing any HTTP headers where each key is a header name and value is the header content. (Limited value type to string https://github.com/hapijs/boom/issues/151 ) */
headers: {[index: string]: string};
/** payload - the formatted object used as the response payload (stringified). Can be directly manipulated but any changes will be lost if reformat() is called. Any content allowed and by default includes the following content: */
payload: {
/** statusCode - the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
/** error - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */
error: string;
/** message - the error message derived from error.message. */
message: string;
}
}
/**
* Decorates an error with the boom properties
* @param error the error object to wrap. If error is already a boom object, returns back the same object.
* @param statusCode optional HTTP status code. Defaults to 500.
* @param message optional message string. If the error already has a message, it adds the message as a prefix. Defaults to no message.
* @see {@link https://github.com/hapijs/boom#wraperror-statuscode-message}
*/
export function wrap(error: Error, statusCode?: number, message?: string): BoomError;
/**
* Generates an Error object with the boom decorations
* @param statusCode an HTTP error code number. Must be greater or equal 400.
* @param message optional message string.
* @param data additional error data set to error.data property.
* @see {@link https://github.com/hapijs/boom#createstatuscode-message-data}
*/
export function create(statusCode: number, message?: string, data?: any): BoomError;
// 4xx
/**
* Returns a 400 Bad Request error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadrequestmessage-data}
*/
export function badRequest(message?: string, data?: any): BoomError;
export function unauthorized(message?: string, scheme?: any, attributes?: any): BoomError;
/**
* Returns a 401 Unauthorized error
* @param message optional message.
* @param scheme can be one of the following:
* * an authentication scheme name
* * an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header.
* @param attributes an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when scheme is a string, otherwise it is ignored. Every key/value pair will be included in the 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the attributes key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. null and undefined will be replaced with an empty string. If attributes is set, message will be used as the 'error' segment of the 'WWW-Authenticate' header. If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object.
* @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes}
*/
export function unauthorized(message?: string, scheme?: string | string[], attributes?: {[index: string]: string}): BoomError;
export function unauthorized(message?: null, scheme?: string | string[], attributes?: string): BoomError;
/**
* Returns a 402 Payment Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompaymentrequiredmessage-data}
*/
export function paymentRequired(message?: string, data?: any): BoomError;
/**
* Returns a 403 Forbidden error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomforbiddenmessage-data}
*/
export function forbidden(message?: string, data?: any): BoomError;
/**
* Returns a 404 Not Found error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotfoundmessage-data}
*/
export function notFound(message?: string, data?: any): BoomError;
export function methodNotAllowed(message?: string, data?: any): BoomError;
/**
* Returns a 405 Method Not Allowed error
* @param message optional message.
* @param data optional additional error data.
* @param allow optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header.
* @see {@link https://github.com/hapijs/boom#boommethodnotallowedmessage-data-allow}
*/
export function methodNotAllowed(message?: string, data?: any, allow?: string | string[]): BoomError;
/**
* Returns a 406 Not Acceptable error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotacceptablemessage-data}
*/
export function notAcceptable(message?: string, data?: any): BoomError;
/**
* Returns a 407 Proxy Authentication Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomproxyauthrequiredmessage-data}
*/
export function proxyAuthRequired(message?: string, data?: any): BoomError;
/**
* Returns a 408 Request Time-out error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomclienttimeoutmessage-data}
*/
export function clientTimeout(message?: string, data?: any): BoomError;
/**
* Returns a 409 Conflict error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomconflictmessage-data}
*/
export function conflict(message?: string, data?: any): BoomError;
/**
* Returns a 410 Gone error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomresourcegonemessage-data}
*/
export function resourceGone(message?: string, data?: any): BoomError;
/**
* Returns a 411 Length Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomlengthrequiredmessage-data}
*/
export function lengthRequired(message?: string, data?: any): BoomError;
/**
* Returns a 412 Precondition Failed error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompreconditionfailedmessage-data}
*/
export function preconditionFailed(message?: string, data?: any): BoomError;
/**
* Returns a 413 Request Entity Too Large error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomentitytoolargemessage-data}
*/
export function entityTooLarge(message?: string, data?: any): BoomError;
/**
* Returns a 414 Request-URI Too Large error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomuritoolongmessage-data}
*/
export function uriTooLong(message?: string, data?: any): BoomError;
/**
* Returns a 415 Unsupported Media Type error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomunsupportedmediatypemessage-data}
*/
export function unsupportedMediaType(message?: string, data?: any): BoomError;
/**
* Returns a 416 Requested Range Not Satisfiable error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomrangenotsatisfiablemessage-data}
*/
export function rangeNotSatisfiable(message?: string, data?: any): BoomError;
/**
* Returns a 417 Expectation Failed error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomexpectationfailedmessage-data}
*/
export function expectationFailed(message?: string, data?: any): BoomError;
/**
* Returns a 418 I'm a Teapot error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomteapotmessage-data}
*/
export function teapot(message?: string, data?: any): BoomError;
/**
* Returns a 422 Unprocessable Entity error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombaddatamessage-data}
*/
export function badData(message?: string, data?: any): BoomError;
/**
* Returns a 423 Locked error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomlockedmessage-data}
*/
export function locked(message?: string, data?: any): BoomError;
/**
* Returns a 428 Precondition Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompreconditionrequiredmessage-data}
*/
export function preconditionRequired(message?: string, data?: any): BoomError;
/**
* Returns a 429 Too Many Requests error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomtoomanyrequestsmessage-data}
*/
export function tooManyRequests(message?: string, data?: any): BoomError;
/**
* Returns a 451 Unavailable For Legal Reasons error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomillegalmessage-data}
*/
export function illegal(message?: string, data?: any): BoomError;
// 5xx
/**
* Returns a 500 Internal Server Error error
* Only 500 errors will hide your message from the end user. Your message is recorded in the server log.
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal}
*/
export function badImplementation(message?: string, data?: any): BoomError;
/**
* Returns a 501 Not Implemented error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotimplementedmessage-data}
*/
export function notImplemented(message?: string, data?: any): BoomError;
/**
* Returns a 502 Bad Gateway error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadgatewaymessage-data}
*/
export function badGateway(message?: string, data?: any): BoomError;
/**
* Returns a 503 Service Unavailable error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomserverunavailablemessage-data}
*/
export function serverUnavailable(message?: string, data?: any): BoomError;
/**
* Returns a 504 Gateway Time-out error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomgatewaytimeoutmessage-data}
*/
export function gatewayTimeout(message?: string, data?: any): BoomError;
}
+8
View File
@@ -0,0 +1,8 @@
import Boom = require('boom');
Boom.create(500, 'Internal server error', { timestamp: Date.now() });
Boom.wrap(new Error('test'), 400);
Boom.badRequest('Invalid cookies');
Boom.unauthorized() as Error;
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for boom 3.2
// Project: http://github.com/hapijs/boom
// Definitions by: Igor Rogatty <http://github.com/rogatty>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = Boom;
declare namespace Boom {
export interface BoomError {
data: any;
reformat: () => void;
isBoom: boolean;
isServer: boolean;
message: string;
output: Output;
name: string;
}
export interface Output {
statusCode: number;
headers: any;
payload: any;
}
export function wrap(error: Error, statusCode?: number, message?: string): BoomError;
export function create(statusCode: number, message?: string, data?: any): BoomError;
// 4xx
export function badRequest(message?: string, data?: any): BoomError;
export function unauthorized(message?: string, scheme?: any, attributes?: any): BoomError;
export function forbidden(message?: string, data?: any): BoomError;
export function notFound(message?: string, data?: any): BoomError;
export function methodNotAllowed(message?: string, data?: any): BoomError;
export function notAcceptable(message?: string, data?: any): BoomError;
export function proxyAuthRequired(message?: string, data?: any): BoomError;
export function clientTimeout(message?: string, data?: any): BoomError;
export function conflict(message?: string, data?: any): BoomError;
export function resourceGone(message?: string, data?: any): BoomError;
export function lengthRequired(message?: string, data?: any): BoomError;
export function preconditionFailed(message?: string, data?: any): BoomError;
export function entityTooLarge(message?: string, data?: any): BoomError;
export function uriTooLong(message?: string, data?: any): BoomError;
export function unsupportedMediaType(message?: string, data?: any): BoomError;
export function rangeNotSatisfiable(message?: string, data?: any): BoomError;
export function expectationFailed(message?: string, data?: any): BoomError;
export function badData(message?: string, data?: any): BoomError;
export function locked(message?: string, data?: any): BoomError;
export function preconditionRequired(message?: string, data?: any): BoomError;
export function tooManyRequests(message?: string, data?: any): BoomError;
export function illegal(message?: string, data?: any): BoomError;
// 5xx
export function badImplementation(message?: string, data?: any): BoomError;
export function notImplemented(message?: string, data?: any): BoomError;
export function badGateway(message?: string, data?: any): BoomError;
export function serverUnavailable(message?: string, data?: any): BoomError;
export function gatewayTimeout(message?: string, data?: any): BoomError;
}
@@ -7,16 +7,21 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"baseUrl": "../../",
"typeRoots": [
"../"
"../../"
],
"types": [],
"paths": {
"boom": [
"boom/v3"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"fast-simplex-noise-tests.ts"
"boom-tests.ts"
]
}
+153 -16
View File
@@ -1,6 +1,7 @@
// Type definitions for bson 1.0
// Type definitions for bson 1.0.4
// Project: https://github.com/mongodb/js-bson
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi/>
// Federico Caselli <https://github.com/CaselIT>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
@@ -37,6 +38,17 @@ export class Binary {
static SUBTYPE_USER_DEFINED: number;
constructor(buffer: Buffer, subType?: number);
/** The length of the binary. */
length(): number;
/** Updates this binary with byte_value */
put(byte_value: number | string): void;
/** Reads length bytes starting at position. */
read(position: number, length: number): Buffer;
/** Returns the value of this binary as a string. */
value(): string;
/** Writes a buffer or string to the binary */
write(buffer: Buffer | string, offset: number): void;
}
export class Code {
constructor(code: string | Function, scope?: any);
@@ -45,15 +57,63 @@ export class DBRef {
constructor(namespace: string, oid: ObjectID, db?: string);
}
export class Double {
constructor (value: number);
constructor(value: number);
valueOf(): number;
}
export class Long {
static MAX_VALUE: Long;
static MIN_VALUE: Long;
static NEG_ONE: Long;
static ONE: Long;
static ZERO: Long;
static fromInt(i: number): Long;
static fromNumber(n: number): Long;
static fromBits(lowBits: number, highBits: number): Long;
static fromString(s: string, opt_radix?: number): Long;
constructor(low: number, high: number);
add(other: Long): Long;
and(other: Long): Long;
compare(other: Long): number;
div(other: Long): Long;
equals(other: Long): boolean;
getHighBits(): number;
getLowBits(): number;
getLowBitsUnsigned(): number;
getNumBitsAbs(): number;
greaterThan(other: Long): number;
greaterThanOrEqual(other: Long): number;
isNegative(): boolean;
isOdd(): boolean;
isZero(): boolean;
lessThan(other: Long): boolean;
lessThanOrEqual(other: Long): boolean;
modulo(other: Long): Long;
multiply(other: Long): Long;
negate(): Long;
not(): Long;
notEquals(other: Long): boolean;
or(other: Long): Long;
shiftLeft(other: number): Long;
shiftRight(other: number): Long;
shiftRightUnsigned(other: number): Long;
subtract(other: Long): Long;
toInt(): number;
toJSON(): string;
toNumber(): number;
toString(radix?: number): string;
xor(other: Long): Long;
}
export class Decimal128 {
static fromString(s: string): Decimal128;
constructor(bytes: Buffer);
toJSON(): string;
toString(): string;
}
export class MaxKey {
constructor();
@@ -61,17 +121,56 @@ export class MaxKey {
export class MinKey {
constructor();
}
export class ObjectId {
static createPk(): ObjectId;
static createFromTime(time: number): ObjectId;
static createFromHexString(hexString: string): ObjectId;
static isValid(id: number | string | ObjectId): boolean;
constructor(id?: number | string | ObjectId);
toHexString(): string;
export class ObjectID {
/**
* Create a new ObjectID instance
* @param {(string|number|ObjectID)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
*/
constructor(id?: string | number | ObjectID);
/** The generation time of this ObjectID instance */
generationTime: number;
/**
* Creates an ObjectID from a hex string representation of an ObjectID.
* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
* @return {ObjectID} return the created ObjectID
*/
static createFromHexString(hexString: string): ObjectID;
/**
* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
* @param {number} time an integer number representing a number of seconds.
* @return {ObjectID} return the created ObjectID
*/
static createFromTime(time: number): ObjectID;
/**
* Checks if a value is a valid bson ObjectID
*
* @return {boolean} return true if the value is a valid bson ObjectID, return false otherwise.
*/
static isValid(id: string | number | ObjectID): boolean;
/**
* Compares the equality of this ObjectID with `otherID`.
* @param {object} otherID ObjectID instance to compare against.
* @return {boolean} the result of comparing two ObjectID's
*/
equals(otherID: ObjectID): boolean;
/**
* Generate a 12 byte id string used in ObjectID's
* @param {number} time optional parameter allowing to pass in a second based timestamp.
* @return {string} return the 12 byte id binary string.
*/
generate(time?: number): string;
/**
* Returns the generation date (accurate up to the second) that this ID was generated.
* @return {date} the generation date
*/
getTimestamp(): Date;
/**
* Return the ObjectID id as a 24 byte hex string representation
* @return {string} return the 24 byte hex string representation.
*/
toHexString(): string;
}
export type ObjectID = ObjectId;
export { ObjectID as ObjectId };
export class BSONRegExp {
constructor(pattern: string, options: string);
}
@@ -79,10 +178,48 @@ export class Symbol {
constructor(value: string);
}
export class Timestamp {
static fromInt(i: number): Timestamp;
static fromNumber(n: number): Timestamp;
static fromBits(lowBits: number, highBits: number): Timestamp;
static fromString(s: string, opt_radix?: number): Timestamp;
constructor(low: number, high: number);
static MAX_VALUE: Timestamp;
static MIN_VALUE: Timestamp;
static NEG_ONE: Timestamp;
static ONE: Timestamp;
static ZERO: Timestamp;
static fromBits(lowBits: number, highBits: number): Timestamp;
static fromInt(value: number): Timestamp;
static fromNumber(value: number): Timestamp;
static fromString(str: string, radix?: number): Timestamp;
add(other: Timestamp): Timestamp;
and(other: Timestamp): Timestamp;
compare(other: Timestamp): number;
div(other: Timestamp): Timestamp;
equals(other: Timestamp): boolean;
getHighBits(): number;
getLowBits(): number;
getLowBitsUnsigned(): number;
getNumBitsAbs(): number;
greaterThan(other: Timestamp): number;
greaterThanOrEqual(other: Timestamp): number;
isNegative(): boolean;
isOdd(): boolean;
isZero(): boolean;
lessThan(other: Timestamp): boolean;
lessThanOrEqual(other: Timestamp): boolean;
modulo(other: Timestamp): Timestamp;
multiply(other: Timestamp): Timestamp;
negate(): Timestamp;
not(): Timestamp;
notEquals(other: Timestamp): boolean;
or(other: Timestamp): Timestamp;
shiftLeft(other: number): Timestamp;
shiftRight(other: number): Timestamp;
shiftRightUnsigned(other: number): Timestamp;
subtract(other: Timestamp): Timestamp;
toInt(): number;
toJSON(): string;
toNumber(): number;
toString(radix?: number): string;
xor(other: Timestamp): Timestamp;
}
-27
View File
@@ -1,27 +0,0 @@
Bugsnag.apiKey = "API-KEY";
Bugsnag.releaseStage = "beta";
Bugsnag.appVersion = "2.4.56";
Bugsnag.user = <BugsnagUser>{
name: "Robert K. User",
email: "robbie@example.com"
};
Bugsnag.metaData = {
account: {
name: "Acme Co",
plan: "hacker"
}
}
Bugsnag.notifyException(new Error("Something broke"));
Bugsnag.notify("Serious Problem", "We are out of cookies");
Bugsnag.notify("Serious Problem",
"We are out of cookies",
{ remaining_snacks: ["carrots", "biscuits"] },
"error");
-90
View File
@@ -1,90 +0,0 @@
// Type definitions for Bugsnag v2.5.0
// Project: https://github.com/bugsnag/bugsnag-js
// Definitions by: Delisa Mason <https://github.com/kattrali>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface BugsnagUser {
id?: string,
name?: string,
email?: string
}
interface BugsnagStatic {
/** Bugsnag project API key */
apiKey: string;
/** The client application version */
appVersion: string;
/** true if Bugsnag should be automatically notified of errors which are
* sent to `window.onerror`
*/
autoNotify: boolean;
/** Callback run before error reports are sent to Bugsnag.
* Payload and metadata information can be altered or removed altogether.
* To cancel sending the report, return false from this function.
*/
beforeNotify: (payload: any, metaData: any) => boolean;
/** The pathname of the current page, not including the fragment identifier
* nor search parameters
*/
context: string;
/** Disables console-based logging. Defaults to false. */
disableLog: boolean;
/** The address used to send errors to Bugsnag. The default is
* `https://notify.bugsnag.com/js`
*/
endpoint: string;
/** Enables sending inline scripts on the page to Bugsnag to assist with
* debugging. Defaults to true
*/
inlineScript: boolean;
/** The maximum depth to parse the error stack */
maxDepth: number;
/** Additional metadata to send to Bugsnag with every error. */
metaData: any;
/** The method used for the notify request. The default is a temporary
* JavaScript image object, however Chrome apps/extensions and other
* applications where XHR is needed can use `xhr` instead.
*/
notifyHandler: string;
/** The releases stages during which Bugsnag will be notified of errors. */
notifyReleaseStages: string[];
/** The recorded root of the project. The default is the current host
* address (protocol and domain).
*/
projectRoot: string;
/** Current phase of the application release process. The default is
* `production`
*/
releaseStage: string;
/** Information about the current user which is sent to Bugsnag with
* exception reports
*/
user: BugsnagUser;
/** Continue catching exceptions after the page error limit is reached.
* Useful for long-running single-page apps
*/
refresh(): void;
/** Remove Bugsnag from the window object and restore the previous
* binding
*/
noConflict(): BugsnagStatic;
/** Send caught exceptions to Bugsnag. Valid severity values are `info`,
* `warning`, and `error`, in order of increasing severity.
*/
notifyException(exception: Error, name?: string, metaData?: any,
severity?: string): void;
/** Send custom errors to Bugsnag */
notify(name: string, message: string, metaData?: any,
severity?: string): void;
}
declare var Bugsnag: BugsnagStatic;
declare module "Bugsnag" {
export = Bugsnag;
}
-22
View File
@@ -1,22 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bugsnag-tests.ts"
]
}
+499 -889
View File
File diff suppressed because it is too large Load Diff
+930 -95
View File
File diff suppressed because it is too large Load Diff
-61
View File
@@ -1,61 +0,0 @@
import * as cheapRuler from 'cheap-ruler'
// -- Fixtures --
const bbox = [30.5, 50.5, 31, 51]
const point1 = [30.5, 50.5]
const point2 = [30.51, 50.49]
const unit = 'miles'
const lineString = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-77.031669, 38.878605],
[-77.029609, 38.881946],
[-77.020339, 38.884084],
[-77.025661, 38.885821],
[-77.021884, 38.889563],
[-77.019824, 38.892368]
]
}
}
const line = lineString.geometry.coordinates
const polygon = [[
[-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534],
[-66.929, 50.458], [-67.031, 50.458]
]]
const points = [
[-67.031, 50.458], [-67.031, 50.534],
[-66.929, 50.534], [-66.929, 50.458]
]
// -- Test initiators --
cheapRuler(35.05)
cheapRuler(35.05, 'miles')
cheapRuler(35.05, unit)
cheapRuler.fromTile(1567, 12)
cheapRuler.fromTile(1567, 12, 'miles')
cheapRuler.fromTile(1567, 12, unit)
// -- Test units --
cheapRuler.units
cheapRuler.units.miles
cheapRuler.units.kilometers
50 * cheapRuler.units.yards / cheapRuler.units.meters
// -- Test cheapRuler --
const ruler = cheapRuler(35.05)
ruler.distance(point1, point2)
ruler.bearing(point1, point2)
ruler.destination(point1, 0.1, 90)
ruler.lineDistance(points)
ruler.area(polygon)
ruler.along(line, 2.5)
ruler.pointOnLine(line, point1).point
ruler.lineSlice(point1, point2, line)
ruler.lineSliceAlong(10, 20, line)
ruler.bufferPoint(point1, 0.01)
ruler.bufferBBox(bbox, 0.2)
ruler.insideBBox(point1, bbox)
-216
View File
@@ -1,216 +0,0 @@
// Type definitions for cheap-ruler 2.4.1
// Project: https://github.com/mapbox/cheap-ruler
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "cheap-ruler" {
type BBox = [number, number, number, number] | number[]
type Point = [number, number] | number[]
type Line = Array<Point>
type Points = Array<Point>
type Polygon = Array<Array<Point>>
interface TemplateUnits {
kilometers: number
miles: number
nauticalmiles: number
meters: number
metres: number
yards: number
feet: number
inches: number
}
interface InterfacePointOnLine {
point: Point
index: number
t: number
}
class CheapRuler {
/**
* Given two points of the form [longitude, latitude], returns the distance.
*
* @param {Point} a point [longitude, latitude]
* @param {Point} b point [longitude, latitude]
* @returns {number} distance
* @example
* var distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);
* //=distance
*/
distance(a: Point, b: Point): number;
/**
* Returns the bearing between two points in angles.
*
* @param {Point} a point [longitude, latitude]
* @param {Point} b point [longitude, latitude]
* @returns {number} bearing
* @example
* var bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]);
* //=bearing
*/
bearing(a: Point, b: Point): number;
/**
* Returns a new point given distance and bearing from the starting point.
*
* @param {Point} p point [longitude, latitude]
* @param {number} dist distance
* @param {number} bearing
* @returns {Point} point [longitude, latitude]
* @example
* var point = ruler.destination([30.5, 50.5], 0.1, 90);
* //=point
*/
destination(p: Point, dist: number, bearing: number): Point;
/**
* Given a line (an array of points), returns the total line distance.
*
* @param {Points} points [longitude, latitude]
* @returns {number} total line distance
* @example
* var length = ruler.lineDistance([
* [-67.031, 50.458], [-67.031, 50.534],
* [-66.929, 50.534], [-66.929, 50.458]
* ]);
* //=length
*/
lineDistance(points: Points): number;
/**
* Given a polygon (an array of rings, where each ring is an array of points), returns the area.
*
* @param {Polygon} polygon
* @returns {number} area value in the specified units (square kilometers by default)
* @example
* var area = ruler.area([[
* [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534],
* [-66.929, 50.458], [-67.031, 50.458]
* ]]);
* //=area
*/
area(polygon: Polygon): number;
/**
* Returns the point at a specified distance along the line.
*
* @param {Line} line
* @param {number} dist distance
* @returns {Point} point [longitude, latitude]
* @example
* var point = ruler.along(line, 2.5);
* //=point
*/
along(line: Line, dist: number): Point
/**
* Returns an object of the form {point, index} where point is closest point on the line from the given point, and index is the start index of the segment with the closest point.
*
* @pointOnLine
* @param {Line} line
* @param {Point} p point [longitude, latitude]
* @returns {Object} {point, index}
* @example
* var point = ruler.pointOnLine(line, [-67.04, 50.5]).point;
* //=point
*/
pointOnLine(line: Line, p: Point): InterfacePointOnLine
/**
* Returns a part of the given line between the start and the stop points (or their closest points on the line).
*
* @param {Point} start point [longitude, latitude]
* @param {Point} stop point [longitude, latitude]
* @param {Line} line
* @returns {Line} line part of a line
* @example
* var line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1);
* //=line2
*/
lineSlice(start: Point, stop: Point, line: Line): Line
/**
* Returns a part of the given line between the start and the stop points indicated by distance along the line.
*
* @param {number} start distance
* @param {number} stop distance
* @param {Line} line
* @returns {Line} line part of a line
* @example
* var line2 = ruler.lineSliceAlong(10, 20, line1);
* //=line2
*/
lineSliceAlong(start: number, stop: number, line: Line): Line
/**
* Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance.
*
* @param {Point} p point [longitude, latitude]
* @param {number} buffer
* @returns {BBox} box object ([w, s, e, n])
* @example
* var bbox = ruler.bufferPoint([30.5, 50.5], 0.01);
* //=bbox
*/
bufferPoint(p: Point, buffer: number): BBox
/**
* Given a bounding box, returns the box buffered by a given distance.
*
* @param {BBox} box object ([w, s, e, n])
* @param {number} buffer
* @returns {BBox} box object ([w, s, e, n])
* @example
* var bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2);
* //=bbox
*/
bufferBBox(bbox: BBox, buffer: number): BBox
/**
* Returns true if the given point is inside in the given bounding box, otherwise false.
*
* @param {Point} p point [longitude, latitude]
* @param {Point} box object ([w, s, e, n])
* @returns {boolean}
* @example
* var inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]);
* //=inside
*/
insideBBox(p: Point, bbox: BBox): boolean
}
/**
* A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale.
*
* @param {number} lat latitude
* @param {string} [units='kilometers']
* @returns {CheapRuler}
* @example
* var ruler = cheapRuler(35.05, 'miles');
* //=ruler
*/
function cheapRuler(lat: number, units?: string): CheapRuler;
namespace cheapRuler {
/**
* Multipliers for converting between units.
*
* @example
* // convert 50 meters to yards
* 50 * cheapRuler.units.yards / cheapRuler.units.meters;
*/
const units: TemplateUnits
/**
* Creates a ruler object from tile coordinates (y and z). Convenient in tile-reduce scripts.
*
* @param {number} y
* @param {number} z
* @param {string} [units='kilometers']
* @returns {CheapRuler}
* @example
* var ruler = cheapRuler.fromTile(1567, 12);
* //=ruler
*/
function fromTile(y: number, z: number, units?: string): CheapRuler;
}
export = cheapRuler
}
+11 -4
View File
@@ -4269,6 +4269,12 @@ declare namespace chrome.notifications {
appIconMaskUrl?: string;
/** Optional. A URL to the image thumbnail for image-type notifications. URLs have the same restrictions as iconUrl. */
imageUrl?: string;
/**
* Indicates that the notification should remain visible on screen until the user activates or dismisses the notification.
* This defaults to false.
* @since Chrome 50
*/
requireInteraction?: boolean;
}
interface NotificationClosedEvent extends chrome.events.Event<(notificationId: string, byUser: boolean) => void> {}
@@ -7100,12 +7106,13 @@ declare namespace chrome.webNavigation {
transitionQualifiers: string[];
}
interface WebNavigationRequestFilter extends chrome.webRequest.RequestFilter {
/** fulfills the webRequest.RequestFilter interface even though it is under web navigation **/
interface WebNavigationEventFilter {
/** Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event. */
url: chrome.events.UrlFilter[];
}
interface WebNavigationEvent<T extends WebNavigationCallbackDetails> extends chrome.events.Event<(details: T) => void> {
addListener(callback: (details: T) => void, filters?: WebNavigationRequestFilter): void;
addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void;
}
interface WebNavigationFramedEvent extends WebNavigationEvent<WebNavigationFramedCallbackDetails> {}
@@ -7215,7 +7222,7 @@ declare namespace chrome.webRequest {
*/
types?: string[];
/** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */
urls: string[] | RegExp[] | "<all_urls>";
urls: string[];
/** Optional. */
windowId?: number;
+5 -13
View File
@@ -171,7 +171,7 @@ function catBlock () {
["blocking"]);
}
// webNavigation.onBeforeNavigate.addListener example similar api to onBeforeRequest but without extra spec
// webNavigation.onBeforeNavigate.addListener example
function beforeRedditNavigation() {
chrome.webNavigation.onBeforeNavigate.addListener(function (requestDetails) {
console.log("URL we want to redirect to: " + requestDetails.url);
@@ -180,18 +180,10 @@ function beforeRedditNavigation() {
return;
}
let url = new URL(requestDetails.url);
let splitUrl = url.hostname.split('.');
//` Note: Does not cover the XX.co.uk type edge case
let host = (splitUrl[(splitUrl.length -1) - 1]);
if (host === null) {
return;
} else if (host === "reddit") {
alert("Were you trying to go on reddit, during working hours? :(")
return;
}
},{urls: ["http://*/*"], types: ["image"]});
alert("Were you trying to go on reddit, during working hours? :(")
},{url: [
{hostSuffix: ".reddit.com"}
]});
}
// for chrome.tabs.InjectDetails.frameId
+1
View File
@@ -66,6 +66,7 @@ declare namespace Color {
keyword(): string | undefined;
hex(color: string): Color;
hex(): string;
rgb(): Color;
rgbNumber(): number;
luminosity(): number;
contrast(color: Color): number;
File diff suppressed because one or more lines are too long
+58830 -58743
View File
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -1,10 +1,11 @@
// Type definitions for Enzyme 2.7
// Type definitions for Enzyme 2.7.1
// Project: https://github.com/airbnb/enzyme
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>
// Cap3 <http://www.cap3.de>
// Ivo Stratev <https://github.com/NoHomey>
// Tom Crockett <https://github.com/pelotom>
// jwbay <https://githb.com/jwbay>
// jwbay <https://github.com/jwbay>
// huhuanming <https://github.com/huhuanming>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
@@ -340,7 +341,7 @@ interface CommonWrapper<P, S> {
}
export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
shallow(): ShallowWrapper<P, S>;
shallow(options?: ShallowRendererProps): ShallowWrapper<P, S>;
unmount(): ShallowWrapper<any, any>;
/**
+7 -7
View File
@@ -123,7 +123,7 @@ expression = expressionStatement.expression;
var ifStatement: ESTree.IfStatement;
expression = ifStatement.test;
statement = ifStatement.consequent;
var statementOrNull: ESTree.Statement | undefined = ifStatement.alternate;
var statementOrNull: ESTree.Statement | null | undefined = ifStatement.alternate;
// LabeledStatement
var labeledStatement: ESTree.LabeledStatement;
@@ -141,18 +141,18 @@ switchCase = switchStatement.cases[0];
// ReturnStatement
var returnStatement: ESTree.ReturnStatement;
var expressionMaybe: ESTree.Expression | undefined = returnStatement.argument;
var expressionMaybe: ESTree.Expression | null | undefined = returnStatement.argument;
// TryStatement
var tryStatement: ESTree.TryStatement;
blockStatement = tryStatement.block;
var catchClauseMaybe: ESTree.CatchClause | undefined = tryStatement.handler;
var blockStatementMaybe: ESTree.BlockStatement | undefined = tryStatement.finalizer;
var catchClauseMaybe: ESTree.CatchClause | null | undefined = tryStatement.handler;
var blockStatementMaybe: ESTree.BlockStatement | null | undefined = tryStatement.finalizer;
// ForStatement
var forStatement: ESTree.ForStatement;
var variableDeclaratorOrExpressionMaybe: typeof variableDeclaratorOrExpression | undefined = forStatement.init;
var expressionMaybe: ESTree.Expression | undefined = forStatement.update;
var variableDeclaratorOrExpressionMaybe: typeof variableDeclaratorOrExpression | null | undefined = forStatement.init;
var expressionMaybe: ESTree.Expression | null | undefined = forStatement.update;
// ForInStatement
var forInStatement: ESTree.ForInStatement;
@@ -176,7 +176,7 @@ string = property.kind;
// FunctionExpression
var functionExpression: ESTree.FunctionExpression;
var identifierMaybe: ESTree.Identifier | undefined = functionExpression.id;
var identifierMaybe: ESTree.Identifier | null | undefined = functionExpression.id;
pattern = functionExpression.params[0];
pattern = assignmentPattern.left;
expression = assignmentPattern.right;
+10 -10
View File
@@ -26,20 +26,20 @@ declare namespace ESTree {
interface ClassImplements extends Node {
id: Identifier;
typeParameters?: TypeParameterInstantiation;
typeParameters?: TypeParameterInstantiation | null;
}
interface ClassProperty {
key: Expression;
value?: Expression;
typeAnnotation?: TypeAnnotation;
value?: Expression | null;
typeAnnotation?: TypeAnnotation | null;
computed: boolean;
static: boolean;
}
interface DeclareClass extends FlowDeclaration {
id: Identifier;
typeParameters?: TypeParameterDeclaration;
typeParameters?: TypeParameterDeclaration | null;
body: ObjectTypeAnnotation;
extends: Array<InterfaceExtends>;
}
@@ -60,8 +60,8 @@ declare namespace ESTree {
interface FunctionTypeAnnotation extends FlowTypeAnnotation {
params: Array<FunctionTypeParam>;
returnType: FlowTypeAnnotation;
rest?: FunctionTypeParam;
typeParameters?: TypeParameterDeclaration;
rest?: FunctionTypeParam | null;
typeParameters?: TypeParameterDeclaration | null;
}
interface FunctionTypeParam {
@@ -72,17 +72,17 @@ declare namespace ESTree {
interface GenericTypeAnnotation extends FlowTypeAnnotation {
id: Identifier | QualifiedTypeIdentifier;
typeParameters?: TypeParameterInstantiation;
typeParameters?: TypeParameterInstantiation | null;
}
interface InterfaceExtends extends Node {
id: Identifier | QualifiedTypeIdentifier;
typeParameters?: TypeParameterInstantiation;
typeParameters?: TypeParameterInstantiation | null;
}
interface InterfaceDeclaration extends FlowDeclaration {
id: Identifier;
typeParameters?: TypeParameterDeclaration;
typeParameters?: TypeParameterDeclaration | null;
extends: Array<InterfaceExtends>;
body: ObjectTypeAnnotation;
}
@@ -115,7 +115,7 @@ declare namespace ESTree {
interface TypeAlias extends FlowDeclaration {
id: Identifier;
typeParameters?: TypeParameterDeclaration;
typeParameters?: TypeParameterDeclaration | null;
right: FlowTypeAnnotation;
}
+19 -19
View File
@@ -28,7 +28,7 @@ interface BaseNode {
leadingComments?: Array<Comment>;
trailingComments?: Array<Comment>;
loc?: SourceLocation;
loc?: SourceLocation | null;
range?: [number, number];
}
export type Node =
@@ -42,7 +42,7 @@ export interface Comment {
}
interface SourceLocation {
source?: string;
source?: string | null;
start: Position;
end: Position;
}
@@ -100,7 +100,7 @@ export interface IfStatement extends BaseStatement {
type: "IfStatement";
test: Expression;
consequent: Statement;
alternate?: Statement;
alternate?: Statement | null;
}
export interface LabeledStatement extends BaseStatement {
@@ -111,12 +111,12 @@ export interface LabeledStatement extends BaseStatement {
export interface BreakStatement extends BaseStatement {
type: "BreakStatement";
label?: Identifier;
label?: Identifier | null;
}
export interface ContinueStatement extends BaseStatement {
type: "ContinueStatement";
label?: Identifier;
label?: Identifier | null;
}
export interface WithStatement extends BaseStatement {
@@ -133,7 +133,7 @@ export interface SwitchStatement extends BaseStatement {
export interface ReturnStatement extends BaseStatement {
type: "ReturnStatement";
argument?: Expression;
argument?: Expression | null;
}
export interface ThrowStatement extends BaseStatement {
@@ -144,8 +144,8 @@ export interface ThrowStatement extends BaseStatement {
export interface TryStatement extends BaseStatement {
type: "TryStatement";
block: BlockStatement;
handler?: CatchClause;
finalizer?: BlockStatement;
handler?: CatchClause | null;
finalizer?: BlockStatement | null;
}
export interface WhileStatement extends BaseStatement {
@@ -162,9 +162,9 @@ export interface DoWhileStatement extends BaseStatement {
export interface ForStatement extends BaseStatement {
type: "ForStatement";
init?: VariableDeclaration | Expression;
test?: Expression;
update?: Expression;
init?: VariableDeclaration | Expression | null;
test?: Expression | null;
update?: Expression | null;
body: Statement;
}
@@ -201,7 +201,7 @@ export interface VariableDeclaration extends BaseDeclaration {
export interface VariableDeclarator extends BaseNode {
type: "VariableDeclarator";
id: Pattern;
init?: Expression;
init?: Expression | null;
}
type Expression =
@@ -239,7 +239,7 @@ export interface Property extends BaseNode {
}
export interface FunctionExpression extends BaseFunction, BaseExpression {
id?: Identifier;
id?: Identifier | null;
type: "FunctionExpression";
body: BlockStatement;
}
@@ -319,7 +319,7 @@ interface BasePattern extends BaseNode { }
export interface SwitchCase extends BaseNode {
type: "SwitchCase";
test?: Expression;
test?: Expression | null;
consequent: Array<Statement>;
}
@@ -389,7 +389,7 @@ export interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
export interface YieldExpression extends BaseExpression {
type: "YieldExpression";
argument?: Expression;
argument?: Expression | null;
delegate: boolean;
}
@@ -443,7 +443,7 @@ export interface AssignmentPattern extends BasePattern {
export type Class = ClassDeclaration | ClassExpression;
interface BaseClass extends BaseNode {
superClass?: Expression;
superClass?: Expression | null;
body: ClassBody;
}
@@ -468,7 +468,7 @@ export interface ClassDeclaration extends BaseClass, BaseDeclaration {
export interface ClassExpression extends BaseClass, BaseExpression {
type: "ClassExpression";
id?: Identifier;
id?: Identifier | null;
}
export interface MetaProperty extends BaseExpression {
@@ -510,9 +510,9 @@ export interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
export interface ExportNamedDeclaration extends BaseModuleDeclaration {
type: "ExportNamedDeclaration";
declaration?: Declaration;
declaration?: Declaration | null;
specifiers: Array<ExportSpecifier>;
source?: Literal;
source?: Literal | null;
}
export interface ExportSpecifier extends BaseModuleSpecifier {
@@ -0,0 +1,21 @@
import { Eureka } from 'eureka-js-client';
// example configuration
let client = new Eureka({
// application instance information
instance: {
app: 'jqservice',
hostName: 'localhost',
ipAddr: '127.0.0.1',
port: 8080,
vipAddress: 'jq.test.something.com',
dataCenterInfo: {
name: 'MyOwn',
},
},
eureka: {
// eureka server host / port
host: '192.168.99.100',
port: 32768,
}
});
+75
View File
@@ -0,0 +1,75 @@
// Type definitions for eureka-js-client 4.3.0
// Project: https://github.com/jquatier/eureka-js-client
// Definitions by: Ilko Hoffmann <https://github.com/Schnillz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class Eureka {
constructor(config: EurekaClient.EurekaConfig)
start(): void;
stop(): void;
getInstancesByAppId(appId: string): string[];
getInstancesByVipAddress(vidAddress: string): string [];
}
export namespace EurekaClient {
type InstanceStatus = 'UP' | 'DOWN' | 'STARTING' | 'OUT_OF_SERVICE' | 'UNKNOWN';
type ActionType = 'ADDED' | 'MODIFIED' | 'DELETED';
type DataCenterName = 'Netflix' | 'Amazon' | 'MyOwn';
interface EurekaConfig {
instance: EurekaInstanceConfig;
eureka: EurekaClientConfig;
}
interface EurekaInstanceConfig {
app: string;
hostName: string;
ipAddr: string;
vipAddress: string;
dataCenterInfo: DataCenterInfo;
port?: number;
instanceId?: string;
appGroupName?: string;
sid?: string;
securePort?: PortWrapper;
homePageUrl?: string;
statusPageUrl?: string;
healthCheckUrl?: string;
secureHealthCheckUrl?: string;
secureVipAddress?: string;
countryId?: number;
status?: InstanceStatus;
overriddenstatus?: InstanceStatus;
leaseInfo?: LeaseInfo;
isCoordinatingDiscoveryServer?: boolean;
}
interface EurekaClientConfig {
host: string;
port: number;
heartbeatInterval?: number;
registryFetchInterval?: number;
maxRetries?: number;
requestRetryDelay?: number;
fetchRegistry?: boolean;
filterUpInstances?: boolean;
servicePath?: string;
ssl?: boolean;
useDns?: boolean;
preferSameZone?: boolean;
clusterRefreshInterval?: boolean;
fetchMetadata?: boolean;
registerWithEureka?: boolean;
useLocalMetadata?: boolean;
preferIpAddress?: boolean;
}
interface PortWrapper {
enabled: boolean;
port: number;
}
interface LeaseInfo {
renewalIntervalInSecs: number;
durationInSecs: number;
}
interface DataCenterInfo {
name: DataCenterName;
}
}
@@ -17,6 +17,6 @@
},
"files": [
"index.d.ts",
"cheap-ruler-tests.ts"
"eureka-js-client-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
@@ -1,28 +0,0 @@
import FastSimplexNoise = require('fast-simplex-noise')
var defaultNoiseGen: FastSimplexNoise = new FastSimplexNoise()
var emptyOptionsNoiseGen: FastSimplexNoise = new FastSimplexNoise({})
var noiseGen: FastSimplexNoise = new FastSimplexNoise({
amplitude: 1,
frequency: 0.01,
max: 255,
min: 0,
octaves: 8,
persistence: 0.5,
random: Math.random
})
var values: number[] = []
values.push(noiseGen.cylindrical2D(5, 1, 1))
values.push(noiseGen.cylindrical3D(5, 1, 1, 1))
values.push(noiseGen.in2D(1, 1))
values.push(noiseGen.in3D(1, 1, 1))
values.push(noiseGen.in4D(1, 1, 1, 1))
values.push(noiseGen.raw2D(1, 1))
values.push(noiseGen.raw3D(1, 1, 1))
values.push(noiseGen.raw4D(1, 1, 1, 1))
values.push(noiseGen.spherical2D(5, 1, 1))
values.push(noiseGen.spherical3D(5, 1, 1, 1))
-94
View File
@@ -1,94 +0,0 @@
// Type definitions for FastSimplexNoise v2.1.1
// Project: https://www.npmjs.com/package/fast-simplex-noise
// Definitions by: Tobias Cohen <https://github.com/tobico/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* A JavaScript implementation of the improved, faster Simplex algorithm outlined in Stefan Gustavson's Simplex noise demystified.
*
* Convenience functions have been added as well, in order to avoid needing to scale and handle the raw noise data directly.
*/
declare class FastSimplexNoise {
amplitude: number;
frequency: number;
max: number;
min: number;
octaves: number;
persistence: number;
random: ()=>number;
/**
* Options is an optional object that can contain:
*
* amplitude: float - The base amplitude (default: 1.0)
* frequency: float - The base frequency (default: 1.0)
* max: float - The maximum scaled value to return (effective default: 1.0)
* min: float - The minimum scaled value to return (effective default: -1.0)
* octaves: integer - The number of octaves to sum for noise generation (default: 1)
* persistence: float - The persistence of amplitude per octave (default: 0.5)
* random: function - A function that generates random values between 0 and 1 (default: Math.random)
*/
constructor(options?: {
amplitude?: number;
frequency?: number;
max?: number;
min?: number;
octaves?: number;
persistence?: number;
random?: ()=>number;
});
/**
* Get a noise value between min and max for a point (x,y) on the surface of a cylinder with circumference c.
*/
cylindrical2D(c: number, x: number, y: number): number;
/**
* Get a noise value between min and max for a point (x, y, z) on the surface of a cylinder with circumference c.
*/
cylindrical3D(c: number, x: number, y: number, z: number): number;
/**
* Get a noise value between min and max at the 2D coordinate (x,y) in summed octaves, using amplitude, frequency, and persistence values.
*/
in2D(x: number, y: number): number;
/**
* Get a noise value between min and max at the 3D coordinate (x,y,z) in summed octaves, using amplitude, frequency, and persistence values.
*/
in3D(x: number, y: number, z: number): number;
/**
* Get a noise value between min and max at the 4D coordinate (x,y,z,w) in summed octaves, using amplitude, frequency, and persistence values.
*/
in4D(x: number, y: number, z: number, w: number): number;
/**
* Get a noise value [-1, 1] at the 2D coordinate (x,y).
*/
raw2D(x: number, y: number): number;
/**
* Get a noise value [-1, 1] at the 3D coordinate (x,y,z).
*/
raw3D(x: number, y: number, z: number): number;
/**
* Get a noise value [-1, 1] at the 4D coordinate (x,y,z,w).
*/
raw4D(x: number, y: number, z: number, w: number): number;
/**
* Get a noise value between min and max for a point (x, y) on the surface of a sphere with circumference c.
*/
spherical2D(c: number, x: number, y: number): number;
/**
* Get a noise value between min and max for a point (x, y, z) on the surface of a sphere with circumference c.
*/
spherical3D(c: number, x: number, y: number, z: number): number;
}
declare module "fast-simplex-noise" {
export = FastSimplexNoise;
}
-27
View File
@@ -1,27 +0,0 @@
import GitHubApi = require("github");
let github = new GitHubApi({
// optional args
debug: true,
protocol: "https",
host: "github.my-GHE-enabled-company.com", // should be api.github.com for GitHub
pathPrefix: "/api/v3", // for some GHEs; none for GitHub
headers: {
"user-agent": "My-Cool-GitHub-App" // GitHub is happy with a unique user agent
},
Promise: null as any,
followRedirects: false, // default: true; there's currently an issue with non-get redirects, so allow ability to disable follow-redirects
timeout: 5000
});
// TODO: optional authentication here depending on desired endpoints. See below in README.
github.users.getFollowingForUser({
// optional:
// headers: {
// "cookie": "blahblah"
// },
user: "defunkt"
}, (err: any, res: any) => {
console.log(JSON.stringify(res));
});
-326
View File
@@ -1,326 +0,0 @@
// Type definitions for github
// Project: https://github.com/mikedeboer/node-github
// Definitions by: vvakame <https://github.com/vvakame/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = Client;
declare class Client {
authorization: Authorization;
events: Events;
gists: Gists;
gitdata: GitData;
gitignore: GitIgnore;
issues: Issues;
markdown: Markdown;
misc: Misc;
orgs: Orgs;
pullRequests: PullRequests;
releases: Releases;
repos: Repos;
search: Search;
statues: Statues;
users: User;
constructor(options: Options);
authenticate(...args: any[]): any;
getFirstPage(...args: any[]): any;
getLastPage(...args: any[]): any;
getNextPage(...args: any[]): any;
getPreviousPage(...args: any[]): any;
hasFirstPage(...args: any[]): any;
hasLastPage(...args: any[]): any;
hasNextPage(...args: any[]): any;
hasPreviousPage(...args: any[]): any;
httpSend(...args: any[]): any;
setupRoutes(...args: any[]): any;
}
declare namespace Client { }
interface Options {
version?: string;
debug?: boolean;
protocol?: string;
host?: string;
pathPrefix?: string;
timeout?: number;
headers?: { [name: string]: any; };
followRedirects?: boolean;
Promise?: typeof Promise;
}
interface Authorization {
create(msg: AuthorizationCreateMessage, callback: Function): void;
delete: Function;
get: Function;
getAll: Function;
update: Function;
}
interface AuthorizationCreateMessage {
headers?: { [name: string]: string; };
scopes?: string[];
note?: string;
note_url?: string;
client_id?: string;
client_secret?: string;
fingerprint?: string;
}
interface Events {
get(...args: any[]): any;
getFromOrg(...args: any[]): any;
getFromRepo(...args: any[]): any;
getFromRepoIssues(...args: any[]): any;
getFromRepoNetwork(...args: any[]): any;
getFromUser(...args: any[]): any;
getFromUserOrg(...args: any[]): any;
getFromUserPublic(...args: any[]): any;
getReceived(...args: any[]): any;
getReceivedPublic(...args: any[]): any;
}
interface Gists {
checkStar(...args: any[]): any;
create(...args: any[]): any;
createComment(...args: any[]): any;
delete(...args: any[]): any;
deleteComment(...args: any[]): any;
deleteStar(...args: any[]): any;
edit(...args: any[]): any;
editComment(...args: any[]): any;
fork(...args: any[]): any;
get(...args: any[]): any;
getAll(...args: any[]): any;
getComment(...args: any[]): any;
getComments(...args: any[]): any;
getFromUser(...args: any[]): any;
public(...args: any[]): any;
star(...args: any[]): any;
starred(...args: any[]): any;
}
interface GitData {
createBlob(...args: any[]): any;
createCommit(...args: any[]): any;
createReference(...args: any[]): any;
createTag(...args: any[]): any;
createTree(...args: any[]): any;
deleteReference(...args: any[]): any;
getAllReferences(...args: any[]): any;
getBlob(...args: any[]): any;
getCommit(...args: any[]): any;
getReference(...args: any[]): any;
getTag(...args: any[]): any;
getTree(...args: any[]): any;
updateReference(...args: any[]): any;
}
interface GitIgnore {
template(...args: any[]): any;
templates(...args: any[]): any;
}
interface Issues {
create(...args: any[]): any;
createComment(...args: any[]): any;
createLabel(...args: any[]): any;
createMilestone(...args: any[]): any;
deleteComment(...args: any[]): any;
deleteLabel(...args: any[]): any;
deleteMilestone(...args: any[]): any;
edit(...args: any[]): any;
editComment(...args: any[]): any;
getAll(...args: any[]): any;
getAllMilestones(...args: any[]): any;
getComment(...args: any[]): any;
getComments(...args: any[]): any;
getEvent(...args: any[]): any;
getEvents(...args: any[]): any;
getIssueLabels(...args: any[]): any;
getLabel(...args: any[]): any;
getLabels(...args: any[]): any;
getMilestone(...args: any[]): any;
getRepoEvents(...args: any[]): any;
getRepoIssue(...args: any[]): any;
repoComments(...args: any[]): any;
repoIssues(...args: any[]): any;
updateLabel(...args: any[]): any;
updateMilestone(...args: any[]): any;
}
interface Markdown {
render(...args: any[]): any;
}
interface Misc {
emojis(...args: any[]): any;
meta(...args: any[]): any;
rateLimit(...args: any[]): any;
}
interface Orgs {
addTeamMember(...args: any[]): any;
addTeamRepo(...args: any[]): any;
concealMembership(...args: any[]): any;
createTeam(...args: any[]): any;
deleteTeam(...args: any[]): any;
deleteTeamMember(...args: any[]): any;
deleteTeamRepo(...args: any[]): any;
get(...args: any[]): any;
getFromUser(...args: any[]): any;
getMember(...args: any[]): any;
getMembers(...args: any[]): any;
getPublicMember(...args: any[]): any;
getPublicMembers(...args: any[]): any;
getTeam(...args: any[]): any;
getTeamMember(...args: any[]): any;
getTeamMembers(...args: any[]): any;
getTeamRepo(...args: any[]): any;
getTeamRepos(...args: any[]): any;
getTeams(...args: any[]): any;
publicizeMembership(...args: any[]): any;
removeMember(...args: any[]): any;
update(...args: any[]): any;
updateTeam(...args: any[]): any;
}
interface PullRequests {
create(...args: any[]): any;
createComment(...args: any[]): any;
createCommentReply(...args: any[]): any;
createFromIssue(...args: any[]): any;
deleteComment(...args: any[]): any;
get(...args: any[]): any;
getAll(...args: any[]): any;
getComment(...args: any[]): any;
getComments(...args: any[]): any;
getCommits(...args: any[]): any;
getFiles(...args: any[]): any;
getMerged(...args: any[]): any;
merge(...args: any[]): any;
update(...args: any[]): any;
updateComment(...args: any[]): any;
}
interface Releases {
createRelease(...args: any[]): any;
deleteAsset(...args: any[]): any;
deleteRelease(...args: any[]): any;
editAsset(...args: any[]): any;
editRelease(...args: any[]): any;
getAsset(...args: any[]): any;
getRelease(...args: any[]): any;
listAssets(...args: any[]): any;
listReleases(...args: any[]): any;
}
interface Repos {
addCollaborator(...args: any[]): any;
compareCommits(...args: any[]): any;
create(...args: any[]): any;
createCommitComment(...args: any[]): any;
createContent(...args: any[]): any;
createFile(...args: any[]): any;
createFromOrg(...args: any[]): any;
createHook(...args: any[]): any;
createKey(...args: any[]): any;
delete(...args: any[]): any;
deleteCommitComment(...args: any[]): any;
deleteDownload(...args: any[]): any;
deleteFile(...args: any[]): any;
deleteHook(...args: any[]): any;
deleteKey(...args: any[]): any;
fork(...args: any[]): any;
get(...args: any[]): any;
getAll(...args: any[]): any;
getAllCommitComments(...args: any[]): any;
getArchiveLink(...args: any[]): any;
getBranch(...args: any[]): any;
getBranches(...args: any[]): any;
getCollaborator(...args: any[]): any;
getCollaborators(...args: any[]): any;
getCommit(...args: any[]): any;
getCommitComment(...args: any[]): any;
getCommitComments(...args: any[]): any;
getCommits(...args: any[]): any;
getContent(...args: any[]): any;
getContributors(...args: any[]): any;
getDownload(...args: any[]): any;
getDownloads(...args: any[]): any;
getForks(...args: any[]): any;
getFromOrg(...args: any[]): any;
getFromUser(...args: any[]): any;
getHook(...args: any[]): any;
getHooks(...args: any[]): any;
getKey(...args: any[]): any;
getKeys(...args: any[]): any;
getLanguages(...args: any[]): any;
getReadme(...args: any[]): any;
getStargazers(...args: any[]): any;
getStarred(...args: any[]): any;
getStarredFromUser(...args: any[]): any;
getStarring(...args: any[]): any;
getStatsCodeFrequency(...args: any[]): any;
getStatsCommitActivity(...args: any[]): any;
getStatsContributors(...args: any[]): any;
getStatsParticipation(...args: any[]): any;
getStatsPunchCard(...args: any[]): any;
getTags(...args: any[]): any;
getTeams(...args: any[]): any;
getWatched(...args: any[]): any;
getWatchedFromUser(...args: any[]): any;
getWatchers(...args: any[]): any;
getWatching(...args: any[]): any;
merge(...args: any[]): any;
one(...args: any[]): any;
removeCollaborator(...args: any[]): any;
star(...args: any[]): any;
testHook(...args: any[]): any;
unStar(...args: any[]): any;
unWatch(...args: any[]): any;
update(...args: any[]): any;
updateCommitComment(...args: any[]): any;
updateFile(...args: any[]): any;
updateHook(...args: any[]): any;
updateKey(...args: any[]): any;
watch(...args: any[]): any;
}
interface Search {
email(...args: any[]): any;
issues(...args: any[]): any;
repos(...args: any[]): any;
users(...args: any[]): any;
}
interface Statues {
create(...args: any[]): any;
get(...args: any[]): any;
getCombined(...args: any[]): any;
}
interface User {
user(...args: any[]): any;
addEmails(...args: any[]): any;
createKey(...args: any[]): any;
deleteEmails(...args: any[]): any;
deleteKey(...args: any[]): any;
followUser(...args: any[]): any;
get(...args: any[]): any;
getEmails(...args: any[]): any;
getFollowers(...args: any[]): any;
getFollowing(...args: any[]): any;
getFollowingFromUser(...args: any[]): any;
getFollowingForUser(...args: any[]): any;
getFrom(...args: any[]): any;
getKey(...args: any[]): any;
getKeys(...args: any[]): any;
getKeysFromUser(...args: any[]): any;
getOrgs(...args: any[]): any;
getTeams(...args: any[]): any;
unFollowUser(...args: any[]): any;
update(...args: any[]): any;
updateKey(...args: any[]): any;
}
+1
View File
@@ -23,6 +23,7 @@ function test_graph() {
g.setDefaultEdgeLabel(() => 'e42');
g.setNodes(['a', 'b', 'c'], 42);
g.setParent('d', 'a');
g.setParent('d');
g.parent('d');
g.children('a');
g.filterNodes(v => true);
+3 -2
View File
@@ -65,7 +65,8 @@ declare module "graphlib" {
setNodes(names: string[], label?: any): Graph;
/**
* Sets node p as a parent for node v. Method throws an exception in case of
* Sets node p as a parent for node v if it is defined, or removes the
* parent for v if p is undefined. Method throws an exception in case of
* invoking it in context of noncompound graph.
* Average-case complexity: O(1).
*
@@ -73,7 +74,7 @@ declare module "graphlib" {
* @argument p - node to be parent for v.
* @returns the graph, allowing this to be chained with other functions.
*/
setParent(v: string, p: string): Graph;
setParent(v: string, p?: string): Graph;
/**
* Gets parent node for node v.
+3 -10
View File
@@ -1,4 +1,4 @@
// Type definitions for hapi 16.0.0
// Type definitions for hapi 16.0.1
// Project: http://github.com/spumko/hapi
// Definitions by: Jason Swearingen <http://github.com/jasonswearingen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -16,16 +16,9 @@ interface IDictionary<T> {
[key: string]: T;
}
interface IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IThenable<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IThenable<U>;
}
export declare type IThenable<R> = PromiseLike<R>
interface IPromise<R> extends IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IPromise<U>;
catch<U>(onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
}
export declare type IPromise<R> = Promise<R>
export interface IHeaderOptions {
append?: boolean;
+22 -22
View File
@@ -30,10 +30,10 @@ declare namespace Highstock {
}
interface RangeSelectorButton {
type: string; // Defines the timespan, can be one of 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' and 'all'.
count?: number;
text: string;
dataGrouping?: any; // not sure how this works
type: string; // Defines the timespan, can be one of 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' and 'all'.
count?: number;
text: string;
dataGrouping?: any; // not sure how this works
}
interface RangeSelectorOptions {
@@ -61,24 +61,24 @@ declare namespace Highstock {
}
interface ScrollbarOptions {
barBackgroundColor?: string;
barBorderColor?: string;
barBorderRadius?: number;
barBorderWidth?: number;
buttonArrowColor?: string;
buttonBackgroundColor?: string;
buttonBorderColor?: string;
buttonBorderRadius?: number;
buttonBorderWidth?: number;
enabled?: boolean;
height?: number;
liveRedraw?: boolean;
minWidth?: number;
rifleColor?: string;
trackBackgroundColor?: string;
trackBorderColor?: string;
trackBorderRadius?: number;
trackBorderWidth?: number;
barBackgroundColor?: string;
barBorderColor?: string;
barBorderRadius?: number;
barBorderWidth?: number;
buttonArrowColor?: string;
buttonBackgroundColor?: string;
buttonBorderColor?: string;
buttonBorderRadius?: number;
buttonBorderWidth?: number;
enabled?: boolean;
height?: number;
liveRedraw?: boolean;
minWidth?: number;
rifleColor?: string;
trackBackgroundColor?: string;
trackBorderColor?: string;
trackBorderRadius?: number;
trackBorderWidth?: number;
}
interface Options extends Highcharts.Options {
+2 -5
View File
@@ -13,16 +13,13 @@ declare module 'highcharts' {
interface MapOptions {
chart?: highcharts.ChartOptions;
legend?: highcharts.LegendOptions;
mapNavigation?: Navigation;
plotOptions?: highcharts.PlotOptions;
series?: MapSeriesOptions[];
colorAxis?: ColorAxis;
title?: highcharts.TitleOptions;
tooltip?: highcharts.TooltipOptions;
}
interface MapSeriesOptions {
+82 -10
View File
@@ -1,15 +1,87 @@
// Type definitions for inert 4.0
// Type definitions for inert 4.2
// Project: https://github.com/hapijs/inert/
// Definitions by: Steve Ognibene <http://github.com/nycdotnet>
// Definitions by: Steve Ognibene <http://github.com/nycdotnet>, AJP <https://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Note: this definition contains only enough to make TypeScript happy (hapi?) when
// importing inert. The functionality that importing inert adds to the reply
// object and its other features are implemented in the hapi definition on
// DefinitelyTyped. The inert object is never actually used in practice except to
// be passed as an extension to the server.register() method which already takes
// an `any` argument, so just using `any` here is fine.
import * as hapi from 'hapi';
/// <reference types="node" />
declare module 'hapi' {
interface IFileHandler {
/** path - a path string or function as described above (required). */
path: string | IRequestHandler<string>;
/** confine - serve file relative to this directory and returns 403 Forbidden if the path resolves outside the confine directory. Defaults to true which uses the relativeTo route option as the confine. Set to false to disable this security feature. */
confine?: boolean;
/** filename - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path */
filename?: string;
/**
* mode - specifies whether to include the 'Content-Disposition' header with the response. Available values:
* * false - header is not included. This is the default value.
* * 'attachment'
* *'inline'
*/
mode?: false | 'attachment' | 'inline';
/** lookupCompressed - if true, looks for for a pre-compressed version of the file with the same filename with an extension, depending on the accepted encoding. Defaults to false. */
lookupCompressed?: boolean;
/** lookupMap - an object which maps content encoding to expected file name extension. Defaults to `{ gzip: '.gz' }. */
lookupMap?: {[index: string]: string};
/**
* etagMethod - specifies the method used to calculate the ETag header response. Available values:
* * 'hash' - SHA1 sum of the file contents, suitable for distributed deployments. Default value.
* * 'simple' - Hex encoded size and modification date, suitable when files are stored on a single server.
* * false - Disable ETag computation.
*/
etagMethod?: 'hash' | 'simple' | false;
/** start - offset in file to reading from, defaults to 0. */
start?: number;
/** end - offset in file to stop reading from. If not set, will read to end of file. */
end?: number;
}
export const inert: any;
interface IDirectoryHandler {
/** path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be:
* * a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string.
* * an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string).
* * a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response.
*/
path: string | string[] | IRequestHandler<string | string[] | Error>;
/** index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. */
index?: boolean | string | string[];
/** listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. */
listing?: boolean;
/** showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. */
showHidden?: boolean;
/** redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. */
redirectToSlash?: boolean;
/** lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */
lookupCompressed?: boolean;
/**
* etagMethod - specifies the method used to calculate the ETag header response. Available values:
* * 'hash' - SHA1 sum of the file contents, suitable for distributed deployments. Default value.
* * 'simple' - Hex encoded size and modification date, suitable when files are stored on a single server.
* * false - Disable ETag computation.
*/
etagMethod?: 'hash' | 'simple' | false;
/** defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension. */
defaultExtension?: string;
}
interface IRouteConfiguration {
/**
* The file handler
*
* Generates a static file endpoint for serving a single file. file can be set to:
* * a relative or absolute file path string (relative paths are resolved based on the route files configuration).
* * a function with the signature function(request) which returns the relative or absolute file path.
* * an object with one or more of the following options:
* @see {@link https://github.com/hapijs/inert#the-file-handler}
*/
file?: string | IRequestHandler<string> | IFileHandler;
/**
* The directory handler
*
* Generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options:
* @see {@link https://github.com/hapijs/inert#the-directory-handler}
*/
directory?: IDirectoryHandler;
}
}
+31
View File
@@ -3,3 +3,34 @@ import * as InertES6 from 'inert';
const server = new HapiES6.Server({});
server.register(InertES6, () => {});
server.route({
path: '',
method: 'GET',
file: {
path: '',
confine: true,
},
directory: {
path: '',
listing: true
}
})
var fileHandler: HapiES6.IFileHandler = {
path: '',
confine: true,
}
var directoryHandler: HapiES6.IDirectoryHandler = {
path: function(){
if(Math.random() > 0.5) {
return '';
}
else if(Math.random() > 0) {
return [''];
}
return new Error('');
},
listing: true,
}
-1
View File
@@ -1 +0,0 @@
{ "extends": "../tslint.json" }
+20 -14
View File
@@ -4,36 +4,42 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace jsonpatch {
type OpPatch = AddPath | RemovePath | ReplacePath | MovePath | CopyPath | TestPath;
type OpPatch = AddPatch | RemovePatch | ReplacePatch | MovePatch | CopyPatch | TestPatch;
interface Patch {
op: string;
}
interface AddPath extends Patch {
path: string;
}
interface AddPatch extends Patch {
op: 'add';
value: any;
}
interface RemovePath extends Patch {
path: string;
interface RemovePatch extends Patch {
op: 'remove';
}
interface ReplacePath extends Patch {
path: string;
interface ReplacePatch extends Patch {
op: 'replace';
value: any;
}
interface MovePath extends Patch {
interface MovePatch extends Patch {
op: 'move';
from: string;
path: string;
}
interface CopyPath extends Patch {
interface CopyPatch extends Patch {
op: 'copy';
from: string;
path: string;
}
interface TestPath extends Patch {
path: string;
interface TestPatch extends Patch {
op: 'test';
value: any;
}
function apply(document: any, patches: OpPatch[]): any;
function compile(patches: OpPatch[]): (document: any) => any;
class JSONPatchError extends Error { }
class InvalidPointerError extends Error { }
class InvalidPatchError extends JSONPatchError { }
class PatchConflictError extends JSONPatchError { }
class PatchTestFailed extends Error { }
}
export = jsonpatch;
+19
View File
@@ -32,3 +32,22 @@ jsonpatch.apply({ foo: 'bar' }, [{ op: 'test', path: '/foo', value: 'bar' }]);
jsonpatch.compile([{ op: 'test', path: '/foo', value: 'bar' }])({ foo: 'bar' });
jp.apply({}, [{ op: 'add', path: '/foo', value: 'bar' }]);
function patchShouldFail(document: any, patches: jsonpatch.OpPatch[]): string {
try {
jsonpatch.apply(document, patches);
throw new Error('Patch did not fail...');
} catch (err) {
if (err instanceof jsonpatch.PatchTestFailed) {
return 'Test failed';
} else if (err instanceof jsonpatch.InvalidPointerError) {
return 'Invalid Pointer';
} else if (err instanceof jsonpatch.InvalidPatchError) {
return 'Invalid Patch';
} else if (err instanceof jsonpatch.PatchConflictError) {
return 'Patch Conflict';
} else {
return 'Failed with unknown error';
}
}
}
+33
View File
@@ -28,8 +28,33 @@ declare namespace karma {
stopper: Stopper;
launcher: Launcher;
VERSION: string;
constants: Constants;
}
interface Constants {
VERSION: string;
DEFAULT_PORT: number;
DEFAULT_HOSTNAME: string;
DEFAULT_LISTEN_ADDR: string;
LOG_DISABLE: string;
LOG_ERROR: string;
LOG_WARN: string;
LOG_INFO: string;
LOG_DEBUG: string;
LOG_LOG: string;
LOG_PRIORITIES: string[];
COLOR_PATTERN: string;
NO_COLOR_PATTERN: string;
CONSOLE_APPENDER: {
type: string;
layout: {
type: string;
pattern: string;
};
};
EXIT_CODE: string;
}
interface LauncherStatic {
generateId(): string;
//TODO: injector should be of type `di.Injector`
@@ -205,6 +230,14 @@ declare namespace karma {
* @description Enable or disable colors in the output (reporters and logs).
*/
colors?: boolean;
/**
* @default 'Infinity'
* @description How many browsers Karma launches in parallel.
* Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited
* amount of browsers at once, and only start more when those have finished. Using this configuration,
* you can specify how many browsers should be running at once at any given point in time.
*/
concurrency?: number;
/**
* @default []
* @description List of files/patterns to exclude from loaded files.
+9 -9
View File
@@ -424,11 +424,11 @@ declare namespace L {
getTooltip(): Tooltip | undefined;
// Extension methods
onAdd?: (map: Map) => this;
onRemove?: (map: Map) => this;
getEvents?: () => {[name: string]: (event: Event) => void};
getAttribution?: () => string | null;
beforeAdd?: (map: Map) => this;
onAdd(map: Map): this;
onRemove(map: Map): this;
getEvents?(): {[name: string]: (event: Event) => void};
getAttribution?(): string | null;
beforeAdd?(map: Map): this;
}
interface GridLayerOptions {
@@ -992,8 +992,8 @@ declare namespace L {
remove(): this;
// Extension methods
onAdd?: (map: Map) => HTMLElement;
onRemove?: (map: Map) => void;
onAdd?(map: Map): HTMLElement;
onRemove?(map: Map): void;
options: ControlOptions;
}
@@ -1175,8 +1175,8 @@ declare namespace L {
enabled(): boolean;
// Extension methods
addHooks?: () => void;
removeHooks?: () => void;
addHooks?(): void;
removeHooks?(): void;
}
interface Event {
+1 -1
View File
@@ -5702,7 +5702,7 @@ declare namespace _ {
/**
* @see _.zipObjectDeep
*/
zipObjectDepp(
zipObjectDeep(
props: List<StringRepresentable>|List<List<any>>,
values?: List<any>
): _.Dictionary<any>;
-387
View File
@@ -1,387 +0,0 @@
// Type definitions for maquette
// Project: http://maquettejs.org/
// Definitions by: Johan Gorter <https://github.com/johan-gorter>
// Definitions: https://github.com/johan-gorter/DefinitelyTyped
/**
* The main object in maquette is the maquette object.
* It is either bound to `window.maquette` or it can be obtained using {@link http://browserify.org/|browserify} or {@link http://requirejs.org/|requirejs}.
*/
declare namespace maquette {
// Needed for typescript pre-1.5?
interface Touch {
clientX: number;
clientY: number;
identifier: number;
pageX: number;
pageY: number;
screenX: number;
screenY: number;
target: EventTarget;
}
interface TouchList {
length: number;
item(index: number): Touch;
[index: number]: Touch;
}
interface TouchEvent extends UIEvent {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
}
export interface VNodeProperties {
enterAnimation?: ((element: Element, properties?: VNodeProperties) => void) | string;
exitAnimation?: ((element: Element, removeElement: () => void, properties?: VNodeProperties) => void) | string;
updateAnimation?: (element: Element, properties?: VNodeProperties, previousProperties?: VNodeProperties) => void;
afterCreate?: (element: Element, projectionOptions: ProjectionOptions, vnodeSelector: string, properties: VNodeProperties,
children: VNode[]) => void;
afterUpdate?: (element: Element, projectionOptions: ProjectionOptions, vnodeSelector: string, properties: VNodeProperties,
children: VNode[]) => void;
key?: Object;
classes?: {[index:string]: boolean};
styles?: {[index:string]: string};
// From Element
ontouchcancel?: (ev?: TouchEvent) => boolean|void;
ontouchend?: (ev?: TouchEvent) => boolean|void;
ontouchmove?: (ev?: TouchEvent) => boolean|void;
ontouchstart?: (ev?: TouchEvent) => boolean|void;
// From HTMLFormElement
action?: string;
encoding?: string;
enctype?: string;
method?: string;
name?: string;
target?: string;
// From HTMLElement
onblur?: (ev?: FocusEvent) => boolean|void;
onchange?: (ev?: Event) => boolean|void;
onclick?: (ev?: MouseEvent) => boolean|void;
ondblclick?: (ev?: MouseEvent) => boolean|void;
onfocus?: (ev?: FocusEvent) => boolean|void;
oninput?: (ev?: Event) => boolean|void;
onkeydown?: (ev?: KeyboardEvent) => boolean|void;
onkeypress?: (ev?: KeyboardEvent) => boolean|void;
onkeyup?: (ev?: KeyboardEvent) => boolean|void;
onload?: (ev?: Event) => boolean|void;
onmousedown?: (ev?: MouseEvent) => boolean|void;
onmouseenter?: (ev?: MouseEvent) => boolean|void;
onmouseleave?: (ev?: MouseEvent) => boolean|void;
onmousemove?: (ev?: MouseEvent) => boolean|void;
onmouseout?: (ev?: MouseEvent) => boolean|void;
onmouseover?: (ev?: MouseEvent) => boolean|void;
onmouseup?: (ev?: MouseEvent) => boolean|void;
onmousewheel?: (ev?: MouseWheelEvent) => boolean|void;
onscroll?: (ev?: UIEvent) => boolean|void;
onsubmit?: (ev?: Event) => boolean|void;
spellcheck?: boolean;
tabIndex?: number;
title?: string;
accessKey?: string;
id?: string;
// From HTMLInputElement
autocomplete?: string;
checked?: boolean;
placeholder?: string;
readOnly?: boolean;
src?: string;
value?: string;
// From HTMLImageElement
alt?: string;
srcset?: string;
// Everything else (uncommon or custom properties and attributes)
[index: string]: Object;
}
export interface ProjectionOptions {
transitions?: {
enter: (element: Element, properties: VNodeProperties, enterAnimation: string) => void;
exit: (element: Element, properties: VNodeProperties, exitAnimation: string, removeElement: () => void) => void;
}
}
// The following line is not possible in Typescript, hence the workaround in the two lines below
// export type VNodeChild = string|VNode|Array<VNodeChild>
export interface VNodeChildren extends Array<VNodeChild> {} // A bit of a hack to create a recursive type
export type VNodeChild = string|VNode|VNodeChildren;
export var dom: MaquetteDom;
/**
* Creates a {@link CalculationCache} object, useful for caching {@link VNode} trees.
* In practice, caching of {@link VNode} trees is not needed, because achieving 60 frames per second is almost never a problem.
* @returns {CalculationCache}
*/
export function createCache<Result>(): CalculationCache<Result>;
/**
* Creates a {@link Mapping} instance that keeps an array of result objects synchronized with an array of source objects.
* @param {function} getSourceKey - `function(source)` that must return a key to identify each source object. The result must eather be a string or a number.
* @param {function} createResult - `function(source, index)` that must create a new result object from a given source. This function is identical argument of `Array.map`.
* @param {function} updateResult - `function(source, target, index)` that updates a result to an updated source.
* @returns {Mapping}
*/
export function createMapping<Source, Target>(
getSourceKey: (source: Source) => (string|number),
createResult: (source: Source, index:number) => Target,
updateResult: (source: Source, target: Target, index: number) => void): Mapping<Source, Target>;
/**
* Creates a {@link Projector} instance using the provided projectionOptions.
* @param {Object} projectionOptions - Options that influence how the DOM is rendered and updated.
* projectionOptions.transitions - A transition strategy to invoke when
* enterAnimation and exitAnimation properties are provided as strings.
* The module `cssTransitions` in the provided `css-transitions.js` file provides such a strategy.
* A transition strategy is not needed when enterAnimation and exitAnimation properties are provided as functions.
* @returns {Projector}
*/
export function createProjector(projectionOptions? : ProjectionOptions) : Projector;
/**
* Creates a virtual DOM node, used to render a real DOM later.
* The `h` stands for (virtual) hyperscript.
*
* @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`.
* @param {Object} properties - An object literal containing attributes, properties, event handlers and more be placed on the DOM node.
* @param {Array<VNodeChild>} children - An array of virtual DOM nodes and strings to add as child nodes. May contain nested arrays, null or undefined.
*
* @returns {VNode} A VNode object, used to render a real DOM later.
*/
export function h(selector: string, properties: VNodeProperties, children: Array<VNodeChild>): VNode;
/**
* Creates a virtual DOM node, used to render a real DOM later.
* The `h` stands for (virtual) hyperscript.
*
* @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`.
* @param {Array<VNodeChild>} children - An array of virtual DOM nodes and strings to add as child nodes. May contain nested arrays, null or undefined.
*
* @returns {VNode} A VNode object, used to render a real DOM later.
*/
export function h(selector: string, children: Array<VNodeChild>): VNode;
/**
* Creates a virtual DOM node, used to render a real DOM later.
* The `h` stands for (virtual) hyperscript.
*
* @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`.
* @param {Object} properties - An object literal containing attributes, properties, event handlers and more be placed on the DOM node.
*
* @returns {VNode} A VNode object, used to render a real DOM later.
*/
export function h(selector: string, properties: VNodeProperties): VNode;
/**
* Creates a virtual DOM node, used to render a real DOM later.
* The `h` stands for (virtual) hyperscript.
*
* @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`.
*
* @returns {VNode} A VNode object, used to render a real DOM later.
*/
export function h(selector: string): VNode;
/**
* A virtual representation of a DOM Node. Maquette assumes that {@link VNode} objects are never modified externally.
* Instances of {@link VNode} can be created using {@link module:maquette.h}.
*/
export interface VNode {
vnodeSelector: string;
properties: VNodeProperties;
children: Array<VNode>;
}
// Not used anywhere in the maquette sourcecode, but it is a widely used pattern.
export interface Component {
renderMaquette() : VNode;
}
/**
* A CalculationCache object remembers the previous outcome of a calculation along with the inputs.
* On subsequent calls the previous outcome is returned if the inputs are identical.
* This object can be used to bypass both rendering and diffing of a virtual DOM subtree.
* Instances of {@link CalculationCache} can be created using {@link module:maquette.createCache}.
*/
export interface CalculationCache<Result> {
/**
* Manually invalidates the cached outcome.
*/
invalidate(): void;
/**
* If the inputs array matches the inputs array from the previous invocation, this method returns the result of the previous invocation.
* Otherwise, the calculation function is invoked and its result is cached and returned.
* Objects in the inputs array are compared using ===.
* @param {Object[]} inputs - Array of objects that are to be compared using === with the inputs from the previous invocation.
* These objects are assumed to be immutable primitive values.
* @param {function} calculation - Function that takes zero arguments and returns an object (A {@link VNode} assumably) that can be cached.
*/
result(inputs: Array<Object>, calculation: () => Result):Result;
}
/**
* Keeps an array of result objects synchronized with an array of source objects.
* Mapping provides a {@link Mapping#map} function that updates the {@link Mapping#results}.
* The {@link Mapping#map} function can be called multiple times and the results will get created, removed and updated accordingly.
* A {@link Mapping} can be used to keep an array of components (objects with a `renderMaquette` method) synchronized with an array of data.
* Instances of {@link Mapping} can be created using {@link module:maquette.createMapping}.
*/
export interface Mapping<Source, Target> {
/**
* The array of results. These results will be synchronized with the latest array of sources that were provided using {@link Mapping#map}.
* @type {Object[]}
*/
results: Array<Target>;
/**
* Maps a new array of sources and updates {@link Mapping#results}.
* @param {Object[]} newSources - The new array of sources.
*/
map(newSources: Array<Source>): void;
}
/**
* Contains simple low-level utility functions to manipulate the real DOM. The singleton instance is available under {@link module:maquette.dom}.
*/
export interface MaquetteDom {
/**
* Appends a new childnode to the DOM which is generated from a {@link VNode}.
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {Element} parentNode - The parent node for the new childNode.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} that was created.
*/
append(parentNode: Element, vnode: VNode, projectionOptions?: ProjectionOptions): Projection;
/**
* Creates a real DOM tree from a {@link VNode}. The {@link Projection} object returned will contain the resulting DOM Node under the {@link Projection#domNode} property.
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} which contains the DOM Node that was created.
*/
create(vnode: VNode, projectionOptions?: ProjectionOptions): Projection;
/**
* Inserts a new DOM node which is generated from a {@link VNode}.
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {Element} beforeNode - The node that the DOM Node is inserted before.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} that was created.
*/
insertBefore(beforeNode: Element, vnode: VNode): Projection;
/**
* Merges a new DOM node which is generated from a {@link VNode} with an existing DOM Node.
* This means that the virtual DOM and real DOM have one overlapping element.
* Therefore the selector for the root {VNode} will be ignored, but its properties and children will be applied to the Element provided
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {Element} domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} that was created.
*/
merge(domNode: Element, vnode: VNode): Projection;
}
/**
* Represents a {@link VNode} tree that has been rendered to a real DOM tree.
*/
export interface Projection {
/**
* Updates the projection with the new virtual DOM tree.
* @param {VNode} updatedVnode - The updated virtual DOM tree. Note: The selector for the root of the tree must remain constant.
*/
update(updatedVnode:VNode): void;
/**
* The DOM node that is used as the root of this {@link Projection}.
* @type {Element}
*/
domNode: Element;
}
/**
* Used to create and update the DOM.
* Use {@link Projector#append}, {@link Projector#merge}, {@link Projector#insertBefore} and {@link Projector#replace}
* to create the DOM.
* The `renderMaquetteFunction` callbacks will be called immediately to create the DOM. Afterwards, these functions
* will be called again to update the DOM on the next animation-frame after:
*
* - The {@link Projector#scheduleRender} function was called
* - An event handler (like `onclick`) on a rendered {@link VNode} was called.
*
* The projector stops when {@link Projector#stop} is called or when an error is thrown during rendering.
* It is possible to use `window.onerror` to handle these errors.
* Instances of {@link Projector} can be created using {@link module:maquette.createProjector}.
*/
export interface Projector {
/**
* Appends a new childnode to the DOM using the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} parentNode - The parent node for the new childNode.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
append(parentNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Stops running the `renderMaquetteFunction` to update the DOM. The `renderMaquetteFunction` must have been
* registered using [[append]], [[merge]], [[insertBefore]] or [[replace]].
*
* @returns The [[Projection]] which was created using this `renderMaquetteFunction`.
* The [[Projection]] contains a reference to the DOM Node that was rendered.
*/
detach(renderMaquetteFunction: () => VNode): Projection;
/**
* Scans the document for `<script>` tags with `type="text/hyperscript"`.
* The content of these scripts are registered as `renderMaquette` functions.
* The result of evaluating these functions will be inserted into the DOM after the script.
* These scripts can make use of variables that come from the `parameters` parameter.
* @param {Element} rootNode - Element to start scanning at, example: `document.body`.
* @param {Object} parameters - Variables to expose to the scripts. format: `{var1:value1, var2: value2}`
*/
evaluateHyperscript(rootNode: Element, parameters: {[index: string]: Object}): void;
/**
* Inserts a new DOM node using the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} beforeNode - The node that the DOM Node is inserted before.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
insertBefore(beforeNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Merges a new DOM node using the result from the provided `renderMaquetteFunction` with an existing DOM Node.
* This means that the virtual DOM and real DOM have one overlapping element.
* Therefore the selector for the root {VNode} will be ignored, but its properties and children will be applied to the Element provided
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
merge(domNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Replaces an existing DOM node with the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} domNode - The DOM node to replace.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
replace(domNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Resumes the projector. Use this method to resume rendering after stop was called or an error occurred during rendering.
*/
resume(): void;
/**
* Instructs the projector to re-render to the DOM at the next animation-frame using the registered `renderMaquette` functions.
* This method is automatically called for you when event-handlers that are registered in the {@link VNode}s are invoked.
* You need to call this method for instance when timeouts expire or AJAX responses arrive.
*/
scheduleRender(): void;
/**
* Stops the projector. This means that the registered `renderMaquette` functions will not be called anymore.
* Note that calling {@link Projector#stop} is not mandatory. A projector is a passive object that will get garbage collected as usual if it is no longer in scope.
*/
stop(): void;
}
}
export = maquette;
export as namespace maquette;
-100
View File
@@ -1,100 +0,0 @@
import maquette = require("maquette");
// The hello world example from the homepage of maquettejs.org:
var h = maquette.h;
var domNode = document.body;
var projector = maquette.createProjector();
var you = ""; // A piece of data
// An ordinary event handler
function handleNameInput(evt: MouseEvent) {
you = (<HTMLInputElement>evt.target).value;
}
// This function uses the 'hyperscript' notation to create the virtual DOM.
// The 'you' variable is used twice here
function renderMaquette() {
return h("div", [
h("input", {
type: "text", placeholder: "What is your name?", value: you, oninput: handleNameInput
}),
h("p.output", ["Hello " + (you || "you") + "!"])
]);
}
// Project the renderMaquette function to the DOM and update the DOM when needed
projector.append(domNode, renderMaquette);
// Some snapshots taken from the maquette unit tests
// createDOM
var projection = maquette.dom.create(h("div", ["text"]));
projection.update(h("div", ["text2", h("span", ["a"])]));
// cache
var cache = maquette.createCache();
var calculationCalled = false;
var calculate = function () {
calculationCalled = true;
return "calculation result";
};
var result = cache.result([1], calculate);
// h
h("div",{onclick: (ev:MouseEvent) => true})
var vnode = h("div", [
"text",
null,
[ /* empty nested array */],
[null],
["nested text"],
[h("span")],
[h("button", ["click me"])],
[[[["deep"], null], "here"]]
]);
// mapping
interface Target {
source: number;
updateCount: number;
alreadyPresent: boolean;
}
var createTarget = function(source:number): Target {
return {
source: source,
updateCount: 0,
alreadyPresent: false
};
};
var updateTarget = function(source: number, target:Target) {
target.updateCount++;
};
var permutations = [[1,2], [2,1]];
for (var i=0;i<permutations.length;i++) {
for (var j=0;j<permutations.length;j++) {
var mapping = maquette.createMapping(function(source){return source;}, createTarget, updateTarget);
mapping.map(permutations[i]);
mapping.results.forEach(function(target) {target.alreadyPresent = true;});
mapping.map(permutations[j]);
}
}
// styles
var projection = maquette.dom.create(h("div", { styles: { height: "20px" } }));
projection.update(h("div", { styles: { height: null } }));
+3
View File
@@ -0,0 +1,3 @@
import { Hyperscript } from "mithril";
declare const h: Hyperscript;
export = h;
+220 -838
View File
File diff suppressed because it is too large Load Diff
-55
View File
@@ -1,55 +0,0 @@
// This is the todolist example from http://lhorie.github.io/mithril/getting-started.html
var todo = {
//the Todo class has two properties
Todo: function(data: any) {
this.description = m.prop(data.description);
this.done = m.prop(false);
},
//the TodoList class is a list of Todo's
TodoList: Array,
//the controller uses three model-level entities, of which one is a custom defined class:
//`Todo` is the central class in this application
//`list` is merely a generic array, with standard array methods
//`description` is a temporary storage box that holds a string
//
//the `add` method simply adds a new todo to the list
controller: function() {
this.list = new todo.TodoList();
this.description = m.prop("");
this.add = function() {
if (this.description()) {
this.list.push(new (<any>todo.Todo)({description: this.description()}));
this.description("");
}
}.bind(this);
},
//here's the view
view: function(ctrl: any) {
return m("html", [
m("body", [
m("input", {onchange: m.withAttr("value", ctrl.description), value: ctrl.description()} as any /* TODO remove `as any` */),
m("button", {onclick: ctrl.add} as any /* TODO remove `as any` */, "Add"),
m("table", [
ctrl.list.map(function(task: any) {
return m("tr", [
m("td", [
m("input[type=checkbox]", {onclick: m.withAttr("checked", task.done), checked: task.done()} as any /* TODO remove `as any` */)
]),
m("td", {style: {textDecoration: task.done() ? "line-through" : "none"}} as any /* TODO remove `as any` */, task.description()),
])
})
])
])
]);
},
};
//initialize the application
m.mount(document, todo);
+3
View File
@@ -0,0 +1,3 @@
import { mount as _mount } from "mithril";
declare const mount: typeof _mount;
export = mount;
+11
View File
@@ -0,0 +1,11 @@
import { redraw, render } from "mithril";
declare namespace RedrawService {
export interface Static {
render: typeof render;
redraw: typeof redraw;
}
}
declare const RedrawService: RedrawService.Static;
export = RedrawService;
+10
View File
@@ -0,0 +1,10 @@
import { render } from "mithril";
declare namespace RenderService {
export interface Static {
render: typeof render;
}
}
declare const RenderService: RenderService.Static;
export = RenderService;
+11
View File
@@ -0,0 +1,11 @@
import { request, jsonp } from "mithril";
declare namespace RequestService {
export interface Static {
request: typeof request;
jsonp: typeof jsonp;
}
}
declare const RequestService: RequestService.Static;
export = RequestService;
+3
View File
@@ -0,0 +1,3 @@
import { Route } from "mithril";
declare const route: Route;
export = route;
+42
View File
@@ -0,0 +1,42 @@
declare namespace Stream {
export interface Stream<T> {
/** Returns the value of the stream. */
(): T;
/** Sets the value of the stream. */
(value: T): this;
/** Creates a dependent stream whose value is set to the result of the callback function. */
map(f: (current: T) => Stream<T> | T | void): Stream<T>;
/** Creates a dependent stream whose value is set to the result of the callback function. */
map<U>(f: (current: T) => Stream<U> | U): Stream<U>;
/** This method is functionally identical to stream. It exists to conform to Fantasy Land's Applicative specification. */
of(val?: T): Stream<T>;
/** Apply. */
ap<U>(f: Stream<(value: T) => U>): Stream<U>;
/** A co-dependent stream that unregisters dependent streams when set to true. */
end: Stream<boolean>;
/** When a stream is passed as the argument to JSON.stringify(), the value of the stream is serialized. */
toJSON(): string;
/** Returns the value of the stream. */
valueOf(): T;
}
export interface Static {
/** Creates a stream. */
<T>(value?: T): Stream<T>;
/** Creates a computed stream that reactively updates if any of its upstreams are updated. */
combine<T>(combiner: (...streams: any[]) => T, streams: Stream<any>[]): Stream<T>;
/** Creates a stream whose value is the array of values from an array of streams. */
merge(streams: Stream<any>[]): Stream<any[]>;
/** Creates a new stream with the results of calling the function on every incoming stream with and accumulator and the incoming value. */
scan<T, U>(fn: (acc: U, value: T) => U, acc: U, stream: Stream<T>): Stream<U>;
/** Takes an array of pairs of streams and scan functions and merges all those streams using the given functions into a single stream. */
scanMerge<T,U>(pairs: [Stream<T>, (acc: U, value: T) => U][], acc: U): Stream<U>;
/** Takes an array of pairs of streams and scan functions and merges all those streams using the given functions into a single stream. */
scanMerge<U>(pairs: [Stream<any>, (acc: U, value: any) => U][], acc: U): Stream<U>;
/** A special value that can be returned to stream callbacks to halt execution of downstreams. */
readonly HALT: any;
}
}
declare const Stream: Stream.Static;
export = Stream;
+720
View File
@@ -0,0 +1,720 @@
// Typescript adaptation of mithril's test suite.
// Not intended to be run; only to compile & check types.
import * as m from 'mithril'
import * as stream from 'mithril/stream'
const FRAME_BUDGET = 100
{
const vnode = m("div")
console.assert(vnode.tag === "div")
console.assert(typeof m.version === "string")
console.assert(m.version.indexOf(".") > -1)
}
{
const vnode = m.trust("<br>")
}
{
const vnode = m.fragment({key: 123}, [m("div")])
console.assert((vnode.children as m.Vnode<any,any>[]).length === 1)
console.assert(vnode.children![0].tag === 'div')
}
{
const handler = m.withAttr("value", (value) => {})
handler({currentTarget: {value: 10}})
}
{
const params = m.parseQueryString("?a=1&b=2")
const query = m.buildQueryString({a: 1, b: 2})
}
{
const root = window.document.createElement("div")
m.render(root, m("div"))
console.assert(root.childNodes.length === 1)
}
{
const root = window.document.createElement("div")
m.mount(root, {view() {return m("div")}})
console.assert(root.childNodes.length === 1)
console.assert(root.firstChild!.nodeName === "DIV")
}
{
const root = window.document.createElement("div")
m.route(root, "/a", {
"/a": {view() {return m("div")}}
})
setTimeout(() => {
console.assert(root.childNodes.length === 1)
console.assert(root.firstChild!.nodeName === "DIV")
}, FRAME_BUDGET)
}
{
const root = window.document.createElement("div")
m.route.prefix("#")
m.route(root, "/a", {
"/a": {view() {return m("div")}}
})
setTimeout(() => {
console.assert(root.childNodes.length === 1)
console.assert(root.firstChild!.nodeName === "DIV")
}, FRAME_BUDGET)
}
{
const root = window.document.createElement("div")
m.route(root, "/a", {
"/a": {view() {return m("div")}}
})
setTimeout(() => {
console.assert(m.route.get() === "/a")
}, FRAME_BUDGET)
}
{
const root = window.document.createElement("div")
m.route(root, "/a", {
"/:id": {view() {return m("div")}}
})
setTimeout(() => {
m.route.set("/b")
setTimeout(() => {
console.assert(m.route.get() === "/b")
}, FRAME_BUDGET)
}, FRAME_BUDGET)
}
{
let count = 0
const root = window.document.createElement("div")
m.mount(root, {view() {count++}})
setTimeout(() => {
m.redraw()
console.assert(count === 2)
}, FRAME_BUDGET)
}
//
// Additional tests by andraaspar
//
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/hyperscript.html#components
////////////////////////////////////////////////////////////////////////////////
{
// define a component
const Greeter: m.Comp<{}, {}> = {
view(vnode) {
return m("div", vnode.attrs, ["Hello ", vnode.children])
}
}
// consume it
m(Greeter, { style: "color:red;" }, "world")
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/hyperscript.html#keys
////////////////////////////////////////////////////////////////////////////////
{
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Mary" },
]
const userInputs = function(users: { id: number, name: string }[]) {
return users.map(u => {
return m("input", { key: u.id }, u.name)
})
}
m.render(document.body, userInputs(users))
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/components.html#state
////////////////////////////////////////////////////////////////////////////////
{
const ComponentWithInitialState: m.Comp<{}, {data: string}> = {
data: "Initial content",
view(vnode) {
return m("div", vnode.state.data)
}
}
m(ComponentWithInitialState)
}
{
const ComponentWithDynamicState: m.Comp<{text: string}, {data?: string}> = {
oninit(vnode) {
vnode.state.data = vnode.attrs.text
},
view(vnode) {
return m("div", vnode.state.data)
}
}
m(ComponentWithDynamicState, { text: "Hello" })
}
{
const ComponentUsingThis: m.Comp<{text: string}, {data?: string}> = {
oninit(vnode) {
this.data = vnode.attrs.text
},
view(vnode) {
return m("div", this.data)
}
}
m(ComponentUsingThis, { text: "Hello" })
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/lifecycle-methods.html
////////////////////////////////////////////////////////////////////////////////
{
const Fader: m.Comp<{}, {}> = {
onbeforeremove(vnode) {
vnode.dom.classList.add("fade-out")
return new Promise(resolve => {
setTimeout(resolve, 1000)
})
},
view() {
return m("div", "Bye")
},
}
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/route.html#wrapping-a-layout-component
////////////////////////////////////////////////////////////////////////////////
{
const Home = {
view() {
return "Welcome"
}
}
const state = {
term: "",
search() {
// save the state for this route
// this is equivalent to `history.replaceState({term: state.term}, null, location.href)`
m.route.set(m.route.get(), null, { replace: true, state: { term: state.term } })
// navigate away
location.href = "https://google.com/?q=" + state.term
}
}
const Form: m.Comp<{term: string}, {}> = {
oninit(vnode) {
state.term = vnode.attrs.term || "" // populated from the `history.state` property if the user presses the back button
},
view() {
return m("form", [
m("input[placeholder='Search']", { oninput: m.withAttr("value", v => { state.term = v }), value: state.term }),
m("button", { onclick: state.search }, "Search")
])
}
}
const Layout: m.Comp<{}, {}> = {
view(vnode) {
return m(".layout", vnode.children)
}
}
// example 1
m.route(document.body, "/", {
"/": {
view() {
return m(Layout, m(Home))
},
},
"/form": {
view() {
return m(Layout, m(Form))
},
}
})
// example 2
m.route(document.body, "/", {
"/": {
render() {
return m(Layout, m(Home))
},
},
"/form": {
render() {
return m(Layout, m(Form))
},
}
})
// functionally equivalent to example 1
const Anon1 = {
view() {
return m(Layout, m(Home))
},
}
const Anon2 = {
view() {
return m(Layout, m(Form))
},
}
m.route(document.body, "/", {
"/": {
render() {
return m(Anon1)
}
},
"/form": {
render() {
return m(Anon2)
}
},
})
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/route.html#preloading-data
////////////////////////////////////////////////////////////////////////////////
{
const state = {
users: [] as any[],
loadUsers() {
return m.request<any>("/api/v1/users").then(users => {
state.users = users
})
}
}
m.route(document.body, "/user/list", {
"/user/list": {
onmatch: state.loadUsers,
render() {
return state.users.map(user => m("div", user.id))
}
},
})
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/request.html#monitoring-progress
////////////////////////////////////////////////////////////////////////////////
{
let progress = 0
m.mount(document.body, {
view() {
return [
m("input[type=file]", { onchange: upload }),
progress + "% completed"
]
}
})
const upload = function(e: Event) {
const file = ((e.target as HTMLInputElement).files as FileList)[0]
const data = new FormData()
data.append("myfile", file)
m.request({
method: "POST",
url: "/api/v1/upload",
data,
config: xhr => {
xhr.addEventListener("progress", e => {
progress = e.loaded / e.total
m.redraw() // tell Mithril that data changed and a re-render is needed
})
}
})
}
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/request.html#casting-response-to-a-type
////////////////////////////////////////////////////////////////////////////////
{
// Start rewrite to TypeScript
class User {
name: string;
constructor(data: any) {
this.name = data.firstName + " " + data.lastName
}
}
// End rewrite to TypeScript
// function User(data) {
// this.name = data.firstName + " " + data.lastName
// }
m.request<User[]>({
method: "GET",
url: "/api/v1/users",
type: User
})
.then(users => {
console.log(users[0].name) // logs a name
})
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/request.html#non-json-responses
////////////////////////////////////////////////////////////////////////////////
{
m.request<string>({
method: "GET",
url: "/files/icon.svg",
deserialize: value => value
})
.then(svg => {
m.render(document.body, m.trust(svg))
})
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/jsonp.html
////////////////////////////////////////////////////////////////////////////////
{
m.jsonp({
url: "/api/v1/users/:id",
data: { id: 1 },
callbackKey: "callback",
})
.then(result => {
console.log(result)
})
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/fragment.html
////////////////////////////////////////////////////////////////////////////////
{
const groupVisible = true
const log = function() {
console.log("group is now visible")
}
m("ul", [
m("li", "child 1"),
m("li", "child 2"),
groupVisible ? m.fragment({ oninit: log }, [
// a fragment containing two elements
m("li", "child 3"),
m("li", "child 4"),
]) : null
])
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/stream.html#computed-properties
////////////////////////////////////////////////////////////////////////////////
{
const firstName = stream("John")
const lastName = stream("Doe")
const fullName = stream.merge([firstName, lastName]).map(values => {
return values.join(" ")
})
console.log(fullName()) // logs "John Doe"
firstName("Mary")
console.log(fullName()) // logs "Mary Doe"
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/stream.html#chaining-streams
////////////////////////////////////////////////////////////////////////////////
{
const halted = stream(1).map(value => {
return stream.HALT
})
halted.map(() => {
// never runs
})
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/stream.html#combining-streams
////////////////////////////////////////////////////////////////////////////////
{
const a = stream(5)
const b = stream(7)
const added = stream.combine((a: stream.Stream<number>, b: stream.Stream<number>) => {
return a() + b()
}, [a, b])
console.log(added()) // logs 12
}
////////////////////////////////////////////////////////////////////////////////
// http://mithril.js.org/stream.html#ended-state
////////////////////////////////////////////////////////////////////////////////
{
const value = stream<number>()
const doubled = value.map(value => value * 2)
value.end(true) // set to ended state
value(5)
console.log(doubled())
}
////////////////////////////////////////////////////////////////////////////////
// https://github.com/lhorie/mithril.js/blob/master/examples/animation/mosaic.html
////////////////////////////////////////////////////////////////////////////////
// Excerpt
{
const root = document.getElementById("root")!
const empty: any[] = []
const full: any[] = []
for (let i = 0; i < 100; i++) full.push(i)
let cells: any[]
const view = function() {
return m(".container", cells.map(i => {
return m(".slice", {
style: {backgroundPosition: (i % 10 * 11) + "% " + (Math.floor(i / 10) * 11) + "%"},
onbeforeremove: exit
})
}))
}
const exit = function(vnode: m.VnodeDOM<any, any>) {
vnode.dom.classList.add("exit")
return new Promise(resolve => {
setTimeout(resolve, 1000)
})
}
const run = function() {
cells = cells === full ? empty : full
m.render(root, [view()])
setTimeout(run, 2000)
}
run()
}
////////////////////////////////////////////////////////////////////////////////
// https://github.com/lhorie/mithril.js/blob/master/examples/editor/index.html
////////////////////////////////////////////////////////////////////////////////
// Excerpt
{
// Start extra declarations
const marked = (v: string) => v
// End extra declarations
// model
const state = {
text: "# Markdown Editor\n\nType on the left panel and see the result on the right panel",
update(value: string) {
state.text = value
}
}
// view
const Editor = {
view() {
return [
m("textarea.input", {
oninput: m.withAttr("value", state.update),
value: state.text
}),
m(".preview", m.trust(marked(state.text))),
]
}
}
m.mount(document.getElementById("editor")!, Editor)
}
////////////////////////////////////////////////////////////////////////////////
// https://github.com/lhorie/mithril.js/blob/master/examples/todomvc/todomvc.js
////////////////////////////////////////////////////////////////////////////////
{
// model
const state = {
dispatch(action: string, args?: any) {
(state as any)[action].apply(state, args || [])
requestAnimationFrame(() => {
localStorage["todos-mithril"] = JSON.stringify(state.todos)
})
},
todos: JSON.parse(localStorage["todos-mithril"] || "[]"),
editing: null as any,
filter: "",
remaining: 0,
todosByStatus: [] as any[],
showing: undefined as any,
createTodo(title: string) {
state.todos.push({title: title.trim(), completed: false})
},
setStatuses(completed: boolean) {
for (let i = 0; i < state.todos.length; i++) state.todos[i].completed = completed
},
setStatus(todo: any, completed: boolean) {
todo.completed = completed
},
destroy(todo: any) {
const index = state.todos.indexOf(todo)
if (index > -1) state.todos.splice(index, 1)
},
clear() {
for (let i = 0; i < state.todos.length; i++) {
if (state.todos[i].completed) state.destroy(state.todos[i--])
}
},
edit(todo: any) {
state.editing = todo
},
update(title: string) {
if (state.editing != null) {
state.editing.title = title.trim()
if (state.editing.title === "") state.destroy(state.editing)
state.editing = null
}
},
reset() {
state.editing = null
},
computed(vnode: m.Vnode<any, any>) {
state.showing = vnode.attrs.status || ""
state.remaining = state.todos.filter((todo: any) => !todo.completed).length
state.todosByStatus = state.todos.filter((todo: any) => {
switch (state.showing) {
case "": return true
case "active": return !todo.completed
case "completed": return todo.completed
}
})
}
}
// view
const Todos: m.Comp<{}, {
add(e: Event): void
toggleAll(): void
toggle(todo: any): void
focus(vnode: m.VnodeDOM<any, any>, todo: any): void
save(e: KeyboardEvent): void
}> = {
add(e: KeyboardEvent) {
if (e.keyCode === 13) {
state.dispatch("createTodo", [(e.target as HTMLInputElement).value]);
(e.target as HTMLInputElement).value = ""
}
},
toggleAll() {
state.dispatch("setStatuses", [(document.getElementById("toggle-all") as HTMLInputElement).checked])
},
toggle(todo: any) {
state.dispatch("setStatus", [todo, !todo.completed])
},
focus(vnode: m.VnodeDOM<any, any>, todo: any) {
if (todo === state.editing && vnode.dom !== document.activeElement) {
const el = vnode.dom as HTMLInputElement
el.value = todo.title
el.focus()
el.selectionStart = el.selectionEnd = todo.title.length
}
},
save(e: KeyboardEvent) {
if (e.keyCode === 13 || e.type === "blur") state.dispatch("update", [(e.target as HTMLInputElement).value])
else if (e.keyCode === 27) state.dispatch("reset")
},
oninit: state.computed,
onbeforeupdate: state.computed,
view(vnode) {
const ui = vnode.state
return [
m("header.header", [
m("h1", "todos"),
m("input#new-todo[placeholder='What needs to be done?'][autofocus]", {onkeypress: ui.add}),
]),
m("section#main", {style: {display: state.todos.length > 0 ? "" : "none"}}, [
m("input#toggle-all[type='checkbox']", {checked: state.remaining === 0, onclick: ui.toggleAll}),
m("label[for='toggle-all']", {onclick: ui.toggleAll}, "Mark all as complete"),
m("ul#todo-list", [
state.todosByStatus.map((todo: any) => {
return m("li", {class: (todo.completed ? "completed" : "") + " " + (todo === state.editing ? "editing" : "")}, [
m(".view", [
m("input.toggle[type='checkbox']", {checked: todo.completed, onclick: () => {ui.toggle(todo)}}),
m("label", {ondblclick: () => {state.dispatch("edit", [todo])}}, todo.title),
m("button.destroy", {onclick: () => {state.dispatch("destroy", [todo])}}),
]),
m("input.edit", {onupdate(vnode: m.VnodeDOM<any, any>) {ui.focus(vnode, todo)}, onkeypress: ui.save, onblur: ui.save})
])
}),
]),
]),
state.todos.length ? m("footer#footer", [
m("span#todo-count", [
m("strong", state.remaining),
state.remaining === 1 ? " item left" : " items left",
]),
m("ul#filters", [
m("li", m("a[href='/']", {oncreate: m.route.link, class: state.showing === "" ? "selected" : ""}, "All")),
m("li", m("a[href='/active']", {oncreate: m.route.link, class: state.showing === "active" ? "selected" : ""}, "Active")),
m("li", m("a[href='/completed']", {oncreate: m.route.link, class: state.showing === "completed" ? "selected" : ""}, "Completed")),
]),
m("button#clear-completed", {onclick: () => {state.dispatch("clear")}}, "Clear completed"),
]) : null,
]
}
}
m.route(document.getElementById("todoapp")!, "/", {
"/": Todos,
"/:status": Todos,
})
}
+135
View File
@@ -0,0 +1,135 @@
import * as m from 'mithril'
import {ClassComponent, CVnode, CVnodeDOM} from 'mithril'
///////////////////////////////////////////////////////////
// 0.
// Simplest component example - no attrs or state.
//
class Comp0 implements ClassComponent<{}> {
constructor (vnode: CVnode<{}>) {
}
view() {
return m('span', "Test")
}
}
// Mount the component
m.mount(document.getElementById('comp0')!, Comp0)
// Unmount the component
m.mount(document.getElementById('comp0')!, null)
///////////////////////////////////////////////////////////
// 1.
// Simple example with lifecycle methods.
//
class Comp1 implements ClassComponent<{}> {
oninit (vnode: CVnode<{}>) {
}
oncreate ({dom}: CVnodeDOM<{}>) {
}
view (vnode: CVnode<{}>) {
return m('span', "Test")
}
}
///////////////////////////////////////////////////////////
// 2.
// Component with attrs type
//
interface Comp2Attrs {
title: string
description: string
}
class Comp2 implements ClassComponent<Comp2Attrs> {
view ({attrs: {title, description}}: CVnode<Comp2Attrs>) {
return [m('h2', title), m('p', description)]
}
}
///////////////////////////////////////////////////////////
// 3.
// Declares attrs type inline.
// Uses comp2 with typed attrs and makes use of `onremove`
// lifecycle method.
//
class Comp3 implements ClassComponent<{pageHead: string}> {
oncreate ({dom}: CVnodeDOM<{pageHead: string}>) {
// Can do stuff with dom
}
view ({attrs}: CVnode<{pageHead: string}>) {
return m('.page',
m('h1', attrs.pageHead),
m(Comp2,
{
// attrs is type checked - nice!
title: "A Title",
description: "Some descriptive text.",
onremove: (vnode) => {
// Vnode type is inferred
console.log("comp2 was removed")
},
}
),
// Test other hyperscript parameter variations
m(Comp1, m(Comp1)),
m('br')
)
}
}
///////////////////////////////////////////////////////////
// 4.
// Typed attrs, component with state, methods
//
interface Comp4Attrs {
name: string
}
class Comp4 implements ClassComponent<Comp4Attrs> {
count: number
constructor (vnode: CVnode<Comp4Attrs>) {
this.count = 0
}
add (num: number) {
this.count += num
}
view ({attrs}: CVnode<Comp4Attrs>) {
return [
m('h1', `This ${attrs.name} has been clicked ${this.count} times`),
m('button',
{
onclick: () => this.add(1)
},
"Click me")
]
}
}
///////////////////////////////////////////////////////////
//
// Test that all are mountable components
//
m.route(document.body, '/', {
'/comp0': Comp0,
'/comp1': Comp1,
'/comp2': Comp2,
'/comp3': Comp3,
'/comp4': Comp4
})
///////////////////////////////////////////////////////////
//
// Concise module example with default export
//
export interface Attrs {
name: string
}
export default class MyComponent implements ClassComponent<Attrs> {
count = 0
view ({attrs}: CVnode<Attrs>) {
return m('span', `name: ${attrs.name}, count: ${this.count}`)
}
}
+159
View File
@@ -0,0 +1,159 @@
import * as m from 'mithril'
import {Component, Comp} from 'mithril'
///////////////////////////////////////////////////////////
// 0.
// Simplest component example - no attrs or state.
//
const comp0 = {
view() {
return m('span', "Test")
}
}
// Mount the component
m.mount(document.getElementById('comp0')!, comp0)
// Unmount the component
m.mount(document.getElementById('comp0')!, null)
///////////////////////////////////////////////////////////
// 1.
// Simple example. Vnode type for component methods is inferred.
//
const comp1: Component<{},{}> = {
oncreate ({dom}) {
// vnode.dom type inferred
},
view (vnode) {
return m('span', "Test")
}
}
///////////////////////////////////////////////////////////
// 2.
// Component with attrs
//
interface Comp2Attrs {
title: string
description: string
}
const comp2: Component<Comp2Attrs,{}> = {
view ({attrs: {title, description}}) { // Comp2Attrs type is inferred
return [m('h2', title), m('p', description)]
}
}
///////////////////////////////////////////////////////////
// 3.
// Declares attrs type inline.
// Uses comp2 with typed attrs and makes use of `onremove`
// lifecycle method.
//
const comp3: Component<{pageHead: string},{}> = {
oncreate ({dom}) {
// Can do stuff with dom
},
view ({attrs}) {
return m('.page',
m('h1', attrs.pageHead),
m(comp2,
{
// attrs is type checked - nice!
title: "A Title",
description: "Some descriptive text.",
onremove: (vnode) => {
console.log("comp2 was removed")
},
}
),
// Test other hyperscript parameter variations
m(comp1, m(comp1)),
m('br')
)
}
}
///////////////////////////////////////////////////////////
// 4.
// Typed attrs and state, and `this` type is inferred.
//
interface Comp4Attrs {
name: string
}
interface Comp4State {
count: number
add(this: Comp4State, num: number): void
}
// Either of these two Comp4 defs will work:
type Comp4 = Component<Comp4Attrs,Comp4State> & Comp4State
// interface Comp4 extends Component<Comp4Attrs,Comp4State>, Comp4State {}
const comp4: Comp4 = {
count: 0, // <- Must be declared to satisfy Comp4 type which includes Comp4State type
add (num) {
// num and this types inferred
this.count += num
},
oninit() {
this.count = 0
},
view ({attrs}) {
return [
m('h1', `This ${attrs.name} has been clicked ${this.count} times`),
m('button',
{
// 'this' is typed!
onclick: () => this.add(1)
},
"Click me")
]
}
}
///////////////////////////////////////////////////////////
// 5.
// Stateful component (Equivalent to Comp4 example.)
// Avoids the use of `this` completely; state manipulated
// through vnode.state.
//
const comp5: Component<Comp4Attrs,Comp4State> = {
oninit ({state}) {
state.count = 0
state.add = num => {state.count += num}
},
view ({attrs, state}) {
return [
m('h1', `This ${attrs.name} has been clicked ${state.count} times`),
m('button',
{
onclick: () => {state.add(1)}
},
"Click me"
)
]
}
}
///////////////////////////////////////////////////////////
//
// Concise module example with default export
//
interface Attrs {
name: string
}
interface State {
count: number
}
export default {
count: 0,
view ({attrs}) {
return m('span', `name: ${attrs.name}, count: ${this.count}`)
}
} as Comp<Attrs,State>
// Using the Comp type will apply the State intersection type for us.
@@ -0,0 +1,179 @@
import * as m from 'mithril'
import {Component, FactoryComponent, Vnode} from 'mithril'
///////////////////////////////////////////////////////////
// 0.
// Simplest component example - no attrs or state.
//
function comp0() {
return {
view() {
return m('span', "Test")
}
}
}
// Mount the component
m.mount(document.getElementById('comp0')!, comp0)
// Unmount the component
m.mount(document.getElementById('comp0')!, null)
///////////////////////////////////////////////////////////
// 1.
// Simple example. Vnode type for component methods is inferred.
//
function comp1() {
return {
oncreate ({dom}) {
// vnode.dom type inferred
},
view (vnode) {
return m('span', "Test")
}
} as Component<{},{}>
}
///////////////////////////////////////////////////////////
// 2.
// Component with attrs type. Different type annotation
// style to infer factory vnode type.
//
interface Comp2Attrs {
title: string
description: string
}
const comp2 = function (vnode) { // vnode is inferred
return {
view ({attrs: {title, description}}) { // Comp2Attrs type is inferred
return [m('h2', title), m('p', description)]
}
}
} as FactoryComponent<Comp2Attrs>
///////////////////////////////////////////////////////////
// 3.
// Declares attrs type inline.
// Uses comp2 with typed attrs and makes use of `onremove`
// lifecycle method.
//
const comp3 = function() {
return {
oncreate ({dom}) {
// Can do stuff with dom
},
view ({attrs}) {
return m('.page',
m('h1', attrs.pageHead),
m(comp2,
{
// attrs is type checked - nice!
title: "A Title",
description: "Some descriptive text.",
onremove: (vnode) => {
console.log("comp2 was removed")
},
}
),
// Test other hyperscript parameter variations
m(comp1, m(comp1)),
m('br')
)
}
}
} as FactoryComponent<{pageHead: string}>
///////////////////////////////////////////////////////////
// 4.
// Stateful component using closure method & var
// to hold state.
//
interface Comp4Attrs {
name: string
}
function comp4(): Component<Comp4Attrs,{}> {
let count = 0
function add (num: number) {
count += num
}
return {
oninit() {
count = 0
},
view ({attrs}) {
return [
m('h1', `This ${attrs.name} has been clicked ${count} times`),
m('button',
{
onclick: () => add(1)
},
"Click me"
)
]
}
}
}
///////////////////////////////////////////////////////////
// 5.
// Stateful component (Equivalent to Comp4 example.)
// Uses vnode.state instead of closure.
//
interface Comp5State {
count: number
add (num: number): void
}
function comp5(): Component<Comp4Attrs,Comp5State> {
return {
oninit ({state}) {
state.count = 0
state.add = num => {state.count += num}
},
view ({attrs, state}) {
return [
m('h1', `This ${attrs.name} has been clicked ${state.count} times`),
m('button',
{
onclick: () => {state.add(1)}
},
"Click me"
)
]
}
}
}
///////////////////////////////////////////////////////////
//
// Test that all are mountable components
//
m.route(document.body, '/', {
'/comp0': comp0,
'/comp1': comp1,
'/comp2': comp2,
'/comp3': comp3,
'/comp4': comp4,
'/comp5': comp5
})
///////////////////////////////////////////////////////////
//
// Concise module example with default export
//
interface Attrs {
name: string
}
export default (): Component<Attrs,{}> => {
let count = 0
return {
view ({attrs}) {
return m('span', `name: ${attrs.name}, count: ${count}`)
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import * as m from 'mithril'
import {Vnode} from 'mithril/'
import * as h from 'mithril/hyperscript'
const vnode = m.fragment({id: 'abc'}, ['test'])
m.fragment({}, ['Test', 123])
m.fragment(
{
id: 'abc',
oninit: (vnode: Vnode<any,any>) => {
console.log('oninit')
}
},
[h('p', 'test1'), [123, h('p', 'abc'), ['abc']], 'Abc', h('p', 'test2')]
)
+27
View File
@@ -0,0 +1,27 @@
import {jsonp} from 'mithril/request'
interface Result {
id: number
}
jsonp<Result>('/item').then(data => {
console.log(data.id)
})
class User {
id: number
constructor (result: Result) {
this.id = result.id
}
}
jsonp<User>({
url: '/user',
data: {test: 'abc'},
type: User,
callbackName: 'getuser',
callbackKey: 'key',
background: true
}).then(user => {
console.log(user.id)
})
+23
View File
@@ -0,0 +1,23 @@
import {trust, parseQueryString, buildQueryString} from 'mithril'
import * as h from 'mithril/hyperscript'
import {render} from 'mithril/render'
import {redraw} from 'mithril/redraw'
import * as withAttr from 'mithril/withAttr'
const vnode = trust('Some <strong>bold</strong> text.')
const params = parseQueryString('?id=123')
const qstr = buildQueryString({id: 123})
render(document.body, 'Hello')
render(document.body, h('h1', 'Test'))
render(document.body, [
h('h1', 'Test'), "abc", null, 123, false, h('p', 'Vnode array'),
['a', 123, undefined, h('div', 'Nested')]
])
redraw()
const handler = withAttr("value", (value) => {})
handler({currentTarget: {value: 10}})
+73
View File
@@ -0,0 +1,73 @@
import {request} from 'mithril/request'
interface Result {
id: number
}
request<Result>({method: "GET", url: "/item"}).then(result => {
console.log(result.id)
})
request<{a: string}>("/item", {method: "POST"}).then(result => {
console.log(result.a)
})
request<any>({
method: "GET",
url: "/item",
data: {x: "y"}
}).then(result => {
console.log(result)
})
request<Result>({
method: "GET",
url: "/item",
data: 5,
serialize: (data: number) => "id=" + data.toString()
}).then(result => {
console.log(result)
})
request<Result>('/item', {
method: "GET",
deserialize: str => JSON.parse(str) as Result
}).then(result => {
console.log(result.id)
})
request<Result>('/id', {
method: "GET",
extract: xhr => ({id: Number(xhr.responseText)})
}).then(result => {
console.log(result.id)
})
request<Result>('/item', {
config: xhr => {
xhr.setRequestHeader('accept', '*')
},
headers: {"Content-Type": "application/json"},
background: true,
}).then(result => {
console.log(result.id)
})
class Item {
identifier: number
constructor(result: Result) {
this.identifier = result.id
}
}
request<Item>('/item', {
method: 'GET',
async: true,
user: "Me",
password: "qwerty",
withCredentials: true,
type: Item,
useBody: false
}).then(item => {
console.log(item.identifier)
})
+60
View File
@@ -0,0 +1,60 @@
import {Component} from 'mithril'
import * as h from 'mithril/hyperscript'
import * as route from 'mithril/route'
const component1 = {
view() {
return h('h1', 'Test')
}
}
const component2 = {
view ({attrs: {title}}) {
return h('h1', title)
}
} as Component<{title: string},{}>
route(document.body, '/', {
'/': component1,
'/test1': {
onmatch (args, path) {
return component1
}
},
'/test2': {
render(vnode) {
return h(component1)
}
},
'test3': {
onmatch (args, path) {
return component2
},
render (vnode) {
return ['abc', 123, null, h(component2), ['nested', h('p', 123)]]
}
},
'test4': {
onmatch (args, path) {
// Must provide a Promise type if we want type checking
return new Promise<Component<{title: string},{}>>((resolve, reject) => {
resolve(component2)
})
}
}
})
route.prefix('/app')
route.set('/test1')
route.set('/test/:id', {id: 1})
route.set('/test2', undefined, {
replace: true,
state: {abc: 123},
title: "Title"
})
const path: string = route.get()
const fn = route.link(h('div', 'test'))
+391
View File
@@ -0,0 +1,391 @@
import * as stream from 'mithril/stream'
import {Stream} from 'mithril/stream'
{
const s = stream(1)
const initialValue = s()
s(2)
const newValue = s()
console.assert(initialValue === 1)
console.assert(newValue === 2)
}
{
const s = stream()
console.assert(s() === undefined)
}
{
const s: Stream<number | undefined> = stream(1)
s(undefined)
console.assert(s() === undefined)
}
{
const s = stream(stream(1))
console.assert(s()() === 1)
}
{
const s = stream()
const doubled = stream.combine(function(s) {return s() * 2}, [s])
s(2)
console.assert(doubled() === 4)
}
{
const s = stream(2)
const doubled = stream.combine(function(s) {return s() * 2}, [s])
console.assert(doubled() === 4)
}
{
const s1 = stream()
const s2 = stream()
const added = stream.combine(function(s1, s2) {return s1() + s2()}, [s1, s2])
s1(2)
s2(3)
console.assert(added() === 5)
}
{
const s1 = stream(2)
const s2 = stream(3)
const added = stream.combine(function(s1, s2) {return s1() + s2()}, [s1, s2])
console.assert(added() === 5)
}
{
const s1 = stream(2)
const s2 = stream()
const added = stream.combine(function(s1, s2) {return s1() + s2()}, [s1, s2])
s2(3)
console.assert(added() === 5)
}
{
let count = 0
const a = stream()
const b = stream.combine(function(a) {return a() * 2}, [a])
const c = stream.combine(function(a) {return a() * a()}, [a])
const d = stream.combine(function(b, c) {
count++
return b() + c()
}, [b, c])
a(3)
console.assert(d() === 15)
console.assert(count === 1)
}
{
let count = 0
const a = stream(3)
const b = stream.combine(function(a) {return a() * 2}, [a])
const c = stream.combine(function(a) {return a() * a()}, [a])
const d = stream.combine(function(b, c) {
count++
return b() + c()
}, [b, c])
console.assert(d() === 15)
console.assert(count === 1)
}
{
let streams: Stream<any>[] = []
const a = stream()
const b = stream()
const c = stream.combine(function(a, b, changed) {
streams = changed
}, [a, b])
a(3)
b(5)
console.assert(streams.length === 1)
console.assert(streams[0] === b)
}
{
let streams: Stream<number>[] = []
const a = stream(3)
const b = stream(5)
const c = stream.combine(function(a, b, changed) {
streams = changed
}, [a, b])
a(7)
console.assert(streams.length === 1)
console.assert(streams[0] === a)
}
{
const a = stream(1)
const b = stream.combine(function(a) {
return undefined
}, [a])
console.assert(b() === undefined)
}
{
const a = stream(1)
const b = stream.combine(function(a) {
return stream(2)
}, [a])
console.assert(b()() === 2)
}
{
const a = stream(1)
const b = stream.combine(function(a) {
return stream()
}, [a])
console.assert(b()() === undefined)
}
{
let count = 0
const a = stream(1)
const b = stream.combine(function(a) {
return stream.HALT
}, [a])
["fantasy-land/map"](function() {
count++
return 1
})
console.assert(b() === undefined)
}
{
const all = stream.merge([
stream(10),
stream("20"),
stream({value: 30}),
])
}
{
const straggler = stream()
const all = stream.merge([
stream(10),
stream("20"),
straggler,
])
console.assert(all() === undefined)
straggler(30)
}
{
let value = 0
const id = function(value: number) {return value}
const a = stream<number>()
const b = stream<number>()
const all = stream.merge([a.map(id), b.map(id)]).map(function(data) {
value = data[0] + data[1]
})
a(1)
b(2)
console.assert(value === 3)
a(3)
b(4)
console.assert(value === 7)
}
{
const s = stream()
const doubled = stream.combine(function(stream) {return stream() * 2}, [s])
s.end(true)
s(3)
console.assert(doubled() === undefined)
}
{
const s = stream(2)
const doubled = stream.combine(function(stream) {return stream() * 2}, [s])
s.end(true)
s(3)
console.assert(doubled() === 4)
}
{
const s = stream(2)
s.end(true)
const doubled = stream.combine(function(stream) {return stream() * 2}, [s])
s(3)
console.assert(doubled() === undefined)
}
{
const s = stream(2)
const doubled = stream.combine(function(stream) {return stream() * 2}, [s])
doubled.end(true)
s(4)
console.assert(doubled() === 4)
}
{
const s = stream<number>()
const doubled = s["fantasy-land/map"](function(value: number) {return value * 2})
s(3)
console.assert(doubled() === 6)
}
{
const s = stream(3)
const doubled = s["fantasy-land/map"](function(value: number) {return value * 2})
console.assert(doubled() === 6)
}
{
const s = stream<undefined>()
const mapped = s["fantasy-land/map"](function(value: undefined) {return String(value)})
s(undefined)
console.assert(mapped() === "undefined")
}
{
const s = stream(undefined)
const mapped = s["fantasy-land/map"](function(value: undefined) {return String(value)})
console.assert(mapped() === "undefined")
}
{
const s = stream(undefined)
const mapped = s["fantasy-land/map"](function(value: undefined) {return stream()})
console.assert(mapped()() === undefined)
}
{
const s = stream(undefined)
console.assert(s["fantasy-land/map"] === s.map)
}
{
const apply = stream(function(value: number) {return value * 2})
const s = stream(3)
const applied = s["fantasy-land/ap"](apply)
console.assert(applied() === 6)
apply(function(value) {return value / 3})
console.assert(applied() === 1)
s(9)
console.assert(applied() === 3)
}
{
const apply = stream(function(value: undefined) {return String(value)})
const s = stream(undefined)
const applied = s["fantasy-land/ap"](apply)
console.assert(applied() === "undefined")
apply(function(value) {return String(value) + "a"})
console.assert(applied() === "undefineda")
}
{
const s = stream(3)
const mapped = s["fantasy-land/map"](function(value: number) {return value})
console.assert(s() === mapped())
}
{
const f = function f(x: number) {return x * 2}
const g = function g(x: number) {return x * x}
const s = stream(3)
const mapped = s["fantasy-land/map"](function(value: any) {return f(g(value))})
const composed = s["fantasy-land/map"](g)["fantasy-land/map"](f)
console.assert(mapped() === 18)
console.assert(mapped() === composed())
}
{
const a = stream(function(value: number) {return value * 2})
const u = stream(function(value: number) {return value * 3})
const v = stream(5)
const mapped = v["fantasy-land/ap"](u["fantasy-land/ap"](a["fantasy-land/map"](function(f: any) {
return function(g: any) {
return function(x: any) {
return f(g(x))
}
}
})))
const composed = v["fantasy-land/ap"](u)["fantasy-land/ap"](a)
console.assert(mapped() === 30)
console.assert(mapped() === composed())
}
{
const a = stream()["fantasy-land/of"](function(value: number) {return value})
const v = stream(5)
console.assert(v["fantasy-land/ap"](a)() === 5)
console.assert(v["fantasy-land/ap"](a)() === v())
}
{
const a = stream(0)
const f = function(value: number) {return value * 2}
const x = 3
console.assert(a["fantasy-land/of"](x)["fantasy-land/ap"](a["fantasy-land/of"](f))() === 6)
console.assert(a["fantasy-land/of"](x)["fantasy-land/ap"](a["fantasy-land/of"](f))() === a["fantasy-land/of"](f(x))())
}
{
const u = stream(function(value: number) {return value * 2})
const a = stream()
const y = 3
console.assert(a["fantasy-land/of"](y)["fantasy-land/ap"](u)() === 6)
console.assert(a["fantasy-land/of"](y)["fantasy-land/ap"](u)() === u["fantasy-land/ap"](a["fantasy-land/of"](function(f: any) {return f(y)}))())
}
// scan
{
const parent = stream<number>()
const child = stream.scan((out, p) => out - p, 123, parent)
}
{
const parent = stream<number>()
const child = stream.scan((arr, p) => arr.concat(p), [] as number[], parent)
parent(7)
}
// scanMerge
{
const parent1 = stream<number>()
const parent2 = stream<number>()
const child = stream.scanMerge([
[parent1, (out, p1) => out + p1],
[parent2, (out, p2) => out + p2]
], -10)
}
{
const parent1 = stream<string>()
const parent2 = stream<string>()
const child = stream.scanMerge([
[parent1, (out, p1) => out + p1],
[parent2, (out, p2) => out + p2 + p2]
], "a")
parent1("b")
parent2("c")
parent1("b")
console.assert(child() === 'abccb')
}
{
const parent1 = stream<string>()
const parent2 = stream<number>()
const child = stream.scanMerge([
[parent1, (out, p1) => out + p1],
[parent2, (out, p2) => out + p2 + p2]
], "a")
parent1("a")
parent2(1)
console.assert(child() === 'aa11')
}
+38 -22
View File
@@ -1,23 +1,39 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": false,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"mithril-tests.ts"
]
}
"compilerOptions": {
"module": "commonjs",
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": []
},
"files": [
"test/test-api.ts",
"test/test-class-component.ts",
"test/test-component.ts",
"test/test-factory-component.ts",
"test/test-fragment.ts",
"test/test-jsonp.ts",
"test/test-misc.ts",
"test/test-request.ts",
"test/test-route.ts",
"test/test-stream.ts",
"index.d.ts",
"hyperscript.d.ts",
"mount.d.ts",
"redraw.d.ts",
"render.d.ts",
"request.d.ts",
"route.d.ts",
"withAttr.d.ts",
"stream/index.d.ts"
],
"atom": {
"rewriteTsconfig": false
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"extends": "../tslint.json",
"rules": {
"array-type": [false, "array"],
"quotemark": [false, "double"],
"semicolon": [false, "always"],
"space-before-function-paren": [false, "always"],
"max-line-length": [false, 200],
"no-empty-interface": false,
"no-redundant-modifiers": false,
"only-arrow-functions": [false],
"prefer-for-of": false,
"unified-signatures": false,
"whitespace": [
false,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
]
}
}
+3
View File
@@ -0,0 +1,3 @@
import { withAttr as _withAttr } from "mithril";
declare const withAttr: typeof _withAttr;
export = withAttr;
+8 -166
View File
@@ -6,10 +6,14 @@
// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/
/// <reference types="node" />
/// <reference types="bson" />
import {EventEmitter} from 'events';
import { ObjectID } from 'bson';
import { EventEmitter } from 'events';
import { Readable, Writable } from "stream";
export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, Timestamp } from 'bson';
// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html
export class MongoClient {
constructor();
@@ -240,8 +244,6 @@ export class Db extends EventEmitter {
stats(options: { scale?: number }, callback: MongoCallback<any>): void;
}
// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html
export class Server extends EventEmitter {
constructor(host: string, port: number, options?: ServerOptions);
@@ -403,166 +405,6 @@ export interface FSyncOptions {
fsync?: boolean
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html
export class ObjectID {
constructor(s?: string | number);
generationTime: number;
// Creates an ObjectID from a hex string representation of an ObjectID.
// hexString – create a ObjectID from a passed in 24 byte hexstring.
static createFromHexString(hexString: string): ObjectID;
// Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
// time – an integer number representing a number of seconds.
static createFromTime(time: number): ObjectID;
// Checks if a value is a valid bson ObjectId
// id - Value to be checked
static isValid(id: any): boolean;
//Compares the equality of this ObjectID with otherID.
equals(otherID: ObjectID): boolean;
// Generate a 12 byte id string used in ObjectID's
// time - optional parameter allowing to pass in a second based timestamp
generate(time?: number): string;
// Returns the generation date (accurate up to the second) that this ID was generated.
getTimestamp(): Date;
// Returns the ObjectID id as a 24 byte hex string representation
toHexString(): string;
// Returns the ObjectID id as a 24 byte hex string representation
toString(): string;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Binary.html
export class Binary {
constructor(buffer: Buffer, subType?: number);
static SUBTYPE_BYTE_ARRAY: number;
static SUBTYPE_DEFAULT: number;
static SUBTYPE_FUNCTION: number;
static SUBTYPE_MD5: number;
static SUBTYPE_USER_DEFINED: number;
static SUBTYPE_UUID: number;
static SUBTYPE_UUID_OLD: number;
// The length of the binary.
length(): number;
// Updates this binary with byte_value
put(byte_value: number | string): void;
// Reads length bytes starting at position.
read(position: number, length: number): Buffer;
// Returns the value of this binary as a string.
value(): string;
// Writes a buffer or string to the binary
write(buffer: Buffer | string, offset: number): void;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Double.html
export class Double {
constructor(value: number);
valueOf(): number;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Long.html
export class Long {
constructor(low: number, high: number);
static MAX_VALUE: Long;
static MIN_VALUE: Long;
static NEG_ONE: Long;
static ONE: Long;
static ZERO: Long;
static fromBits(lowBits: number, highBits: number): Long;
static fromInt(value: number): Long;
static fromNumber(value: number): Long;
static fromString(str: string, radix?: number): Long;
add(other: Long): Long;
and(other: Long): Long;
compare(other: Long): number;
div(other: Long): Long;
equals(other: Long): boolean;
getHighBits(): number;
getLowBits(): number;
getLowBitsUnsigned(): number;
getNumBitsAbs(): number;
greaterThan(other: Long): number;
greaterThanOrEqual(other: Long): number;
isNegative(): boolean;
isOdd(): boolean;
isZero(): boolean;
lessThan(other: Long): boolean;
lessThanOrEqual(other: Long): boolean;
modulo(other: Long): Long;
multiply(other: Long): Long;
negate(): Long;
not(): Long;
notEquals(other: Long): boolean;
or(other: Long): Long;
shiftLeft(other: number): Long;
shiftRight(other: number): Long;
shiftRightUnsigned(other: number): Long;
subtract(other: Long): Long;
toInt(): number;
toJSON(): string;
toNumber(): number;
toString(radix?: number): string;
xor(other: Long): Long;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/MaxKey.html
export class MaxKey { }
//http://mongodb.github.io/node-mongodb-native/2.1/api/MinKey.html
export class MinKey { }
//http://mongodb.github.io/node-mongodb-native/2.1/api/Timestamp.html
export class Timestamp {
constructor(low: number, high: number);
static MAX_VALUE: Timestamp;
static MIN_VALUE: Timestamp;
static NEG_ONE: Timestamp;
static ONE: Timestamp;
static ZERO: Timestamp;
static fromBits(lowBits: number, highBits: number): Timestamp;
static fromInt(value: number): Timestamp;
static fromNumber(value: number): Timestamp;
static fromString(str: string, radix?: number): Timestamp;
add(other: Timestamp): Timestamp;
and(other: Timestamp): Timestamp;
compare(other: Timestamp): number;
div(other: Timestamp): Timestamp;
equals(other: Timestamp): boolean;
getHighBits(): number;
getLowBits(): number;
getLowBitsUnsigned(): number;
getNumBitsAbs(): number;
greaterThan(other: Timestamp): number;
greaterThanOrEqual(other: Timestamp): number;
isNegative(): boolean;
isOdd(): boolean;
isZero(): boolean;
lessThan(other: Timestamp): boolean;
lessThanOrEqual(other: Timestamp): boolean;
modulo(other: Timestamp): Timestamp;
multiply(other: Timestamp): Timestamp;
negate(): Timestamp;
not(): Timestamp;
notEquals(other: Timestamp): boolean;
or(other: Timestamp): Timestamp;
shiftLeft(other: number): Timestamp;
shiftRight(other: number): Timestamp;
shiftRightUnsigned(other: number): Timestamp;
subtract(other: Timestamp): Timestamp;
toInt(): number;
toJSON(): string;
toNumber(): number;
toString(radix?: number): string;
xor(other: Timestamp): Timestamp;
}
// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html
export interface Collection {
// Get the collection name.
@@ -983,7 +825,7 @@ export interface FindOperatorsOrdered {
upsert(): FindOperatorsOrdered;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html
//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html
export interface UnorderedBulkOperation {
//http://mongodb.github.io/node-mongodb-native/2.1/api/lib_bulk_unordered.js.html line 339
length: number;
@@ -1371,8 +1213,8 @@ export interface GridFSBucketReadStreamOptions {
}
// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketWriteStream.html
export class GridFSBucketWriteStream extends Writable{
constructor(bucket: GridFSBucket, filename:string, options?: GridFSBucketWriteStreamOptions);
export class GridFSBucketWriteStream extends Writable {
constructor(bucket: GridFSBucket, filename: string, options?: GridFSBucketWriteStreamOptions);
}
// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketWriteStream.html
+16
View File
@@ -1307,6 +1307,8 @@ declare module "mongoose" {
// the ObjectIdConstructor, so we add the interface below
interface ObjectId extends mongodb.ObjectID {}
class Decimal128 extends mongodb.Decimal128 {}
/*
* section types/embedded.js
* http://mongoosejs.com/docs/api.html#types-embedded-js
@@ -2019,6 +2021,20 @@ declare module "mongoose" {
/** This schema type's name, to defend against minifiers that mangle function names. */
static schemaName: string;
}
/*
* section schema/decimal128.js
* http://mongoosejs.com/docs/api.html#schema-decimal128-js
*/
class Decimal128 extends SchemaType {
/** Decimal128 SchemaType constructor. */
constructor(key: string, options?: Object);
/** Check if the given value satisfies a required validator. */
checkRequired(value: any, doc: MongooseDocument): boolean;
/** This schema type's name, to defend against minifiers that mangle function names. */
static schemaName: string;
}
/*
* section schema/mixed.js
+22 -1
View File
@@ -61,7 +61,10 @@ mongoose.STATES.hasOwnProperty('');
mongoose.connection.on('error', cb);
new mongoose.mongo.MongoError('error').stack;
mongoose.SchemaTypes.String;
mongoose.SchemaTypes.ObjectId;
mongoose.SchemaTypes.Decimal128;
mongoose.Types.ObjectId;
mongoose.Types.Decimal128;
mongoose.version.toLowerCase();
/*
@@ -228,6 +231,7 @@ var schema: mongoose.Schema = new mongoose.Schema({
age: { type: Number, min: 18, max: 65 },
mixed: mongoose.Schema.Types.Mixed,
_someId: mongoose.Schema.Types.ObjectId,
someDecimal:mongoose.Schema.Types.Decimal128,
array: [],
ofString: [String],
ofNumber: [Number],
@@ -585,6 +589,23 @@ mongooseBuffer.compare(mongooseBuffer);
/* inherited static properties */
mongoose.Types.Buffer.from([1, 2, 3]);
/*
* section types/decimal128.js
* http://mongoosejs.com/docs/api.html#types-decimal128-js
*/
var decimal128: mongoose.Types.Decimal128 = mongoose.Types.Decimal128.fromString('123.45678901234567');
decimal128 = new mongoose.Types.Decimal128(new Buffer('12345'));
/* practical examples */
export interface ILargeValuesSchema extends mongoose.MongooseDocument {
sum: mongoose.Schema.Types.Decimal128;
}
export var LargeValuesSchema = new mongoose.Schema({
sum: {
type: mongoose.Schema.Types.Decimal128,
required: true
}
});
/*
* section types/objectid.js
* http://mongoosejs.com/docs/api.html#types-objectid-js
@@ -1050,7 +1071,7 @@ aggregate.unwind(
includeArrayIndex: "idx",
preserveNullAndEmptyArrays: true
});
/*
* section schematype.js
* http://mongoosejs.com/docs/api.html#schematype-js
+1
View File
@@ -190,6 +190,7 @@ interface Document {
interface Window {
on(event: string, callback: (event: Phonon.PhononCustomWindowEvent) => void, useCapture?: boolean): void;
off(event: string, callback: (event: Phonon.PhononCustomWindowEvent) => void, useCapture?: boolean): void;
phonon: Phonon.Phonon;
}
interface Element {
on(event: string, callback: (event: any) => void, useCapture?: boolean): void;
+1
View File
@@ -550,3 +550,4 @@ phonon.options({
});
setupHTML();
phonon.navigator().start();
window.phonon;
+1 -1
View File
@@ -15,7 +15,7 @@ declare namespace R {
}
interface Functor<T> {
map<T>(a: any): T;
map<U>(fn: (t: T) => U): Functor<U>;
}
interface ObjectIterator<T, TResult> {
+8 -1
View File
@@ -668,7 +668,7 @@ interface Obj { a: number; b: number };
const stringFunctor = {
map: (fn: (c: number) => number) => {
var chars = "Ifmmp!Xpsme".split("");
return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join("");
return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join("") as any;
}
};
R.map((x: number) => x-1, stringFunctor); // => "Hello World"
@@ -1985,3 +1985,10 @@ class Why {
R.intersperse(0, [1, 2]); //=> [1, 0, 2]
R.intersperse(0, [1]); //=> [1]
}
{
const functor = {
map: (fn: (x: string) => string) => functor
}
R.map(x => x.trim(), functor)
}
+29 -10
View File
@@ -1,8 +1,8 @@
// Type definitions for react-data-grid 1.0.4
// Type definitions for react-data-grid 2.0
// Project: https://github.com/adazzle/react-data-grid.git
// Definitions by: Simon Gellis <https://github.com/SupernaviX>
// Definitions by: Simon Gellis <https://github.com/SupernaviX>, Kieran Peat <https://github.com/KieranPeat>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.2
/// <reference types="react" />
@@ -18,7 +18,7 @@ declare namespace AdazzleReactDataGrid {
* Gets the data to render in each row. Required.
* Can be an array or a function that takes an index and returns an object.
*/
rowGetter: Array<Object> | ((rowIdx: number) => Object)
rowGetter: Array<object> | ((rowIdx: number) => object)
/**
* The total number of rows to render. Required.
*/
@@ -148,7 +148,7 @@ declare namespace AdazzleReactDataGrid {
* Called when a row is selected.
* @param rows The (complete) current selection of rows.
*/
onRowSelect?: (rows: Array<Object>) => void
onRowSelect?: (rows: Array<object>) => void
/**
* A property that's unique to every row.
* This property is required to enable row selection.
@@ -191,6 +191,13 @@ declare namespace AdazzleReactDataGrid {
isSelectedKey?: string;
}
}
/**
* An event function called when a row is clicked.
* Clicking the header row will trigger a call with -1 for the rowIdx.
* @param rowIdx zero index number of row clicked
* @param row object behind the row
*/
onRowClick?: (rowIdx : number, row : object) => void
}
/**
@@ -235,7 +242,11 @@ declare namespace AdazzleReactDataGrid {
* Whether the rows in the grid can be filtered by this column.
* @default false
*/
filterable?: boolean
filterable?: boolean;
/**
* A custom formatter for this column's filter.
*/
filterRenderer?: React.ReactElement<any> | React.ComponentClass<any> | React.StatelessComponent<any>;
/**
* The editor for this column. Several editors are available in "react-data-grid/addons".
* @default A simple text editor
@@ -258,6 +269,14 @@ declare namespace AdazzleReactDataGrid {
events?: {
[name: string]: ColumnEventCallback
}
/**
* Retrieve meta data about the row, optionally provide column as a second argument
*/
getRowMetaData?: (rowdata: any, column?: Column) => any;
/**
* A class name to be applied to the cells in the column
*/
cellClass?: string;
}
interface ColumnEventCallback {
@@ -280,7 +299,7 @@ declare namespace AdazzleReactDataGrid {
/**
* The columns that were updated and their values.
*/
updated: Object
updated: object
/**
* The name of the column that was updated.
*/
@@ -328,7 +347,7 @@ declare namespace AdazzleReactDataGrid {
/**
* The values of the row.
*/
rowData: Object
rowData: object
/**
* The double click event.
*/
@@ -380,7 +399,7 @@ declare namespace AdazzleReactDataGrid {
/**
* The columns that were updated and their values.
*/
updated: Object
updated: object
/**
* The action that occurred to trigger this event.
* One of 'cellUpdate', 'cellDrag', 'columnFill', or 'copyPaste'.
@@ -472,7 +491,7 @@ declare module "react-data-grid" {
export = ReactDataGrid;
}
declare module "react-data-grid/addons" {
declare module "react-data-grid-addons" {
import Plugins = AdazzleReactDataGridPlugins;
import Editors = Plugins.Editors;
import Formatters = Plugins.Formatters;
@@ -1,6 +1,6 @@
import * as React from 'react';
import * as ReactDataGrid from 'react-data-grid';
import * as ReactDataGridPlugins from 'react-data-grid/addons';
import * as ReactDataGridPlugins from 'react-data-grid-addons';
import faker = require('faker');
var Editors = ReactDataGridPlugins.Editors;
@@ -8,6 +8,29 @@ var Toolbar = ReactDataGridPlugins.Toolbar;
var AutoCompleteEditor = Editors.AutoComplete;
var DropDownEditor = Editors.DropDownEditor;
class CustomFilterHeaderCell extends React.Component<any, any> {
constructor(props: any, context: any) {
super(props, context);
this.state = {
filterTerm: ""
};
}
handleChange(e: any) {
let val = e.target.value;
this.setState({filterTerm: val});
this.props.onChange({filterTerm: val, column: this.props.column});
}
render() {
return (
<div>
<input type="text" value={this.state.filterTerm} onChange={(e) => this.handleChange(e)} />
</div>
);
}
}
faker.locale = 'en_GB';
function createFakeRowObjectData(index:number):Object {
@@ -103,7 +126,10 @@ var columns:ReactDataGrid.Column[] = [
name: 'County',
editor: <AutoCompleteEditor options={counties}/>,
width: 200,
resizable: true
resizable: true,
getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => {
return {};
}
},
{
key: 'title',
@@ -178,14 +204,17 @@ var columns:ReactDataGrid.Column[] = [
name: 'Company Name',
editable: true,
width: 200,
resizable: true
resizable: true,
filterable: true,
filterRenderer: CustomFilterHeaderCell
},
{
key: 'sentence',
name: 'Sentence',
editable: true,
width: 200,
resizable: true
resizable: true,
cellClass: 'sentence-class'
}
];
@@ -220,6 +249,10 @@ class Example extends React.Component<any, any> {
this.setState({rows: rows});
}
onRowClick(rowIdx:number, row: Object) {
// Do nothing, just test that it accepts an event
}
handleAddRow(e:any) {
var newRow = {
value: e.newRowIndex,
@@ -278,6 +311,7 @@ class Example extends React.Component<any, any> {
keys: {rowKey: 'id', values: selectedRows}
}
}}
onRowClick={this.onRowClick}
/>
);
+501
View File
@@ -0,0 +1,501 @@
// Type definitions for react-data-grid 1.0.4
// Project: https://github.com/adazzle/react-data-grid.git
// Definitions by: Simon Gellis <https://github.com/SupernaviX>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="react" />
declare namespace AdazzleReactDataGrid {
interface SelectionParams {
rowIdx: number,
row: any
}
interface GridProps {
/**
* Gets the data to render in each row. Required.
* Can be an array or a function that takes an index and returns an object.
*/
rowGetter: Array<Object> | ((rowIdx: number) => Object)
/**
* The total number of rows to render. Required.
*/
rowsCount: number
/**
* The columns to render.
*/
columns?: Array<Column>
/**
* Invoked when the user changes the value of a single cell.
* Should update that cell's value.
* @param e Information about the event
*/
onRowUpdated?: (e: RowUpdateEvent) => void
/**
* Invoked when the user pulls down the drag handle of an editable cell.
* Should update the values of the selected cells.
* @param e Information about the event
*/
onCellsDragged?: (e: CellDragEvent) => void
/**
* Invoked when the user double clicks on the drag handle of an editable cell.
* Should update the values of the cells beneath the selected cell.
* @param e Information about the event
*/
onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void
/**
* Invoked when the user copies a value from one cell and pastes it into another (in the same column).
* Should update the value of the cell in row e.toRow.
* @param e Information about the event
*/
onCellCopyPaste?: (e: CellCopyPasteEvent) => void
/**
* Invoked after the user updates the grid rows in any way.
* @param e Information about the event
*/
onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void
/**
* A toolbar to display above the grid.
* Consider using the toolbar included in "react-data-grid/addons".
*/
toolbar?: React.ReactElement<any>
/**
* A context menu to disiplay when the user right-clicks a cell.
* Consider using "react-contextmenu", included in "react-data-grid/addons".
*/
contextMenu?: React.ReactElement<any>
/**
* A react component to customize how rows are rendered.
* If you want to define your own, consider extending ReactDataGrid.Row.
*/
rowRenderer?: React.ReactElement<any> | React.ComponentClass<any> | React.StatelessComponent<any>
/**
* A component to display when there are no rows to render.
*/
emptyRowsView?: React.ComponentClass<any> | React.StatelessComponent<any>
/**
* The minimum width of the entire grid in pixels.
*/
minWidth?: number
/**
* The minimum height of the entire grid in pixels.
* @default 350
*/
minHeight?: number
/**
* The height of each individual row in pixels.
* @default 35
*/
rowHeight?: number
/**
* The height of the header row in pixels.
* @default rowHeight
*/
headerRowHeight?: number
/**
* The minimum width of each column in pixels.
* @default 80
*/
minColumnWidth?: number
/**
* Invoked when a column has been resized.
* @param index The index of the column
* @param width The new width of the column
*/
onColumnResize?: (index: number, width: number) => void
/**
* Controls what happens when the user navigates beyond the first or last cells.
* 'loopOverRow' will navigate to the beginning/end of the current row.
* 'changeRow' will navigate to the beginning of the next row or the end of the last.
* 'none' will do nothing.
* @default none
*/
cellNavigationMode?: 'none' | 'loopOverRow' | 'changeRow'
/**
* Called when the user sorts the grid by some column.
* Should update the order of the rows returned by rowGetter.
* @param sortColumn The name of the column being sorted by
* @param sortDirection The direction to sort ('ASC'/'DESC'/'NONE')
*/
onGridSort?: (sortColumn: string, sortDirection: 'ASC' | 'DESC' | 'NONE') => void
/**
* Called when the user filters a column by some value.
* Should restrict the rows in rowGetter to only things that match the filter.
* @param filter The filter being added
*/
onAddFilter?: (filter: Filter) => void
/**
* Called when the user clears all filters.
* Should restore the rows in rowGetter to their original state.
*/
onClearFilters?: () => void
/**
* When set to true or 'multi', enables multiple row select.
* When set to 'single', enables single row select.
* When set to false or not set, disables row select.
* @default false
*/
enableRowSelect?: boolean | 'single' | 'multi'
/**
* Called when a row is selected.
* @param rows The (complete) current selection of rows.
*/
onRowSelect?: (rows: Array<Object>) => void
/**
* A property that's unique to every row.
* This property is required to enable row selection.
* @default 'id'
*/
rowKey?: string
/**
* Enables cells to be selected when clicked.
* @default false
*/
enableCellSelect?: boolean
/**
* Called when a cell is selected.
* @param coordinates The row and column indices of the selected cell.
*/
onCellSelected?: (coordinates: {rowIdx: number, idx: number}) => void
/**
* Called when a cell is deselected.
* @param coordinates The row and column indices of the deselected cell.
*/
onCellDeSelected?: (coordinates: {rowIdx: number, idx: number}) => void
/**
* How long to wait before rendering a new row while scrolling in milliseconds.
* @default 0
*/
rowScrollTimeout?: number
/**
* Options object for selecting rows
*/
rowSelection?: {
showCheckbox?: boolean
enableShiftSelect?: boolean
onRowsSelected?: (rows: Array<SelectionParams>) => void,
onRowsDeselected?: (rows: Array<SelectionParams>) => void,
selectBy?: {
indexes?: Array<number>;
keys?: { rowKey: string, values: Array<any> };
isSelectedKey?: string;
}
}
}
/**
* Information about a specific column to be rendered.
*/
interface Column {
/**
* A unique key for this column. Required.
* Each row should have a property with this name, which contains this column's value.
*/
key: string
/**
* This column's display name. Required.
*/
name: string
/**
* A custom width for this specific column.
* @default minColumnWidth from the ReactDataGrid
*/
width?: number
/**
* Whether this column can be resized by the user.
* @default false
*/
resizable?: boolean
/**
* Whether this column should stay fixed on the left as the user scrolls horizontally.
* @default false
*/
locked?: boolean
/**
* Whether this column can be edited.
* @default false
*/
editable?: boolean
/**
* Whether the rows in the grid can be sorted by this column.
* @default false
*/
sortable?: boolean
/**
* Whether the rows in the grid can be filtered by this column.
* @default false
*/
filterable?: boolean
/**
* The editor for this column. Several editors are available in "react-data-grid/addons".
* @default A simple text editor
*/
editor?: React.ReactElement<any>
/**
* A custom read-only formatter for this column. An image formatter is available in "react-data-grid/addons".
*/
formatter?: React.ReactElement<any> | React.ComponentClass<any> | React.StatelessComponent<any>
/**
* A custom formatter for this column's header.
*/
headerRenderer?: React.ReactElement<any> | React.ComponentClass<any> | React.StatelessComponent<any>
/**
* Events to be bound to the cells in this specific column.
* Each event must respect this standard in order to work correctly:
* @example
* function onXxx(ev :SyntheticEvent, (rowIdx, idx, name): args)
*/
events?: {
[name: string]: ColumnEventCallback
}
}
interface ColumnEventCallback {
/**
* A callback for a native react event on a specific cell.
* @param ev The react event
* @param args The row and column coordinates of the cell, and the name of the event.
*/
(ev: React.SyntheticEvent<any>, args: {rowIdx: number, idx: number, name: string}): void
}
/**
* Information about a row update
*/
interface RowUpdateEvent {
/**
* The index of the updated row.
*/
rowIdx: number
/**
* The columns that were updated and their values.
*/
updated: Object
/**
* The name of the column that was updated.
*/
cellKey: string
/**
* The name of the key pressed to trigger the event ('Tab', 'Enter', etc.).
*/
key: string
}
/**
* Information about a cell drag
*/
interface CellDragEvent {
/**
* The name of the column that was dragged.
*/
cellKey: string
/**
* The row where the drag began.
*/
fromRow: number
/**
* The row where the drag ended.
*/
toRow: number
/**
* The value of the cell that was dragged.
*/
value: any
}
/**
* Information about a drag handle double click
*/
interface DragHandleDoubleClickEvent {
/**
* The row where the double click occurred.
*/
rowIdx: number
/**
* The column where the double click occurred.
*/
idx: number
/**
* The values of the row.
*/
rowData: Object
/**
* The double click event.
*/
e: React.SyntheticEvent<any>
}
/**
* Information about a copy paste
*/
interface CellCopyPasteEvent {
/**
* The row that was pasted to.
*/
rowIdx: number
/**
* The value that was pasted.
*/
value: any
/**
* The row that was copied from.
*/
fromRow: number
/**
* The row that was pasted to.
*/
toRow: number
/**
* The key of the column where the copy paste occurred.
*/
cellKey: string
}
/**
* Information about some update to the grid's contents
*/
interface GridRowsUpdatedEvent {
/**
* The key of the column where the event occurred.
*/
cellKey: string
/**
* The top row affected by the event.
*/
fromRow: number
/**
* The bottom row affected by the event.
*/
toRow: number
/**
* The columns that were updated and their values.
*/
updated: Object
/**
* The action that occurred to trigger this event.
* One of 'cellUpdate', 'cellDrag', 'columnFill', or 'copyPaste'.
*/
action: 'cellUpdate' | 'cellDrag' | 'columnFill' | 'copyPaste'
}
/**
* Some filter to be applied to the grid's contents
*/
interface Filter {
/**
* The key of the column being filtered.
*/
columnKey: string
/**
* The term to filter by.
*/
filterTerm: string
}
/**
* Excel-like grid component built with React, with editors, keyboard navigation, copy & paste, and the like
* http://adazzle.github.io/react-data-grid/
*/
export class ReactDataGrid extends React.Component<GridProps, {}> { }
export namespace ReactDataGrid {
// Useful types
export import Column = AdazzleReactDataGrid.Column;
export import Filter = AdazzleReactDataGrid.Filter;
// Various events
export import RowUpdateEvent = AdazzleReactDataGrid.RowUpdateEvent;
export import SelectionParams = AdazzleReactDataGrid.SelectionParams;
export import CellDragEvent = AdazzleReactDataGrid.CellDragEvent;
export import DragHandleDoubleClickEvent = AdazzleReactDataGrid.DragHandleDoubleClickEvent;
export import CellCopyPasteEvent = AdazzleReactDataGrid.CellCopyPasteEvent;
export import GridRowsUpdatedEvent = AdazzleReactDataGrid.GridRowsUpdatedEvent;
// Actual classes exposed on module.exports
/**
* A react component that renders a row of the grid
*/
export class Row extends React.Component<any, any> { }
/**
* A react coponent that renders a cell of the grid
*/
export class Cell extends React.Component<any, any> { }
}
}
declare namespace AdazzleReactDataGridPlugins {
// TODO: refine types for these addons
export namespace Editors {
export class AutoComplete extends React.Component<any, {}> { }
export class DropDownEditor extends React.Component<any, {}> { }
export class SimpleTextEditor extends React.Component<any, {}> { }
export class CheckboxEditor extends React.Component<any, {}> { }
}
export namespace Formatters {
export class ImageFormatter extends React.Component<any, {}> { }
export class DropDownFormatter extends React.Component<any, {}> { }
}
export class Toolbar extends React.Component<any, any> {}
// TODO: re-export the react-contextmenu typings once those exist
// https://github.com/vkbansal/react-contextmenu/issues/10
export namespace Menu {
export class ContextMenu extends React.Component<any, {}> { }
export class MenuHeader extends React.Component<any, {}> { }
export class MenuItem extends React.Component<any, {}> { }
export class SubMenu extends React.Component<any, {}> { }
export const monitor: {
getItem(): any
getPosition(): any
hideMenu(): void
};
export function connect(Menu: any): any;
export function ContextMenuLayer(
identifier: any,
configure?: (props: any) => any
): (Component: any) => any
}
}
declare module "react-data-grid" {
import ReactDataGrid = AdazzleReactDataGrid.ReactDataGrid;
// commonjs export
export = ReactDataGrid;
}
declare module "react-data-grid/addons" {
import Plugins = AdazzleReactDataGridPlugins;
import Editors = Plugins.Editors;
import Formatters = Plugins.Formatters;
import Toolbar = Plugins.Toolbar;
import Menu = Plugins.Menu;
// ES6 named exports
export {
Editors,
Formatters,
Toolbar,
Menu
}
// attach to window
global {
interface Window {
ReactDataGridPlugins: {
Editors: typeof Editors
Formatters: typeof Formatters
Toolbar: typeof Toolbar
Menu: typeof Menu
}
}
}
}
@@ -0,0 +1,285 @@
import * as React from 'react';
import * as ReactDataGrid from 'react-data-grid';
import * as ReactDataGridPlugins from 'react-data-grid/addons';
import faker = require('faker');
var Editors = ReactDataGridPlugins.Editors;
var Toolbar = ReactDataGridPlugins.Toolbar;
var AutoCompleteEditor = Editors.AutoComplete;
var DropDownEditor = Editors.DropDownEditor;
faker.locale = 'en_GB';
function createFakeRowObjectData(index:number):Object {
return {
id: 'id_' + index,
avartar: faker.image.avatar(),
county: faker.address.county(),
email: faker.internet.email(),
title: faker.name.prefix(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
street: faker.address.streetName(),
zipCode: faker.address.zipCode(),
date: faker.date.past().toLocaleDateString(),
bs: faker.company.bs(),
catchPhrase: faker.company.catchPhrase(),
companyName: faker.company.companyName(),
words: faker.lorem.words(),
sentence: faker.lorem.sentence()
};
}
function createRows(numberOfRows:number) {
var rows:Object[] = [];
for (var i = 0; i < numberOfRows; i++) {
rows[i] = createFakeRowObjectData(i);
}
return rows;
}
var counties = [
{id: 0, title: 'Bedfordshire'},
{id: 1, title: 'Berkshire'},
{id: 2, title: 'Buckinghamshire'},
{id: 3, title: 'Cambridgeshire'},
{id: 4, title: 'Cheshire'},
{id: 5, title: 'Cornwall'},
{id: 6, title: 'Cumbria, (Cumberland)'},
{id: 7, title: 'Derbyshire'},
{id: 8, title: 'Devon'},
{id: 9, title: 'Dorset'},
{id: 10, title: 'Durham'},
{id: 11, title: 'Essex'},
{id: 12, title: 'Gloucestershire'},
{id: 13, title: 'Hampshire'},
{id: 14, title: 'Hertfordshire'},
{id: 15, title: 'Huntingdonshire'},
{id: 16, title: 'Kent'},
{id: 17, title: 'Lancashire'},
{id: 18, title: 'Leicestershire'},
{id: 19, title: 'Lincolnshire'},
{id: 20, title: 'Middlesex'},
{id: 21, title: 'Norfolk'},
{id: 22, title: 'Northamptonshire'},
{id: 23, title: 'Northumberland'},
{id: 24, title: 'Nottinghamshire'},
{id: 25, title: 'Northamptonshire'},
{id: 26, title: 'Oxfordshire'},
{id: 27, title: 'Northamptonshire'},
{id: 28, title: 'Rutland'},
{id: 29, title: 'Shropshire'},
{id: 30, title: 'Somerset'},
{id: 31, title: 'Staffordshire'},
{id: 32, title: 'Suffolk'},
{id: 33, title: 'Surrey'},
{id: 34, title: 'Sussex'},
{id: 35, title: 'Warwickshire'},
{id: 36, title: 'Westmoreland'},
{id: 37, title: 'Wiltshire'},
{id: 38, title: 'Worcestershire'},
{id: 39, title: 'Yorkshire'}
];
var titles = ['Dr.', 'Mr.', 'Mrs.', 'Miss', 'Ms.'];
var columns:ReactDataGrid.Column[] = [
{
key: 'id',
name: 'ID',
width: 80,
resizable: true
},
{
key: 'avartar',
name: 'Avartar',
width: 60,
formatter: ReactDataGridPlugins.Formatters.ImageFormatter,
resizable: true,
headerRenderer: <ReactDataGridPlugins.Formatters.ImageFormatter value={faker.image.cats()}/>
},
{
key: 'county',
name: 'County',
editor: <AutoCompleteEditor options={counties}/>,
width: 200,
resizable: true
},
{
key: 'title',
name: 'Title',
editor: <DropDownEditor options={titles}/>,
width: 200,
resizable: true,
events: {
onDoubleClick: function () {
console.log("The user double clicked on title column");
}
}
},
{
key: 'firstName',
name: 'First Name',
editable: true,
width: 200,
resizable: true
},
{
key: 'lastName',
name: 'Last Name',
editable: true,
width: 200,
resizable: true
},
{
key: 'email',
name: 'Email',
editable: true,
width: 200,
resizable: true
},
{
key: 'street',
name: 'Street',
editable: true,
width: 200,
resizable: true
},
{
key: 'zipCode',
name: 'ZipCode',
editable: true,
width: 200,
resizable: true
},
{
key: 'date',
name: 'Date',
editable: true,
width: 200,
resizable: true
},
{
key: 'bs',
name: 'bs',
editable: true,
width: 200,
resizable: true
},
{
key: 'catchPhrase',
name: 'Catch Phrase',
editable: true,
width: 200,
resizable: true
},
{
key: 'companyName',
name: 'Company Name',
editable: true,
width: 200,
resizable: true
},
{
key: 'sentence',
name: 'Sentence',
editable: true,
width: 200,
resizable: true
}
];
class Example extends React.Component<any, any> {
getInitialState() {
var fakeRows = createRows(2000);
return {rows: fakeRows};
}
getColumns() {
var clonedColumns = columns.slice();
clonedColumns[2].events = {
onClick: function (ev:React.SyntheticEvent<any>, args:{idx:number, rowIdx:number}) {
var idx = args.idx;
var rowIdx = args.rowIdx;
this.refs.grid.openCellEditor(rowIdx, idx);
}.bind(this)
};
return clonedColumns;
}
handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) {
var rows = this.state.rows;
for (var i = updatedRowData.fromRow; i <= updatedRowData.toRow; i++) {
var rowToUpdate = rows[i];
var updatedRow = Object.assign({}, rowToUpdate, updatedRowData.updated);
rows[i] = updatedRow;
}
this.setState({rows: rows});
}
handleAddRow(e:any) {
var newRow = {
value: e.newRowIndex,
userStory: '',
developer: '',
epic: ''
};
var rows = this.state.rows;
rows.push(newRow);
this.setState({rows: rows});
}
getRowAt(index:number) {
if (index < 0 || index > this.getSize()) {
return undefined;
}
return this.state.rows[index];
}
getSize() {
return this.state.rows.length;
}
onRowsSelected(rows: Array<ReactDataGrid.SelectionParams>) {
var selectedIndexes = this.state.selectedIndexes as Array<number>;
this.setState({selectedIndexes: selectedIndexes.concat(rows.map(r => r.rowIdx))});
}
onRowsDeselected(rows: Array<ReactDataGrid.SelectionParams>) {
var rowIndexes = rows.map(r => r.rowIdx);
var selectedIndexes = this.state.selectedIndexes as Array<number>;
this.setState({selectedIndexes: selectedIndexes.filter(i => rowIndexes.indexOf(i) === -1 )});
}
render() {
let selectedRows = ['id1', 'id2'];
return (
<ReactDataGrid
ref='grid'
enableCellSelect={true}
columns={this.getColumns()}
rowGetter={this.getRowAt}
rowsCount={this.getSize()}
onGridRowsUpdated={this.handleGridRowsUpdated}
toolbar={<Toolbar onAddRow={this.handleAddRow}/>}
enableRowSelect={true}
rowHeight={50}
minHeight={600}
rowScrollTimeout={200}
rowSelection={{
showCheckbox: true,
enableShiftSelect: true,
onRowsSelected: this.onRowsSelected,
onRowsDeselected: this.onRowsDeselected,
selectBy: {
keys: {rowKey: 'id', values: selectedRows}
}
}}
/>
);
}
}
@@ -6,18 +6,22 @@
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitThis": false,
"strictNullChecks": false,
"baseUrl": "../",
"baseUrl": "../../",
"jsx": "react",
"typeRoots": [
"../"
"../../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"paths": {
"react-data-grid": [ "react-data-grid/v1" ]
}
},
"files": [
"index.d.ts",
"maquette-tests.ts"
"react-data-grid-tests.tsx"
]
}
}
+7
View File
@@ -16,21 +16,28 @@ declare module "react-datepicker" {
dateFormat?: string;
dateFormatCalendar?: string;
disabled?: boolean;
dropdownMode?: string;
endDate?: moment.Moment;
excludeDates?: any[];
filterDate?(): any;
fixedHeight?: boolean;
forceShowMonthNavigation?: boolean;
highlightDates?: any[];
id?: string;
includeDates?: any[];
inline?: boolean;
isClearable?: boolean;
locale?: string;
maxDate?: moment.Moment;
minDate?: moment.Moment;
monthsShown?: number;
name?: string;
onBlur?(event: React.FocusEvent<HTMLInputElement>): void;
onChange(date: moment.Moment | null, event: React.SyntheticEvent<any> | undefined): any;
onChangeRaw?(event: React.FocusEvent<HTMLInputElement>): void;
onFocus?(event: React.FocusEvent<HTMLInputElement>): void;
onMonthChange?(date: moment.Moment): void;
openToDate?: moment.Moment;
peekNextMonth?: boolean;
placeholderText?: string;
popoverAttachment?: string;
@@ -8,8 +8,9 @@ import {
Image,
View,
Dimensions,
FlexJustifyType,
FlexAlignType
ViewStyle,
TextStyle,
ImageStyle,
} from 'react-native';
import SortableList, {RowProps} from 'react-native-sortable-list';
@@ -61,20 +62,20 @@ const data = {
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center" as FlexJustifyType,
alignItems: "center" as FlexAlignType,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#eee',
paddingTop: 60,
},
} as ViewStyle,
list: {
flex: 1,
},
} as ViewStyle,
contentContainer: {
width: window.width,
paddingHorizontal: 30,
},
} as ViewStyle,
row: {
flexDirection: 'row',
@@ -89,18 +90,18 @@ const styles = StyleSheet.create({
shadowOpacity: 1,
shadowOffset: {height: 2, width: 2},
shadowRadius: 2,
},
} as ViewStyle,
image: {
width: 60,
height: 60,
marginRight: 30,
borderRadius: 30,
},
} as ImageStyle,
text: {
fontSize: 24,
},
} as TextStyle,
});
+7 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for react-native-swiper 1.5
// Project: https://github.com/leecade/react-native-swiper#readme
// Definitions by: CaiHuan <https://github.com/CaiHuan>
// Definitions by: CaiHuan <https://github.com/CaiHuan>, HuHuanming <https://github.com/huhuanming>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
@@ -57,6 +57,12 @@ interface SwiperProperties extends React.Props<Swiper> {
dotColor?: string;
activeDotColor?: string;
height?: number;
width?: number;
paginationStyle?: ViewStyle;
}
export default class Swiper extends React.Component<SwiperProperties, {}> {
+80 -21
View File
@@ -1,6 +1,7 @@
// Type definitions for react-native 0.42
// Type definitions for react-native 0.43
// Project: https://github.com/facebook/react-native
// Definitions by: Eloy Durán <https://github.com/alloy>
// Fedor Nezhivoi <https://github.com/gyzerok>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
@@ -531,9 +532,7 @@ export interface LayoutAnimationStatic {
spring: (config: LayoutAnimationConfig, onAnimationDidEnd?: () => void) => void
}
export type FlexAlignType = "flex-start" | "flex-end" | "center" | "stretch" | "baseline";
export type FlexJustifyType = "flex-start" | "flex-end" | "center" | "space-between" | "space-around";
export type FlexDirection = "row" | "column" | "row-reverse" | "column-reverse";
type FlexAlignType = "flex-start" | "flex-end" | "center" | "stretch" | "baseline";
/**
* Flex Prop Types
@@ -541,9 +540,9 @@ export type FlexDirection = "row" | "column" | "row-reverse" | "column-reverse";
* @see LayoutPropTypes.js
*/
export interface FlexStyle {
alignItems?: FlexAlignType;
alignSelf?: "auto" | FlexAlignType;
alignContent?: "flex-start" | "flex-end" | "center" | "stretch" | "space-between" | "space-around"
alignItems?: FlexAlignType
alignSelf?: "auto" | FlexAlignType
borderBottomWidth?: number
borderLeftWidth?: number
borderRightWidth?: number
@@ -551,18 +550,14 @@ export interface FlexStyle {
borderWidth?: number
bottom?: number | string
flex?: number
flexBasis?: number | string
flexDirection?: "row" | "column" | "row-reverse" | "column-reverse"
flexGrow?: number
flexShrink?: number
flexBasis?: number | string
flexDirection?: FlexDirection
flexWrap?: "wrap" | "nowrap"
height?: number | string
justifyContent?: FlexJustifyType
justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"
left?: number | string
minWidth?: number | string
maxWidth?: number | string
minHeight?: number | string
maxHeight?: number | string
margin?: number | string
marginBottom?: number | string
marginHorizontal?: number | string
@@ -570,6 +565,10 @@ export interface FlexStyle {
marginRight?: number | string
marginTop?: number | string
marginVertical?: number | string
maxHeight?: number | string
maxWidth?: number | string
minHeight?: number | string
minWidth?: number | string
overflow?: "visible" | "hidden" | "scroll"
padding?: number | string
paddingBottom?: number | string
@@ -582,11 +581,12 @@ export interface FlexStyle {
right?: number | string
top?: number | string
width?: number | string
zIndex?: number
/**
* @platform ios
*/
zIndex?: number
direction?: 'inherit' | 'ltr' | 'rtl'
}
/**
@@ -2612,12 +2612,14 @@ export interface PickerIOSItemStatic extends React.ComponentClass<PickerIOSItemP
/**
* @see Picker.js
*/
export interface PickerItemProperties extends React.Props<PickerItemStatic> {
export interface PickerItemProperties extends React.Props<PickerItem> {
testID?: string
color?: string
label: string
value?: any
}
export interface PickerItemStatic extends React.ComponentClass<PickerItemProperties> {
export interface PickerItem extends React.ComponentClass<PickerItemProperties> {
}
export interface PickerPropertiesIOS extends ViewProperties, React.Props<PickerStatic> {
@@ -2697,7 +2699,7 @@ export interface PickerProperties extends PickerPropertiesIOS, PickerPropertiesA
*/
export interface PickerStatic extends React.ComponentClass<PickerProperties> {
/**
/**
* On Android, display the options in a dialog.
*/
MODE_DIALOG: string
@@ -2706,7 +2708,7 @@ export interface PickerStatic extends React.ComponentClass<PickerProperties> {
*/
MODE_DROPDOWN: string
Item?: PickerItemStatic
Item: PickerItem
}
/**
@@ -3909,11 +3911,17 @@ export interface TouchableWithoutFeedbackIOSProperties {
*/
export interface TouchableWithoutFeedbackProperties extends TouchableWithoutFeedbackAndroidProperties, TouchableWithoutFeedbackIOSProperties {
/**
* Overrides the text that's read by the screen reader when the user interacts with the element. By default, the
* label is constructed by traversing all the children and accumulating all the Text nodes separated by space.
*/
accessibilityLabel?: string;
/**
* Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock).
* When true, indicates that the view is an accessibility element.
* By default, all the touchable elements are accessible.
*/
accessible?: boolean
accessible?: boolean;
/**
* Delay in ms, from onPressIn, before onLongPress is called.
@@ -7148,6 +7156,57 @@ export interface UIManagerStatic {
quality ?: number,
}
) => Promise<string>
/**
* Determines the location on screen, width, and height of the given view and
* returns the values via an async callback. If successful, the callback will
* be called with the following arguments:
*
* - x
* - y
* - width
* - height
* - pageX
* - pageY
*
* Note that these measurements are not available until after the rendering
* has been completed in native. If you need the measurements as soon as
* possible, consider using the [`onLayout`
* prop](docs/view.html#onlayout) instead.
*/
measure(node: number, callback: MeasureOnSuccessCallback): void;
/**
* Determines the location of the given view in the window and returns the
* values via an async callback. If the React root view is embedded in
* another native view, this will give you the absolute coordinates. If
* successful, the callback will be called with the following
* arguments:
*
* - x
* - y
* - width
* - height
*
* Note that these measurements are not available until after the rendering
* has been completed in native.
*/
measureInWindow(node: number, callback: MeasureInWindowOnSuccessCallback): void;
/**
* Like [`measure()`](#measure), but measures the view relative an ancestor,
* specified as `relativeToNativeNode`. This means that the returned x, y
* are relative to the origin x, y of the ancestor view.
*
* As always, to obtain a native node handle for a component, you can use
* `React.findNodeHandle(component)`.
*/
measureLayout(
node: number,
relativeToNativeNode: number,
onFail: () => void, /* currently unused */
onSuccess: MeasureLayoutOnSuccessCallback
): void;
}
export interface SwitchPropertiesIOS extends ViewProperties, React.Props<SwitchStatic> {
+48 -49
View File
@@ -1,18 +1,53 @@
// Type definitions for react-router-redux 4.0
// Project: https://github.com/rackt/react-router-redux
// Definitions by: Isman Usoh <http://github.com/isman-usoh>
// Noah Shipley <https://github.com/noah79>
// Dimitri Rosenberg <https://github.com/rosendi>
// Karol Janyst <https://github.com/LKay>
// Dovydas Navickas <https://github.com/DovydasNavickas>
// Type definitions for react-router-redux 5.0
// Project: https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux
// Definitions by: Huy Nguyen <https://github.com/huy-nguyen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.2
import { Action, Middleware, Store } from "redux";
import { History, Location, LocationDescriptor } from "history";
import {
Store,
Dispatch,
Action,
Middleware
} from 'redux';
import {
History,
Location,
Path,
LocationState,
LocationDescriptor
} from 'history';
import * as React from 'react';
export interface ConnectedRouterProps<State> {
store?: Store<State>;
history?: History;
}
export class ConnectedRouter<State> extends React.Component<ConnectedRouterProps<State>, {}> {}
export const LOCATION_CHANGE: string;
export interface RouterState {
location: Location | null;
}
export function routerReducer(state?: RouterState, action?: RouterAction): RouterState;
export const CALL_HISTORY_METHOD: string;
export const LOCATION_CHANGE: string;
export function push(location: LocationDescriptor, state?: LocationState): RouterAction;
export function replace(location: LocationDescriptor, state?: LocationState): RouterAction;
export function go(n: number): RouterAction;
export function goBack(): RouterAction;
export function goForward(): RouterAction;
export const routerAction: {
push: typeof push
replace: typeof replace
go: typeof go
goBack: typeof goBack
goForward: typeof goForward
};
export interface LocationActionPayload {
method: string;
@@ -20,44 +55,8 @@ export interface LocationActionPayload {
}
export interface RouterAction extends Action {
payload?: LocationActionPayload;
type: typeof CALL_HISTORY_METHOD;
payload: LocationActionPayload;
}
type LocationAction = (nextLocation: LocationDescriptor) => RouterAction;
type GoAction = (n: number) => RouterAction;
type NavigateAction = () => RouterAction;
export const push: LocationAction;
export const replace: LocationAction;
export const go: GoAction;
export const goBack: NavigateAction;
export const goForward: NavigateAction;
interface RouteActions {
push: typeof push;
replace: typeof replace;
go: typeof go;
goForward: typeof goForward;
goBack: typeof goBack;
}
export const routerActions: RouteActions;
export interface RouterState {
locationBeforeTransitions: Location;
}
export type DefaultSelectLocationState = (state: any) => RouterState;
export interface SyncHistoryWithStoreOptions {
selectLocationState?: DefaultSelectLocationState;
adjustUrlOnReplay?: boolean;
}
export interface HistoryUnsubscribe {
unsubscribe(): void;
}
export function routerReducer(state?: RouterState, action?: Action): RouterState;
export function syncHistoryWithStore(history: History, store: Store<any>, options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribe;
export function routerMiddleware(history: History): Middleware;
@@ -0,0 +1,46 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware, Reducer } from 'redux';
import { Provider } from 'react-redux';
import createHistory from 'history/createBrowserHistory';
import { Route } from 'react-router';
import { ConnectedRouter, routerReducer, routerMiddleware, push, RouterState } from 'react-router-redux';
// Create a history of your choosing (we're using a browser history in this case)
const history = createHistory();
// Build the middleware for intercepting and dispatching navigation actions
const middleware = routerMiddleware(history);
interface State {
router: RouterState;
}
// For testing, assume the router reducer is the only sub-reducer:
const reducers: Reducer<State> = combineReducers<State>({router: routerReducer});
// Add the reducer to your store on the `router` key
// Also apply our middleware for navigating
const store = createStore(
reducers,
applyMiddleware(middleware)
);
const Home = () => <div>Home</div>;
ReactDOM.render(
<Provider store={store}>
{ /* ConnectedRouter will use the store from Provider automatically */ }
<ConnectedRouter history={history}>
<div>
<Route exact path="/" component={Home}/>
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// Now you can dispatch navigation actions from anywhere!
store.dispatch(push('/foo'));
+3 -6
View File
@@ -8,20 +8,17 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"jsx": "react",
"baseUrl": "../",
"typeRoots": [
"../"
"../"
],
"paths": {
"history": ["history/v3"],
"history/*": ["history/v3/*"]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"react-router-redux-tests.ts"
"react-router-redux-tests.tsx"
]
}
+3 -1
View File
@@ -1 +1,3 @@
{ "extends": "../tslint.json" }
{
"extends": "../tslint.json"
}
-1
View File
@@ -7,7 +7,6 @@
import * as Redux from "redux";
import * as History from "history";
export const TRANSITION: string;
export const UPDATE_LOCATION: string;
+63
View File
@@ -0,0 +1,63 @@
// Type definitions for react-router-redux 4.0
// Project: https://github.com/rackt/react-router-redux
// Definitions by: Isman Usoh <http://github.com/isman-usoh>,
// Noah Shipley <https://github.com/noah79>,
// Dimitri Rosenberg <https://github.com/rosendi>,
// Karol Janyst <https://github.com/LKay>,
// Dovydas Navickas <https://github.com/DovydasNavickas>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import { Action, Middleware, Store } from "redux";
import { History, Location, LocationDescriptor } from "history";
export const CALL_HISTORY_METHOD: string;
export const LOCATION_CHANGE: string;
export interface LocationActionPayload {
method: string;
args?: any[];
}
export interface RouterAction extends Action {
payload?: LocationActionPayload;
}
type LocationAction = (nextLocation: LocationDescriptor) => RouterAction;
type GoAction = (n: number) => RouterAction;
type NavigateAction = () => RouterAction;
export const push: LocationAction;
export const replace: LocationAction;
export const go: GoAction;
export const goBack: NavigateAction;
export const goForward: NavigateAction;
interface RouteActions {
push: typeof push;
replace: typeof replace;
go: typeof go;
goForward: typeof goForward;
goBack: typeof goBack;
}
export const routerActions: RouteActions;
export interface RouterState {
locationBeforeTransitions: Location;
}
export type DefaultSelectLocationState = (state: any) => RouterState;
export interface SyncHistoryWithStoreOptions {
selectLocationState?: DefaultSelectLocationState;
adjustUrlOnReplay?: boolean;
}
export interface HistoryUnsubscribe {
unsubscribe(): void;
}
export function routerReducer(state?: RouterState, action?: Action): RouterState;
export function syncHistoryWithStore(history: History, store: Store<any>, options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribe;
export function routerMiddleware(history: History): Middleware;
+5
View File
@@ -0,0 +1,5 @@
{
"dependencies": {
"redux": "^3.6.0"
}
}

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