Merge branch 'master' into node_urlUrl

This commit is contained in:
Flarna
2017-03-08 20:33:35 +01:00
249 changed files with 41098 additions and 30912 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
import packer = require("3d-bin-packing");
import samchon = require("samchon-framework");
import samchon = require("samchon");
function main(): void
{
+140 -258
View File
@@ -1,20 +1,22 @@
// Type definitions for 3d-bin-packing
// Type definitions for 3d-bin-packing v1.1.2
// Project: https://github.com/betterwaysystems/packer
// Definitions by: Jeongho Nam <http://samchon.org>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="typescript-stl" />
/// <reference types="samchon-framework" />
/// <reference types="react" />
/// <reference types="react-data-grid" />
/// <reference types="three" />
/// <reference types="samchon" />
declare module "3d-bin-packing"
{
export = bws.packer;
export = bws.packer;
}
/// <reference types="samchon" />
/// <reference types="tstl" />
declare namespace bws.packer {
export import library = samchon.library;
export import protocol = samchon.protocol;
function _Test(): void;
}
declare var ReactDataGrid: typeof AdazzleReactDataGrid.ReactDataGrid;
declare namespace boxologic {
/**
* <p> An abstract instance of boxologic. </p>
@@ -62,122 +64,6 @@ declare namespace boxologic {
constructor(width: number, height: number, length: number);
}
}
declare namespace bws.packer {
/**
* @brief Packer, a solver of 3d bin packing with multiple wrappers.
*
* @details
* <p> Packer is a facade class supporting packing operations in user side. You can solve a packing problem
* by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to
* pack and executing {@link optimize Packer.optimize()} method. </p>
*
* <p> In background side, deducting packing solution, those algorithms are used. </p>
* <ul>
* <li> <a href="http://betterwaysystems.github.io/packer/reference/AirForceBinPacking.pdf" target="_blank">
* Airforce Bin Packing; 3D pallet packing problem: A human intelligence-based heuristic approach </a>
* </li>
* <li> Genetic Algorithm </li>
* <li> Greedy and Back-tracking algorithm </li>
* </ul>
*
* @author Jeongho Nam <http://samchon.org>
*/
class Packer extends samchon.protocol.Entity {
/**
* Candidate wrappers who can contain instances.
*/
protected wrapperArray: WrapperArray;
/**
* Instances trying to pack into the wrapper.
*/
protected instanceArray: InstanceArray;
/**
* Default Constructor.
*/
constructor();
/**
* Construct from members.
*
* @param wrapperArray Candidate wrappers who can contain instances.
* @param instanceArray Instances to be packed into some wrappers.
*/
constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray);
/**
* @inheritdoc
*/
construct(xml: samchon.library.XML): void;
/**
* Get wrapperArray.
*/
getWrapperArray(): WrapperArray;
/**
* Get instanceArray.
*/
getInstanceArray(): InstanceArray;
/**
* <p> Deduct
*
*/
optimize(): WrapperArray;
/**
* @brief Initialize sequence list (gene_array).
*
* @details
* <p> Deducts initial sequence list by such assumption: </p>
*
* <ul>
* <li> Cost of larger wrapper is less than smaller one, within framework of price per volume unit. </li>
* <ul>
* <li> Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3) </li>
* <li> Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3) </li>
* <li> Larger's <u>cost</u> is less than Smaller, within framework of price per volume unit </li>
* </ul>
* </ul>
*
* <p> Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding
* with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup},
* has the smallest <u>cost</u> between containbles. </p>
*
* <p> After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to
* {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best
* solution between them. It's the initial sequence list of genetic algorithm. </p>
*
* @return Initial sequence list.
*/
protected initGenes(): GAWrapperArray;
/**
* Try to repack each wrappers to another type.
*
* @param $wrappers Wrappers to repack.
* @return Re-packed wrappers.
*/
protected repack($wrappers: WrapperArray): WrapperArray;
/**
* @inheritdoc
*/
TAG(): string;
/**
* @inheritdoc
*/
toXML(): samchon.library.XML;
}
}
declare namespace flex {
class TabNavigator extends React.Component<TabNavigatorProps, TabNavigatorProps> {
render(): JSX.Element;
private handle_change(index, event);
}
class NavigatorContent extends React.Component<NavigatorContentProps, NavigatorContentProps> {
render(): JSX.Element;
}
interface TabNavigatorProps extends React.Props<TabNavigator> {
selectedIndex?: number;
style?: React.CSSProperties;
}
interface NavigatorContentProps extends React.Props<NavigatorContent> {
label: string;
}
}
declare namespace boxologic {
/**
* A box, trying to pack into a {@link Pallet}.
@@ -589,7 +475,7 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
class PackerForm extends samchon.protocol.Entity {
class PackerForm extends protocol.Entity {
/**
* Form of Instances to pack.
*/
@@ -609,12 +495,12 @@ declare namespace bws.packer {
* @param wrapperArray Type of Wrappers to be used.
*/
constructor(instanceFormArray: InstanceFormArray, wrapperArray: WrapperArray);
construct(xml: samchon.library.XML): void;
construct(xml: library.XML): void;
optimize(): WrapperArray;
getInstanceFormArray(): InstanceFormArray;
getWrapperArray(): WrapperArray;
TAG(): string;
toXML(): samchon.library.XML;
toXML(): library.XML;
toPacker(): Packer;
}
/**
@@ -622,12 +508,12 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
class InstanceFormArray extends samchon.protocol.EntityArrayCollection<InstanceForm> {
class InstanceFormArray extends protocol.EntityArrayCollection<InstanceForm> {
/**
* Default Constructor.
*/
constructor();
createChild(xml: samchon.library.XML): InstanceForm;
createChild(xml: library.XML): InstanceForm;
TAG(): string;
CHILD_TAG(): string;
/**
@@ -645,7 +531,7 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
class InstanceForm extends samchon.protocol.Entity {
class InstanceForm extends protocol.Entity {
/**
* A duplicated Instance.
*/
@@ -661,7 +547,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
construct(xml: samchon.library.XML): void;
construct(xml: library.XML): void;
private createInstance(xml);
key(): any;
getInstance(): Instance;
@@ -679,7 +565,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
toXML(): samchon.library.XML;
toXML(): library.XML;
/**
* <p> Repeated {@link instance} to {@link InstanceArray}.
*
@@ -694,7 +580,7 @@ declare namespace bws.packer {
}
}
declare namespace bws.packer {
class WrapperArray extends samchon.protocol.EntityArrayCollection<Wrapper> {
class WrapperArray extends protocol.EntityArrayCollection<Wrapper> {
/**
* Default Constructor.
*/
@@ -702,7 +588,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
createChild(xml: samchon.library.XML): Wrapper;
createChild(xml: library.XML): Wrapper;
/**
* Get (calculate) price.
*/
@@ -756,7 +642,7 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
interface Instance extends samchon.protocol.IEntity {
interface Instance extends protocol.IEntity {
/**
* Get name.
*/
@@ -813,7 +699,7 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
class InstanceArray extends samchon.protocol.EntityArray<Instance> {
class InstanceArray extends protocol.EntityArray<Instance> {
/**
* Default Constructor.
*/
@@ -821,7 +707,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
createChild(xml: samchon.library.XML): Instance;
createChild(xml: library.XML): Instance;
/**
* @inheritdoc
*/
@@ -832,13 +718,113 @@ declare namespace bws.packer {
CHILD_TAG(): string;
}
}
declare namespace bws.packer {
/**
* @brief Packer, a solver of 3d bin packing with multiple wrappers.
*
* @details
* <p> Packer is a facade class supporting packing operations in user side. You can solve a packing problem
* by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to
* pack and executing {@link optimize Packer.optimize()} method. </p>
*
* <p> In background side, deducting packing solution, those algorithms are used. </p>
* <ul>
* <li> <a href="http://betterwaysystems.github.io/packer/reference/AirForceBinPacking.pdf" target="_blank">
* Airforce Bin Packing; 3D pallet packing problem: A human intelligence-based heuristic approach </a>
* </li>
* <li> Genetic Algorithm </li>
* <li> Greedy and Back-tracking algorithm </li>
* </ul>
*
* @author Jeongho Nam <http://samchon.org>
*/
class Packer extends protocol.Entity {
/**
* Candidate wrappers who can contain instances.
*/
protected wrapperArray: WrapperArray;
/**
* Instances trying to pack into the wrapper.
*/
protected instanceArray: InstanceArray;
/**
* Default Constructor.
*/
constructor();
/**
* Construct from members.
*
* @param wrapperArray Candidate wrappers who can contain instances.
* @param instanceArray Instances to be packed into some wrappers.
*/
constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray);
/**
* @inheritdoc
*/
construct(xml: library.XML): void;
/**
* Get wrapperArray.
*/
getWrapperArray(): WrapperArray;
/**
* Get instanceArray.
*/
getInstanceArray(): InstanceArray;
/**
* <p> Deduct
*
*/
optimize(): WrapperArray;
/**
* @brief Initialize sequence list (gene_array).
*
* @details
* <p> Deducts initial sequence list by such assumption: </p>
*
* <ul>
* <li> Cost of larger wrapper is less than smaller one, within framework of price per volume unit. </li>
* <ul>
* <li> Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3) </li>
* <li> Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3) </li>
* <li> Larger's <u>cost</u> is less than Smaller, within framework of price per volume unit </li>
* </ul>
* </ul>
*
* <p> Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding
* with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup},
* has the smallest <u>cost</u> between containbles. </p>
*
* <p> After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to
* {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best
* solution between them. It's the initial sequence list of genetic algorithm. </p>
*
* @return Initial sequence list.
*/
protected initGenes(): GAWrapperArray;
/**
* Try to repack each wrappers to another type.
*
* @param $wrappers Wrappers to repack.
* @return Re-packed wrappers.
*/
protected repack($wrappers: WrapperArray): WrapperArray;
/**
* @inheritdoc
*/
TAG(): string;
/**
* @inheritdoc
*/
toXML(): library.XML;
}
}
declare namespace bws.packer {
/**
* A product.
*
* @author Jeongho Nam <http://samchon.org>
*/
class Product extends samchon.protocol.Entity implements Instance {
class Product extends protocol.Entity implements Instance {
/**
* <p> Name, key of the Product. </p>
*
@@ -921,7 +907,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
toXML(): samchon.library.XML;
toXML(): library.XML;
}
}
declare namespace bws.packer {
@@ -937,7 +923,7 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
class Wrap extends samchon.protocol.Entity {
class Wrap extends protocol.Entity {
/**
* A wrapper wrapping the {@link instance}.
*/
@@ -962,10 +948,6 @@ declare namespace bws.packer {
* Placement orientation of wrapped {@link instance}.
*/
protected orientation: number;
/**
*
*/
protected color: number;
/**
* Construct from a Wrapper.
*
@@ -996,7 +978,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
construct(xml: samchon.library.XML): void;
construct(xml: library.XML): void;
/**
* Factory method of wrapped Instance.
*
@@ -1058,11 +1040,11 @@ declare namespace bws.packer {
/**
* Get width.
*/
getWidth(): number;
getLayoutWidth(): number;
/**
* Get height.
*/
getHeight(): number;
getLayoutHeight(): number;
/**
* Get length.
*/
@@ -1071,9 +1053,9 @@ declare namespace bws.packer {
* Get volume.
*/
getVolume(): number;
$instanceName: string;
$layoutScale: string;
$position: string;
readonly $instanceName: string;
readonly $layoutScale: string;
readonly $position: string;
/**
* @inheritdoc
*/
@@ -1081,19 +1063,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
toXML(): samchon.library.XML;
/**
* Thickness of boundary lines of a shape represents the {@link instance}.
*/
private static BOUNDARY_THICKNESS;
/**
*
*
* @param geometry
*
* @return A shape and its boundary lines as 3D-objects.
*/
toDisplayObjects(geometry: THREE.Geometry): std.Vector<THREE.Object3D>;
toXML(): library.XML;
}
}
declare namespace bws.packer {
@@ -1102,7 +1072,7 @@ declare namespace bws.packer {
*
* @author Jeongho Nam <http://samchon.org>
*/
class Wrapper extends samchon.protocol.EntityDeque<Wrap> implements Instance {
class Wrapper extends protocol.EntityDeque<Wrap> implements Instance {
/**
* <p> Name, key of the Wrapper. </p>
*
@@ -1151,11 +1121,10 @@ declare namespace bws.packer {
* @param thickness A thickness causes shrinkness on containable volume.
*/
constructor(name: string, price: number, width: number, height: number, length: number, thickness: number);
construct(xml: samchon.library.XML): void;
/**
* @inheritdoc
*/
createChild(xml: samchon.library.XML): Wrap;
createChild(xml: library.XML): Wrap;
/**
* Key of a Wrapper is its name.
*/
@@ -1232,7 +1201,7 @@ declare namespace bws.packer {
* @return utilization ratio.
*/
getUtilization(): number;
equal_to(obj: Wrapper): boolean;
equals(obj: Wrapper): boolean;
/**
* <p> Wrapper is enough greater? </p>
*
@@ -1272,8 +1241,8 @@ declare namespace bws.packer {
$height: string;
$length: string;
$thickness: string;
$scale: string;
$spaceUtilization: string;
readonly $scale: string;
readonly $spaceUtilization: string;
/**
* @inheritdoc
*/
@@ -1289,25 +1258,7 @@ declare namespace bws.packer {
/**
* @inheritdoc
*/
toXML(): samchon.library.XML;
private static scene;
private static renderer;
private static camera;
private static trackball;
private static mouse;
private static BOUNDARY_THICKNESS;
/**
* <p> Convert to a canvas containing 3D elements. </p>
*
* @param endIndex
*
* @return A 3D-canvans printing the Wrapper and its children {@link Wrap wrapped}
* {@link Instance instances} with those boundary lines.
*/
toCanvas(endIndex?: number): HTMLCanvasElement;
private static handleMouseMove(event);
private static animate();
private static render();
toXML(): library.XML;
}
}
declare namespace bws.packer {
@@ -1430,72 +1381,3 @@ declare namespace bws.packer {
TAG(): string;
}
}
declare namespace bws.packer {
abstract class Editor<T extends samchon.protocol.IEntity> extends React.Component<{
dataProvider: samchon.protocol.EntityArrayCollection<T>;
}, {}> {
private columns;
private selected_index;
/**
* Default Constructor.
*/
constructor();
protected abstract createColumns(): AdazzleReactDataGrid.Column[];
private get_row(index);
private insert_instance(event);
private erase_instances(event);
private handle_data_change(event);
private handle_row_change(event);
private handle_select(event);
render(): JSX.Element;
}
}
declare namespace bws.packer {
interface ItemEditorProps extends React.Props<ItemEditor> {
application: PackerApplication;
instances: InstanceFormArray;
wrappers: WrapperArray;
}
class ItemEditor extends React.Component<ItemEditorProps, {}> {
private clear(event);
private open(event);
private save(event);
private pack(event);
render(): JSX.Element;
}
class InstanceEditor extends Editor<InstanceForm> {
protected createColumns(): AdazzleReactDataGrid.Column[];
}
class WrapperEditor extends Editor<Wrapper> {
protected createColumns(): AdazzleReactDataGrid.Column[];
}
}
declare namespace bws.packer {
class PackerApplication extends React.Component<{}, {}> {
private instances;
private wrappers;
private result;
/**
* Default Constructor.
*/
constructor();
pack(): void;
drawWrapper(wrapper: Wrapper, index?: number): void;
render(): JSX.Element;
static main(): void;
}
}
declare namespace bws.packer {
class ResultViewer extends React.Component<WrapperViewerProps, {}> {
drawWrapper(wrapper: Wrapper, index?: number): void;
private clear(event);
private open(event);
private save(event);
refresh(): void;
render(): JSX.Element;
}
interface WrapperViewerProps extends React.Props<ResultViewer> {
application: PackerApplication;
wrappers: WrapperArray;
}
}
+3
View File
@@ -67,3 +67,6 @@ acorn.getLineInfo('string', 56);
acorn.plugins['test'] = function (p: acorn.Parser, config: any) {
}
acorn.tokenizer('console.log("hello world)', {locations: true}).getToken();
acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next();
+6 -3
View File
@@ -238,9 +238,12 @@ declare namespace acorn {
function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression;
// todo: here the tokenizer function returns a Parser instance, that is targeting the detail of
// Parser prototype. Someone need this please reade README.md first.
// function tokenizer(options: Options, input: string): Parser;
interface ITokenizer {
getToken() : Token,
[Symbol.iterator](): Iterator<Token>
}
function tokenizer(input: string, options: Options): ITokenizer;
let parse_dammit: IParse | undefined;
let LooseParser: ILooseParserClass | undefined;
+1 -1
View File
@@ -11,7 +11,7 @@ declare module 'angular' {
export namespace dynamicLocale {
interface tmhDynamicLocaleService {
set(locale: string): void;
set(locale: string): angular.IPromise<string>;
get(): string;
}
+10
View File
@@ -0,0 +1,10 @@
import * as angular from 'angular';
angular.module('angular-oauth2-test', ['angular-oauth2'])
.config(['OAuthProvider', function(OAuthProvider:angular.oauth2.OAuthProvider){
OAuthProvider.configure({
baseUrl: 'https://api.website.com',
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET' // optional
});
}]);
+49
View File
@@ -0,0 +1,49 @@
// Type definitions for angular-oauth2 4.1
// Project: https://github.com/oauthjs/angular-oauth2
// Definitions by: Antério Vieira <https://github.com/anteriovieira>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as angular from 'angular';
declare module 'angular' {
export namespace oauth2 {
interface OAuthConfig {
baseUrl: string;
clientId: string;
clientSecret?: string;
grantPath?: string;
revokePath?: string;
}
interface OAuthProvider {
configure(params: OAuthConfig): OAuthConfig;
}
interface Data {
username: string;
password: string;
}
interface OAuth {
isAuthenticated(): boolean;
getAccessToken(data: Data, options?: any): angular.IPromise<string>;
getRefreshToken(data?: Data, options?: any): angular.IPromise<string>;
revokeToken(data?: Data, options?: any): angular.IPromise<string>;
}
interface OAuthTokenConfig {
name: string;
options: any;
}
interface OAuthTokenOptions {
secure: boolean;
}
interface OAuthTokenProvider {
configure(params: OAuthTokenConfig): OAuthTokenConfig;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"angular-oauth2-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
-483
View File
@@ -1,483 +0,0 @@
/// <reference types="react" />
/*import {
Affix,
Button,
Alert,
Badge,
Breadcrumb,
Calendar,
Carousel,
Cascader,
Checkbox,
Collapse,
DatePicker,
Dropdown,
Icon,
Form,
Input,
InputNumber,
Row,
Col,
Menu,
message,
Modal,
notification,
Pagination,
Popconfirm,
Popover,
Progress,
QueueAnim,
Radio,
Select,
Slider,
Spin,
Steps,
Switch,
Table,
Tabs,
Tag,
TimePicker,
Timeline,
Tooltip,
Transfer,
Tree,
TreeSelect,
Upload,
} from 'antd';*/
import * as React from 'react'
import Affix from 'antd/lib/Affix'
import Button from 'antd/lib/Button'
import Alert from 'antd/lib/Alert'
import Badge from 'antd/lib/Badge'
import Breadcrumb from 'antd/lib/Breadcrumb'
import Calendar from 'antd/lib/Calendar'
import Carousel from 'antd/lib/Carousel'
import Cascader from 'antd/lib/Cascader'
import Checkbox from 'antd/lib/Checkbox'
import Collapse from 'antd/lib/Collapse'
import DatePicker from 'antd/lib/DatePicker'
import Dropdown from 'antd/lib/Dropdown'
import Icon from 'antd/lib/Icon'
import Form from 'antd/lib/Form'
import Input from 'antd/lib/Input'
import InputNumber from 'antd/lib/InputNumber'
import Row from 'antd/lib/Row'
import Col from 'antd/lib/Col'
import Menu from 'antd/lib/Menu'
import message from 'antd/lib/message'
import Modal from 'antd/lib/Modal'
import notification from 'antd/lib/notification'
import Pagination from 'antd/lib/Pagination'
import Popconfirm from 'antd/lib/Popconfirm'
import Popover from 'antd/lib/Popover'
import Progress from 'antd/lib/Progress'
import QueueAnim from 'antd/lib/QueueAnim'
import Radio from 'antd/lib/Radio'
import Select from 'antd/lib/Select'
import Slider from 'antd/lib/Slider'
import Spin from 'antd/lib/Spin'
import Steps from 'antd/lib/Steps'
import Switch from 'antd/lib/Switch'
import Table from 'antd/lib/Table'
import Tabs from 'antd/lib/Tabs'
import Tag from 'antd/lib/Tag'
import TimePicker from 'antd/lib/TimePicker'
import Timeline from 'antd/lib/Timeline'
import Tooltip from 'antd/lib/Tooltip'
import Transfer from 'antd/lib/Transfer'
import Tree from 'antd/lib/Tree'
import TreeSelect from 'antd/lib/TreeSelect'
import Upload from 'antd/lib/Upload'
const ButtonGroup = Button.Group;
const CheckboxGroup = Checkbox.Group;
const Panel = Collapse.Panel;
const RangePicker = DatePicker.RangePicker;
const MonthPicker = DatePicker.MonthPicker;
const DropdownButton = Dropdown.Button;
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
const ProgressCircle = Progress.Circle;
const ProgressLine = Progress.Line;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const OptGroup = Select.OptGroup;
const Step = Steps.Step;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;
const TreeSelectTreeNode = TreeSelect.TreeNode;
const onChange = () => { }
const options = [{
value: 'zhejiang',
label: '浙江',
children: [{
value: 'hangzhou',
label: '杭州',
children: [{
value: 'xihu',
label: '西湖',
}],
}],
}, {
value: 'jiangsu',
label: '江苏',
children: [{
value: 'nanjing',
label: '南京',
children: [{
value: 'zhonghuamen',
label: '中华门',
}],
}],
}];
const columns = [{
title: '姓名',
dataIndex: 'name',
key: 'name',
render(text: any) {
return <a href="#">{text}</a>;
}
}, {
title: '年龄',
dataIndex: 'age',
key: 'age',
}, {
title: '住址',
dataIndex: 'address',
key: 'address',
}, {
title: '操作',
key: 'operation',
render(text: any, record: any) {
return (
<span>
<a href="#">{record.name}</a>
<span className="ant-divider"></span>
<a href="#"></a>
<span className="ant-divider"></span>
<a href="#" className="ant-dropdown-link">
<Icon type="down" />
</a>
</span>
);
}
}];
const data = [{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号'
}, {
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号'
}, {
key: '3',
name: '李大嘴',
age: 32,
address: '西湖区湖底公园1号'
}];
// tests
class AccountForm extends React.Component<any, any>{
render() {
const { getFieldProps } = this.props.form;
return (
<Form inline>
<FormItem
label="账户:">
<Input placeholder="请输入账户名"
{...getFieldProps('userName') } />
</FormItem>
<FormItem
label="密码:">
<Input type="password" placeholder="请输入密码"
{...getFieldProps('password') } />
</FormItem>
<FormItem>
<label className="ant-checkbox-inline">
<Checkbox
{...getFieldProps('agreement') } />
</label>
</FormItem>
<Button type="primary" htmlType="submit"></Button>
</Form>
);
}
}
var Account = Form.create()(AccountForm);
// app
class App extends React.Component<any, any>{
render() {
message.success('success')
message.config({ top: 100 })
message.destroy()
message.info('info', 1000)
message.error('error', 3500)
Modal.info({ title: 'hello' });
Modal.success({ cancelText: 'No' })
notification.success({
message: 'hello',
description: 'test'
})
const props = {
name: 'file',
action: '/upload.do',
onChange(info: any) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
message.success(`${info.file.name} 上传成功。`);
} else if (info.file.status === 'error') {
message.error(`${info.file.name} 上传失败。`);
}
}
};
return <div>
<Affix>Affix</Affix>
<Row>
<Col>test</Col>
</Row>
<Alert message="Hello" type='info' closable={true}/>
<Badge count={10}/>
<Button type='primary'>Primary Button</Button>
<ButtonGroup>
<Button type='primary'>Primary Button</Button>
<Button type='ghost'>Primary Button</Button>
</ButtonGroup>
<Breadcrumb>
<Breadcrumb.Item></Breadcrumb.Item>
<Breadcrumb.Item href=""></Breadcrumb.Item>
<Breadcrumb.Item href=""></Breadcrumb.Item>
<Breadcrumb.Item></Breadcrumb.Item>
</Breadcrumb>
<Calendar/>
<Carousel autoplay>
<div><h3>1</h3></div>
<div><h3>2</h3></div>
<div><h3>3</h3></div>
<div><h3>4</h3></div>
</Carousel>
<Cascader options={options} />
<CheckboxGroup options={['Apple', 'Pear', 'Orange']} defaultValue={['Apple']} onChange={onChange} />
<Collapse defaultActiveKey={['1']}>
<Panel header="This is panel header 1" key="1">
<p>test1</p>
</Panel>
<Panel header="This is panel header 2" key="2">
<p>test2</p>
</Panel>
<Panel header="This is panel header 3" key="3">
<p>test3</p>
</Panel>
</Collapse>
<DatePicker defaultValue="2015-01-01" />
<RangePicker showTime format="yyyy/MM/dd HH:mm:ss" onChange={onChange} />
<MonthPicker defaultValue="2015-12" />
<Dropdown trigger={['click']} overlay={<div>Hello Dp</div>}>
<a className="ant-dropdown-link" href="#">
<Icon type="down" />
</a>
</Dropdown>
<DropdownButton overlay={<p>dpb</p>} type="primary">
</DropdownButton>
<InputNumber min={0} max={10}/>
<Menu
selectedKeys={[this.state.current]}
theme={this.state.theme}
mode="horizontal">
<Menu.Item key="mail">
<Icon type="mail" />
</Menu.Item>
<SubMenu title={<span><Icon type="setting" /> - </span>}>
<MenuItemGroup title="分组1">
<Menu.Item key="setting:1">1</Menu.Item>
<Menu.Item key="setting:2">2</Menu.Item>
</MenuItemGroup>
<MenuItemGroup title="分组2">
<Menu.Item key="setting:3">3</Menu.Item>
<Menu.Item key="setting:4">4</Menu.Item>
</MenuItemGroup>
</SubMenu>
</Menu>
<Modal title='Modal .....' maskClosable/>
<Pagination defaultCurrent={1} total={50} />,
<Popconfirm title="confirm .">
<a href="#">remove</a>
</Popconfirm>
<Popover overlay={<div>Overlay</div>} title="title">
<Button type="primary">display card</Button>
</Popover>
<ProgressCircle percent={75} />
<ProgressCircle percent={70} status="exception" />
<ProgressCircle percent={100} />
<ProgressLine percent={30} />
<ProgressLine percent={50} status="active" />
<ProgressLine percent={70} status="exception" />
<ProgressLine percent={100} />
<ProgressLine percent={50} showInfo={false} />
<QueueAnim>
<div key='demo1'>demo1</div>
<div key='demo2'>demo2</div>
<div key='demo3'>demo3</div>
<div key='demo4'>demo4</div>
</QueueAnim>
<RadioGroup>
<Radio key="a" value={1}>A</Radio>
<Radio key="b" value={2}>B</Radio>
<Radio key="c" value={3}>C</Radio>
<Radio key="d" value={null}>D</Radio>
</RadioGroup>
<Select defaultValue="lucy"
style={{ width: 200 }}
showSearch={false}>
<OptGroup label="Manager">
<Option value="jack">jack</Option>
<Option value="lucy">lucy</Option>
</OptGroup>
<OptGroup label="Engineer">
<Option value="yiminghe">yiminghe</Option>
</OptGroup>
</Select>
<Select defaultValue="lucy" style={{ width: 120 }} disabled>
<Option value="lucy">Lucy</Option>
</Select>
<Slider defaultValue={30} />
<Slider range defaultValue={[20, 50]} />
<Slider range defaultValue={[20, 50]} disabled />
<Spin />
<Step status="finish" title="步骤1" icon="cloud" />
<Step status="process" title="步骤2" icon="apple" />
<Step status="wait" title="步骤3" icon="github" />
<Switch defaultChecked={false} onChange={onChange} />,
<Tabs defaultActiveKey="1" onChange={onChange}>
<TabPane tab="选项卡一" key="1"></TabPane>
<TabPane tab="选项卡二" key="2"></TabPane>
<TabPane tab="选项卡三" key="3"></TabPane>
</Tabs>
<Tag></Tag>
<Tag></Tag>
<Tag closable onClose={() => { } }></Tag>
<Tag><a href="https://www.alipay.com/" target="_blank"></a></Tag>
<TimePicker onChange={onChange} />
<Timeline>
<Timeline.Item> 2015-09-01</Timeline.Item>
<Timeline.Item> 2015-09-01</Timeline.Item>
<Timeline.Item> 2015-09-01</Timeline.Item>
<Timeline.Item> 2015-09-01</Timeline.Item>
</Timeline>
<Tooltip title="提示文字">
<span></span>
</Tooltip>
<Transfer
dataSource={this.state.mockData}
targetKeys={this.state.targetKeys}
onChange={onChange} />
<Tree className="myCls" showLine multiple checkable
defaultExpandedKeys={this.state.defaultExpandedKeys}
defaultSelectedKeys={this.state.defaultSelectedKeys}
defaultCheckedKeys={this.state.defaultCheckedKeys}
>
<TreeNode title="parent 1" key="0-0">
<TreeNode title="parent 1-0" key="0-0-0" disabled>
<TreeNode title="leaf" key="0-0-0-0" disableCheckbox />
<TreeNode title="leaf" key="0-0-0-1" />
</TreeNode>
<TreeNode title="parent 1-1" key="0-0-1">
<TreeNode title={<span style={{ color: '#08c' }}>sss</span>} key="0-0-1-0" />
</TreeNode>
</TreeNode>
</Tree>
<Upload {...props}>
<Button type="ghost">
<Icon type="upload" />
</Button>
</Upload>
<TreeSelect style={{ width: 300 }}
value={this.state.value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="请选择"
allowClear
treeDefaultExpandAll
onChange={onChange}>
<TreeSelectTreeNode value="parent 1" title="parent 1" key="0-1">
<TreeSelectTreeNode value="parent 1-0" title="parent 1-0" key="0-1-1">
<TreeSelectTreeNode value="leaf1" title="my leaf" key="random" />
<TreeSelectTreeNode value="leaf2" title="your leaf" key="random1" />
</TreeSelectTreeNode>
<TreeSelectTreeNode value="parent 1-1" title="parent 1-1" key="random2">
<TreeSelectTreeNode value="sss" title={<b style={{ color: '#08c' }}>sss</b>} key="random3" />
</TreeSelectTreeNode>
</TreeSelectTreeNode>
</TreeSelect>
<Table columns={columns} dataSource={data}/>
</div>
}
}
-2083
View File
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,3 @@
// More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md
var config: Microsoft.ApplicationInsights.IConfig = {
@@ -24,7 +23,11 @@ var config: Microsoft.ApplicationInsights.IConfig = {
disableCorrelationHeaders: true,
disableFlushOnBeforeUnload: false,
enableSessionStorageBuffer: false,
cookieDomain: ""
cookieDomain: "",
isCookieUseDisabled: true,
isRetryDisabled: true,
isPerfAnalyzerEnabled: true,
isStorageUseDisabled: true
};
var appInsights: Microsoft.ApplicationInsights.IAppInsights = {
@@ -35,17 +38,17 @@ var appInsights: Microsoft.ApplicationInsights.IAppInsights = {
startTrackPage(name?: string) { return null; },
stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; },
startTrackEvent(name: string) { return null },
stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null },
trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null },
trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null },
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null },
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null },
trackTrace(message: string, properties?: { [name: string]: string; }) { return null },
flush() { return null },
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null },
clearAuthenticatedUserContext() { return null },
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null }
startTrackEvent(name: string) { return null; },
stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; },
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; },
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; },
trackTrace(message: string, properties?: { [name: string]: string; }) { return null; },
flush() { return null; },
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; },
clearAuthenticatedUserContext() { return null; },
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null; }
};
// trackPageView
@@ -75,6 +78,9 @@ appInsights.trackException(new Error("sample error"), "handledAt", null, null);
appInsights.trackTrace("message");
appInsights.trackTrace("message", null);
// trackDependency
appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null);
// flush
appInsights.flush();
+22 -18
View File
@@ -1,4 +1,4 @@
// Type definitions for ApplicationInsights-JS v0.23.2
// Type definitions for ApplicationInsights-JS 1.0
// Project: https://github.com/Microsoft/ApplicationInsights-JS
// Definitions by: Kamil Szostak <https://github.com/kamilszostak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -323,7 +323,7 @@ declare module Microsoft.ApplicationInsights.Telemetry {
/**
* Constructs a new instance of the EventTelemetry object
*/
constructor(name: string, properties?: Object, measurements?: Object);
constructor(name: string, properties?: any, measurements?: any);
}
class Exception implements Microsoft.ApplicationInsights.ISerializable {
@@ -348,7 +348,7 @@ declare module Microsoft.ApplicationInsights.Telemetry {
/**
* Constructs a new isntance of the ExceptionTelemetry object
*/
constructor(exception: Error, handledAt?: string, properties?: Object, measurements?: Object, severityLevel?: AI.SeverityLevel);
constructor(exception: Error, handledAt?: string, properties?: any, measurements?: any, severityLevel?: AI.SeverityLevel);
/**
* Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.
*/
@@ -369,7 +369,7 @@ declare module Microsoft.ApplicationInsights.Telemetry {
/**
* Constructs a new instance of the MetricTelemetry object
*/
constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: Object);
constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: any);
}
class PageView extends AI.PageViewData implements Microsoft.ApplicationInsights.ISerializable {
@@ -477,7 +477,7 @@ declare module Microsoft.ApplicationInsights.Telemetry {
/**
* Constructs a new instance of the MetricTelemetry object
*/
constructor(message: string, properties?: Object);
constructor(message: string, properties?: any);
}
}
@@ -567,8 +567,12 @@ declare module Microsoft.ApplicationInsights {
disableCorrelationHeaders?: boolean;
disableFlushOnBeforeUnload?: boolean;
enableSessionStorageBuffer?: boolean;
isCookieUseDisabled?: boolean;
cookieDomain?: string;
isRetryDisabled?: boolean;
isPerfAnalyzerEnabled?: boolean;
url?: string;
isStorageUseDisabled?: boolean;
}
/**
@@ -657,7 +661,7 @@ declare module Microsoft.ApplicationInsights {
interface IAppInsights {
config: IConfig;
context: ITelemetryContext;
queue: (() => void)[];
queue: Array<() => void>;
/**
* Starts timing how long the user views a page or other item. Call this when the page opens.
* This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes.
@@ -717,16 +721,16 @@ declare module Microsoft.ApplicationInsights {
[name: string]: number;
}): any;
/**
* Log an AJAX request
* @param id Event id
* @param absoluteUrl Full url
* @param pathName Leave this parameter blank
* @param totalTime Total time it took for AJAX request to complete
* @param success Whether AJAX request succeeded or failed
* @param resultCode Result code returned from AJAX call
* @param method HTTP verb that was used (GET, POST)
*/
trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any;
* Log a dependency call
* @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id.
* @param method represents request verb (GET, POST, etc.)
* @param absoluteUrl absolute url used to make the dependency request
* @param pathName the path part of the absolute url
* @param totalTime total request time
* @param success indicates if the request was sessessful
* @param resultCode response code returned by the dependency request
*/
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any;
/**
* Log an exception you have caught.
* @param exception An Error from a catch clause, or the string error message.
@@ -755,7 +759,7 @@ declare module Microsoft.ApplicationInsights {
/**
* Log a diagnostic message.
* @param message A message string
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
*/
trackTrace(message: string, properties?: {
[name: string]: string;
@@ -776,7 +780,7 @@ declare module Microsoft.ApplicationInsights {
* Clears the authenticated user id and the account id from the user context.
*/
clearAuthenticatedUserContext(): any;
downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void;
downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): any;
/**
* The custom error handler for Application Insights
* @param {string} message - The error message
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../tslint.json",
"rules": {
"interface-name": [ false ],
"no-internal-module": false,
"no-single-declare-module": false
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
import 'auth0-js';
import * as auth0 from 'auth0-js';
let webAuth = new auth0.WebAuth({
domain: 'mine.auth0.com',
@@ -64,7 +64,7 @@ webAuth.signupAndAuthorize({
webAuth.client.login({
ealm: 'Username-Password-Authentication', //connection name or HRD domain
realm: 'Username-Password-Authentication', //connection name or HRD domain
username: 'info@auth0.com',
password: 'areallystrongpassword',
audience: 'https://mystore.com/api/v2',
+492 -437
View File
@@ -1,456 +1,511 @@
// Type definitions for Auth0.js 8.1
// Type definitions for Auth0.js 8.2
// Project: https://github.com/auth0/auth0.js
// Definitions by: Adrian Chia <https://github.com/adrianchia>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace auth0 {
export as namespace auth0;
export class Authentication {
constructor(options: AuthOptions);
passwordless: PasswordlessAuthentication;
dbConnection: DBConnection;
export class Authentication {
constructor(options: AuthOptions);
/**
* Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction
*
* @method buildAuthorizeUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
buildAuthorizeUrl(options: any): string;
passwordless: PasswordlessAuthentication;
dbConnection: DBConnection;
/**
* Builds and returns the Logout url in order to initialize a new authN/authZ transaction
*
* @method buildLogoutUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
buildLogoutUrl(options?: any): string;
/**
* Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction
*
* @method buildAuthorizeUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
buildAuthorizeUrl(options: any): string;
/**
* Makes a call to the `oauth/token` endpoint with `password` grant type
*
* @method loginWithDefaultDirectory
* @param {Object} options: https://auth0.com/docs/api-auth/grant/password
* @param {Function} callback
*/
loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Builds and returns the Logout url in order to initialize a new authN/authZ transaction
*
* @method buildLogoutUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
buildLogoutUrl(options?: any): string;
/**
* Makes a call to the `/ro` endpoint
* @param {any} options
* @param {Function} callback
* @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead.
*/
loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint with `password` grant type
*
* @method loginWithDefaultDirectory
* @param {Object} options: https://auth0.com/docs/api-auth/grant/password
* @param {Function} callback
*/
loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint with `password-realm` grant type
* @param {any} options
* @param {Function} callback
*/
login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ro` endpoint
* @param {any} options
* @param {Function} callback
* @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead.
*/
loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint
* @param {any} options
* @param {Function} callback
*/
oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint with `password-realm` grant type
* @param {any} options
* @param {Function} callback
*/
login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
* @deprecated `getSSOData` will be soon deprecated.
*/
getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint
* @param {any} options
* @param {Function} callback
*/
oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
* @deprecated `getSSOData` will be soon deprecated.
*/
getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
* @deprecated `getSSOData` will be soon deprecated.
*/
getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/userinfo` endpoint and returns the user profile
*
* @method userInfo
* @param {String} accessToken
* @param {Function} callback
*/
userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
* @deprecated `getSSOData` will be soon deprecated.
*/
getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/delegation` endpoint
*
* @method delegation
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation
* @param {Function} callback
* @deprecated `delegation` will be soon deprecated.
*/
delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any;
/**
* Makes a call to the `/userinfo` endpoint and returns the user profile
*
* @method userInfo
* @param {String} accessToken
* @param {Function} callback
*/
userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Fetches the user country based on the ip.
*
* @method getUserCountry
* @param {Function} callback
*/
getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void;
}
export class PasswordlessAuthentication {
constructor(request: any, option: any);
/**
* Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction
*
* @method buildVerifyUrl
* @param {Object} options
* @param {Function} callback
*/
buildVerifyUrl(options: any): string;
/**
* Initializes a new passwordless authN/authZ transaction
*
* @method start
* @param {Object} options: https://auth0.com/docs/api/authentication#passwordless
* @param {Function} callback
*/
start(options: PasswordlessStartOptions, callback: any): void;
/**
* Verifies the passwordless TOTP and returns an error if any.
*
* @method buildVerifyUrl
* @param {Object} options
* @param {Function} callback
*/
verify(options: any, callback: any): void;
}
export class DBConnection {
constructor(request: any, option: any);
/**
* Signup a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} calback
*/
signup(options: any, callback: any): void;
/**
* Initializes the change password flow
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: ChangePasswordOptions, callback: any): void;
}
export class Management {
constructor(options: ManagementOptions);
/**
* Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id
*
* @method getUser
* @param {String} userId
* @param {Function} callback
*/
getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Updates the user metdata. It will patch the user metdata with the attributes sent.
* https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
*
* @method patchUserMetadata
* @param {String} userId
* @param {Object} userMetadata
* @param {Function} callback
*/
patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities
*
* @method linkUser
* @param {String} userId
* @param {String} secondaryUserToken
* @param {Function} callback
*/
linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void;
}
export class WebAuth {
constructor(options: AuthOptions);
client: Authentication;
popup: Popup;
redirect: Redirect;
/**
* Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
authorize(options: any): void;
/**
* Parse the url hash and extract the returned tokens depending on the transaction.
*
* Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed
* by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be
* accepted.
*
* @method parseHash
* @param {Object} options:
* @param {String} options.state [OPTIONAL] to verify the response
* @param {String} options.nonce [OPTIONAL] to verify the id_token
* @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash
* @param {Function} callback: any(err, token_payload)
*/
parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Decodes the id_token and verifies the nonce.
*
* @method validateToken
* @param {String} token
* @param {String} state
* @param {String} nonce
* @param {Function} callback: function(err, {payload, transaction})
*/
validateToken(token: string, state: string, nonce: string, callback: any): void;
/**
* Executes a silent authentication transaction under the hood in order to fetch a new token.
*
* @method renewAuth
* @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint
* @param {Function} callback
*/
renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Initialices a change password transaction
*
* @method changePassword
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Signs up a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signup(options: any, callback: any): void;
/**
* Signs up a new user, automatically logs the user in after the signup and returns the user token.
* The login will be done using /oauth/token with password-realm grant type.
*
* @method signupAndAuthorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Redirects to the auth0 logout page
*
* @method logout
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
logout(options: any): void;
passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void;
/**
* Verifies the passwordless TOTP and redirects to finish the passwordless transaction
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: any): void;
}
export class Redirect {
constructor(client: any, options: any);
/**
* Initializes the legacy Lock login flow in a popup
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
*/
loginWithCredentials(options: any, callback: any): void;
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndLogin(options: any, callback: any): void;
}
export class Popup {
constructor(client: any, options: any);
/**
* Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser.
*
* @method preload
* @param {Object} options: receives the window height and width and any other window feature to be sent to window.open
*/
preload(options: any): any;
/**
* Internal use.
*
* @method getPopupHandler
*/
getPopupHandler(options: any, preload: boolean): any;
/**
* Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
* @param {Function} callback
*/
authorize(options: any, callback: any): void;
/**
* Initializes the legacy Lock login flow in a popup
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
*/
loginWithCredentials(options: any, callback: any): void;
/**
* Verifies the passwordless TOTP and returns the requested token
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: any): void;
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndLogin(options: any, callback: any): void;
}
interface ManagementOptions {
domain: string;
token: string;
_sendTelemetry?: boolean;
_telemetryInfo?: any;
}
interface AuthOptions {
domain: string;
clientID: string;
responseType?: string;
responseMode?: string;
redirectUri?: string;
scope?: string;
audience?: string;
leeway?: number;
_disableDeprecationWarnings?: boolean;
_sendTelemetry?: boolean;
_telemetryInfo?: any;
}
interface PasswordlessAuthOptions {
connection: string;
verificationCode: string;
phoneNumber: string;
email: string;
}
interface Auth0Error {
error: any;
errorDescription: string;
}
interface Auth0DecodedHash {
accessToken?: string;
idToken?: string;
idTokenPayload?: any;
refreshToken?: string;
state?: string;
expiresIn?: number;
tokenType?: string;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
ExpiresIn: number;
/** The JWT for delegated access. */
idToken: string;
/** The type of token being returned. Possible values: "Bearer" */
tokenType: string;
}
interface ChangePasswordOptions {
connection: string;
email: string;
password?: string;
}
interface PasswordlessStartOptions {
connection: string;
send: string;
phoneNumber?: string;
email?: string;
authParams?: any;
}
interface PasswordlessVerifyOptions {
connection: string;
verificationCode: string;
phoneNumber?: string;
email?: string;
}
/**
* Makes a call to the `/delegation` endpoint
*
* @method delegation
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation
* @param {Function} callback
* @deprecated `delegation` will be soon deprecated.
*/
delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any;
/**
* Fetches the user country based on the ip.
*
* @method getUserCountry
* @param {Function} callback
*/
getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void;
}
export class PasswordlessAuthentication {
constructor(request: any, option: any);
/**
* Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction
*
* @method buildVerifyUrl
* @param {Object} options
* @param {Function} callback
*/
buildVerifyUrl(options: any): string;
/**
* Initializes a new passwordless authN/authZ transaction
*
* @method start
* @param {Object} options: https://auth0.com/docs/api/authentication#passwordless
* @param {Function} callback
*/
start(options: PasswordlessStartOptions, callback: any): void;
/**
* Verifies the passwordless TOTP and returns an error if any.
*
* @method buildVerifyUrl
* @param {Object} options
* @param {Function} callback
*/
verify(options: any, callback: any): void;
}
export class DBConnection {
constructor(request: any, option: any);
/**
* Signup a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} calback
*/
signup(options: any, callback: any): void;
/**
* Initializes the change password flow
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: ChangePasswordOptions, callback: any): void;
}
export class Management {
constructor(options: ManagementOptions);
/**
* Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id
*
* @method getUser
* @param {String} userId
* @param {Function} callback
*/
getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Updates the user metdata. It will patch the user metdata with the attributes sent.
* https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
*
* @method patchUserMetadata
* @param {String} userId
* @param {Object} userMetadata
* @param {Function} callback
*/
patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities
*
* @method linkUser
* @param {String} userId
* @param {String} secondaryUserToken
* @param {Function} callback
*/
linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void;
}
export class WebAuth {
constructor(options: AuthOptions);
client: Authentication;
popup: Popup;
redirect: Redirect;
/**
* Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
authorize(options: any): void;
/**
* Parse the url hash and extract the returned tokens depending on the transaction.
*
* Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed
* by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be
* accepted.
*
* @method parseHash
* @param {Object} options:
* @param {String} options.state [OPTIONAL] to verify the response
* @param {String} options.nonce [OPTIONAL] to verify the id_token
* @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash
* @param {Function} callback: any(err, token_payload)
*/
parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Decodes the id_token and verifies the nonce.
*
* @method validateToken
* @param {String} token
* @param {String} state
* @param {String} nonce
* @param {Function} callback: function(err, {payload, transaction})
*/
validateToken(token: string, state: string, nonce: string, callback: any): void;
/**
* Executes a silent authentication transaction under the hood in order to fetch a new token.
*
* @method renewAuth
* @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint
* @param {Function} callback
*/
renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Initialices a change password transaction
*
* @method changePassword
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Signs up a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signup(options: any, callback: any): void;
/**
* Signs up a new user, automatically logs the user in after the signup and returns the user token.
* The login will be done using /oauth/token with password-realm grant type.
*
* @method signupAndAuthorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Redirects to the auth0 logout page
*
* @method logout
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
logout(options: any): void;
passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void;
/**
* Verifies the passwordless TOTP and redirects to finish the passwordless transaction
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: any): void;
}
export class Redirect {
constructor(client: any, options: any);
/**
* Initializes the legacy Lock login flow in a popup
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
*/
loginWithCredentials(options: any, callback: any): void;
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndLogin(options: any, callback: any): void;
}
export class Popup {
constructor(client: any, options: any);
/**
* Returns a new instance of the popup handler
*
* @method buildPopupHandler
*/
buildPopupHandler(): any;
/**
* Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser.
*
* @method preload
* @param {Object} options: receives the window height and width and any other window feature to be sent to window.open
*/
preload(options: any): any;
/**
* Internal use.
*
* @method getPopupHandler
*/
getPopupHandler(options: any, preload: boolean): any;
/**
* Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
* @param {Function} callback
*/
authorize(options: any, callback: any): void;
/**
* Initializes the legacy Lock login flow in a popup
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
*/
loginWithCredentials(options: any, callback: any): void;
/**
* Verifies the passwordless TOTP and returns the requested token
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: any): void;
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndLogin(options: any, callback: any): void;
}
interface ManagementOptions {
domain: string;
token: string;
_sendTelemetry?: boolean;
_telemetryInfo?: any;
}
interface AuthOptions {
domain: string;
clientID: string;
responseType?: string;
responseMode?: string;
redirectUri?: string;
scope?: string;
audience?: string;
leeway?: number;
plugins?: any[];
_disableDeprecationWarnings?: boolean;
_sendTelemetry?: boolean;
_telemetryInfo?: any;
}
interface PasswordlessAuthOptions {
connection: string;
verificationCode: string;
phoneNumber: string;
email: string;
}
interface Auth0Error {
error?: any;
errorDescription?: string;
code?: string;
description?: string;
name?: string;
policy?: string;
original?: any;
statusCode?: number;
statusText?: string;
}
interface Auth0DecodedHash {
accessToken?: string;
idToken?: string;
idTokenPayload?: any;
refreshToken?: string;
state?: string;
expiresIn?: number;
tokenType?: string;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
ExpiresIn: number;
/** The JWT for delegated access. */
idToken: string;
/** The type of token being returned. Possible values: "Bearer" */
tokenType: string;
}
interface ChangePasswordOptions {
connection: string;
email: string;
password?: string;
}
interface PasswordlessStartOptions {
connection: string;
send: string;
phoneNumber?: string;
email?: string;
authParams?: any;
}
interface PasswordlessVerifyOptions {
connection: string;
verificationCode: string;
phoneNumber?: string;
email?: string;
}
interface Auth0UserProfile {
name: string;
nickname: string;
picture: string;
user_id: string;
username?: string;
given_name?: string;
family_name?: string;
email?: string;
email_verified?: string;
clientID: string;
gender?: string;
locale?: string;
identities: Auth0Identity[];
created_at: string;
updated_at: string;
sub: string;
user_metadata?: any;
app_metadata?: any;
}
interface MicrosoftUserProfile extends Auth0UserProfile {
emails?: string[]; //optional depending on whether email addresses permission is granted
}
interface Office365UserProfile extends Auth0UserProfile {
tenantid: string;
upn: string;
}
interface AdfsUserProfile extends Auth0UserProfile {
issuer?: string;
}
interface Auth0Identity {
connection: string;
isSocial: boolean;
provider: string;
user_id: string;
}
+2 -2
View File
@@ -1,4 +1,4 @@
import 'auth0-js/v7';
import * as auth0 from 'auth0-js';
import Auth0Lock from 'auth0-lock';
const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID";
@@ -38,7 +38,7 @@ lock.show(showOptions);
// "on" event-driven example
lock.on("authenticated", function(authResult : any) {
lock.getProfile(authResult.idToken, function(error, profile) {
lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) {
if (error) {
// Handle error
return;
+13 -10
View File
@@ -1,9 +1,9 @@
// Type definitions for auth0-lock 10.9
// Type definitions for auth0-lock 10.10
// Project: http://auth0.com
// Definitions by: Brian Caruso <https://github.com/carusology>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js/v7" />
/// <reference types="auth0-js" />
interface Auth0LockAdditionalSignUpFieldOption {
value: string;
@@ -11,13 +11,13 @@ interface Auth0LockAdditionalSignUpFieldOption {
}
type Auth0LockAdditionalSignUpFieldOptionsCallback =
(error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void;
(error: auth0.Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void;
type Auth0LockAdditionalSignUpFieldOptionsFunction =
(callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void;
type Auth0LockAdditionalSignUpFieldPrefillCallback =
(error: Auth0Error, prefill: string) => void;
(error: auth0.Auth0Error, prefill: string) => void;
type Auth0LockAdditionalSignUpFieldPrefillFunction =
(callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void;
@@ -32,8 +32,8 @@ interface Auth0LockAdditionalSignUpField {
validator?: (input: string) => { valid: boolean; hint?: string };
}
type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void;
type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void;
type Auth0LockAvatarUrlCallback = (error: auth0.Auth0Error, url: string) => void;
type Auth0LockAvatarDisplayNameCallback = (error: auth0.Auth0Error, displayName: string) => void;
interface Auth0LockAvatarOptions {
url: (email: string, callback: Auth0LockAvatarUrlCallback) => void;
@@ -63,6 +63,7 @@ interface Auth0LockAuthOptions {
redirectUrl?: string;
responseType?: string;
sso?: boolean;
audience?: string;
}
interface Auth0LockPopupOptions {
@@ -101,6 +102,7 @@ interface Auth0LockConstructorOptions {
socialButtonStyle?: "big" | "small";
theme?: Auth0LockThemeOptions;
usernameStyle?: string;
oidcConformant?: boolean;
}
interface Auth0LockFlashMessageOptions {
@@ -123,15 +125,16 @@ interface Auth0LockStatic {
new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic;
// deprecated
getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void;
getUserInfo(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void;
getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
// https://github.com/auth0/lock#resumeauthhash-callback
resumeAuth( hash: string, callback: (error: auth0.Auth0Error, authResult: any) => void): void;
show(options?: Auth0LockShowOptions): void;
hide(): void;
logout(query: any): void;
on(event: "show" | "hide", callback: () => void): void;
on(event: "unrecoverable_error" | "authorization_error", callback: (error: Auth0Error) => void): void;
on(event: "unrecoverable_error" | "authorization_error", callback: (error: auth0.Auth0Error) => void): void;
on(event: "authenticated", callback: (authResult: any) => void): void;
on(event: string, callback: (...args: any[]) => void): void;
}
+52
View File
@@ -0,0 +1,52 @@
import b_ = require("b_");
const blockClass: string = b_("block");
const blockWithModsClass: string = b_("block", {stringMod: "string", boolMod: true, numberMod: 5});
const elemClass: string = b_("block", "elem");
const elemWithModsClass: string = b_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5});
const withBlock = b_.with("block");
const withBlockClass: string = withBlock();
const withBlockWithModsClass: string = withBlock({stringMod: "string", boolMod: true, numberMod: 5});
const withBlockElemClass: string = withBlock("elem");
const withBlockElemWithModsClass: string = withBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5});
const lockBlock = b_.lock("block");
const lockBlockClass: string = lockBlock();
const lockBlockWithModsClass: string = lockBlock({stringMod: "string", boolMod: true, numberMod: 5});
const lockBlockElemClass: string = lockBlock("elem");
const lockBlockElemWithModsClass: string = lockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5});
const withElem = b_.with("block", "elem");
const withElemClass: string = withElem();
const withElemWithModsClass: string = withElem({stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedB_ = b_.B({
tailSpace: " ",
elementSeparator: "-",
modSeparator: "_",
modValueSeparator: "-",
classSeparator: " ",
isFullModifier: true
});
const parameterizedBlockClass: string = parameterizedB_("block");
const parameterizedBlockWithModsClass: string = parameterizedB_("block", {stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedElemClass: string = parameterizedB_("block", "elem");
const parameterizedElemWithModsClass: string = parameterizedB_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedWithBlock = parameterizedB_.with("block");
const parameterizedWithBlockClass: string = parameterizedWithBlock();
const parameterizedWithBlockWithModsClass: string = parameterizedWithBlock({stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedWithBlockElemClass: string = parameterizedWithBlock("elem");
const parameterizedWithBlockElemWithModsClass: string = parameterizedWithBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedLockBlock = parameterizedB_.lock("block");
const parameterizedLockBlockClass: string = parameterizedLockBlock();
const parameterizedLockBlockWithModsClass: string = parameterizedLockBlock({stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedLockBlockElemClass: string = parameterizedLockBlock("elem");
const parameterizedLockBlockElemWithModsClass: string = parameterizedLockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5});
const parameterizedWithElem = parameterizedB_.with("block", "elem");
const parameterizedWithElemClass: string = parameterizedWithElem();
const parameterizedWithElemWithModsClass: string = parameterizedWithElem({stringMod: "string", boolMod: true, numberMod: 5});
+40
View File
@@ -0,0 +1,40 @@
// Type definitions for b_ 1.3
// Project: https://github.com/azproduction/b_
// Definitions by: Vasya Aksyonov <https://github.com/outring>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Options {
tailSpace?: string;
elementSeparator?: string;
modSeparator?: string;
modValueSeparator?: string;
classSeparator?: string;
isFullModifier?: boolean;
}
interface Mods {
[name: string]: any;
}
interface Formatter {
(block: string, mods?: Mods): string;
(block: string, elem: string, mods?: Mods): string;
with(block: string): BlockFormatter;
with(block: string, elem: string): ElemFormatter;
lock(block: string): BlockFormatter;
lock(block: string, elem: string): ElemFormatter;
B(options: Options): Formatter;
}
interface BlockFormatter {
(mods?: Mods): string;
(elem: string, mods?: Mods): string;
}
type ElemFormatter = (mods?: Mods) => string;
declare const formatter: Formatter;
export = formatter;
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"b_-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+3
View File
@@ -40,5 +40,8 @@ expect(wrapper).to.have.data("test", "Test");
expect(wrapper).to.have.style("background", "green");
expect(wrapper).to.have.state("test", "test");
expect(wrapper).to.have.prop("test", 5);
expect(wrapper).to.have.props(["test1", "test2"]);
expect(wrapper).to.have.props({ test: 5 });
expect(wrapper).to.contain(<Test/>);
expect(wrapper).to.containMatchingElement(<Test/>);
expect(wrapper).to.match(<Test/>);
+19 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for chai-enzyme 0.5.0
// Type definitions for chai-enzyme 0.6.1
// Project: https://github.com/producthunt/chai-enzyme
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -39,6 +39,12 @@ declare namespace Chai {
*/
className(name: string): Assertion;
/**
* Assert that the wrapper contains a certain element:
* @param selector
*/
containMatchingElement(selector: EnzymeSelector): Assertion;
/**
* Assert that the wrapper contains a descendant matching the given selector:
* @param selector
@@ -140,6 +146,18 @@ declare namespace Chai {
* @param val
*/
prop(key: string, val?: any): Assertion;
/**
* Assert that the wrapper has given props [with values]:
* @param keys
*/
props(keys: string[]): Assertion;
/**
* Assert that the wrapper has given props [with values]:
* @param props
*/
props(props: EnzymeSelector): Assertion;
}
}
+2 -2
View File
@@ -1831,7 +1831,7 @@ declare namespace chrome.devtools.panels {
* If you specify the callback parameter, it should be a function that looks like this:
* function() {...};
*/
setObject(jsonObject: string, rootTitle?: string, callback?: () => void): void;
setObject(jsonObject: Object, rootTitle?: string, callback?: () => void): void;
/**
* Sets a JSON-compliant object to be displayed in the sidebar pane.
* @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client).
@@ -1839,7 +1839,7 @@ declare namespace chrome.devtools.panels {
* If you specify the callback parameter, it should be a function that looks like this:
* function() {...};
*/
setObject(jsonObject: string, callback?: () => void): void;
setObject(jsonObject: Object, callback?: () => void): void;
/**
* Sets an HTML page to be displayed in the sidebar pane.
* @param path Relative path of an extension page to display within the sidebar.
+30
View File
@@ -0,0 +1,30 @@
import * as CombinedStream from "combined-stream";
import { createReadStream, createWriteStream } from "fs";
const stream1 = new CombinedStream();
stream1.append(createReadStream("tsconfig.json"));
stream1.append(createReadStream("tslint.json"));
stream1.append(createReadStream("index.d.ts"));
stream1.pipe(createWriteStream("combined.txt"));
const stream2 = CombinedStream.create({
maxDataSize: 1 << 32,
pauseStreams: false,
});
stream1.destroy();
// should log true
console.log(CombinedStream.isStreamLike(stream2));
stream2.on("data", (data) => {
console.log(data);
});
stream2.pipe(createWriteStream("combined.txt"));
stream2.write(CombinedStream.name);
stream2.destroy();
+56
View File
@@ -0,0 +1,56 @@
// Type definitions for combined-stream 1.0
// Project: https://github.com/felixge/node-combined-stream
// Definitions by: Felix Geisendörfer <https://github.com/felixge>, Tomek Łaziuk <https://github.com/tlaziuk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Stream } from "stream";
declare class CombinedStream extends Stream implements CombinedStream.Options {
readonly writable: boolean;
readonly readable: boolean;
readonly dataSize: number;
maxDataSize: number;
pauseStreams: boolean;
append(stream: NodeJS.ReadableStream | NodeJS.WritableStream | Buffer | string): this;
write(data: any): void;
pause(): void;
resume(): void;
end(): void;
destroy(): void;
// private properties
_released: boolean;
// @TODO it should be a type of Array<'delayed-stream' instance | Buffer | string>
_streams: Array<Stream | Buffer | string>;
_currentStream: Stream | Buffer | string | null;
_getNext(): void;
_pipeNext(): void;
_handleErrors(stream: NodeJS.EventEmitter): void;
_reset(): void;
_checkDataSize(): void;
_updateDataSize(): void;
_emitError(error: Error): void;
// events
on(event: "close" | "end" | "resume" | "pause", cb: () => void): this;
on(event: "error", cb: (err: Error) => void): this;
on(event: "data", cb: (data: any) => void): this;
once(event: "close" | "end" | "resume" | "pause", cb: () => void): this;
once(event: "error", cb: (err: Error) => void): this;
once(event: "data", cb: (data: any) => void): this;
}
declare namespace CombinedStream {
export interface Options {
maxDataSize?: number;
pauseStreams?: boolean;
}
export function create(options?: Options): CombinedStream;
export function isStreamLike(stream: any): stream is Stream;
}
export = CombinedStream;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"combined-stream-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+18
View File
@@ -97,6 +97,24 @@ function StepSample() {
} )
});
cucumber.defineSupportCode(function(hook: cucumber.Hooks){
hook.addTransform({
captureGroupRegexps: ['red|blue|green'],
transformer: (arg: string) => arg,
typeName: 'color'
});
});
cucumber.defineSupportCode(function({After, Given}) {
Given( /^a variable set to (\d+)$/, (x:string) => {
console.log("the number is: " + x);
});
After((scenario: HookScenario, callback?: Callback) => {
console.log("After");
callback();
});
});
let fns : cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns()
cucumber.clearSupportCodeFns();
+7
View File
@@ -64,6 +64,12 @@ declare namespace cucumber {
(scenario: HookScenario, runScenario?: (error:string, callback?:Function)=>void): void;
}
interface Transform {
captureGroupRegexps: Array<RegExp | string>;
transformer: (arg: string) => any;
typeName: string;
}
export interface Hooks {
Before(code: HookCode): void;
After(code: HookCode): void;
@@ -72,6 +78,7 @@ declare namespace cucumber {
setWorldConstructor(world: () => void): void;
registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void;
registerListener(listener: EventListener): void;
addTransform(transform: Transform): void;
}
export class EventListener {
+13
View File
@@ -537,6 +537,19 @@ geoPathCentroid = geoPathCanvas.centroid(sampleExtendedFeatureCollection);
// geoPathCentroid = geoPathSVG.centroid(sampleExtendedFeatureCollection); // fails, wrong data object type
// measure(...) ------------------------------------------------------
let geoPathMeasure: number = geoPathCanvas.measure(samplePolygon);
geoPathMeasure = geoPathCanvas.measure(sampleSphere);
geoPathMeasure = geoPathCanvas.measure(sampleGeometryCollection);
geoPathMeasure = geoPathCanvas.measure(sampleExtendedGeometryCollection);
geoPathMeasure = geoPathCanvas.measure(sampleFeature);
geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeature1);
geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeature2);
geoPathMeasure = geoPathCanvas.measure(sampleFeatureCollection);
geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeatureCollection);
// render path to context of get path string----------------------------
// render to GeoContext/Canvas
+14 -4
View File
@@ -1,4 +1,4 @@
// Type definitions for D3JS d3-geo module v1.4.0
// Type definitions for D3JS d3-geo module v1.5.0
// Project: https://github.com/d3/d3-geo/
// Definitions by: Hugues Stefanski <https://github.com/Ledragon>, Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -908,7 +908,7 @@ export interface GeoPath<This, DatumObject extends GeoPermissibleObjects> {
* this method first computes the area of the exterior ring, and then subtracts the area of any interior holes.
* This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent.
*
* @param An object for which the area is to be calculated.
* @param object An object for which the area is to be calculated.
*/
area(object: DatumObject): number;
@@ -921,7 +921,7 @@ export interface GeoPath<This, DatumObject extends GeoPermissibleObjects> {
* the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.)
* This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent.
*
* @param An object for which the bounds are to be calculated.
* @param object An object for which the bounds are to be calculated.
*/
bounds(object: DatumObject): [[number, number], [number, number]];
@@ -931,10 +931,20 @@ export interface GeoPath<This, DatumObject extends GeoPermissibleObjects> {
* For example, a noncontiguous cartogram might scale each state around its centroid.
* This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent.
*
* @param An object for which the centroid is to be calculated.
* @param pbject An object for which the centroid is to be calculated.
*/
centroid(object: DatumObject): [number, number];
/**
* Returns the projected planar length (typically in pixels) for the specified GeoJSON object.
* Point and MultiPoint features have zero length. For Polygon and MultiPolygon features, this method computes the summed length of all rings.
*
* This method observes any clipping performed by the projection.
*
* @param object An object for which the measure is to be calculated.
*/
measure(object: DatumObject): number;
/**
* Returns the current render context which defaults to null.
*
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for D3JS d3 standard bundle 4.5
// Type definitions for D3JS d3 standard bundle 4.6
// Project: https://github.com/d3/d3
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+2
View File
@@ -180,6 +180,8 @@ d3.json("data/yelp_test_set_business.json", (yelp_data:IYelpData[]) => {
.xAxis()
.tickFormat((v: string) => v);
lineChart.legend(dc.legend().x(200).y(10).itemHeight(13).gap(5));
rowChart
.width(340)
.height(850)
+8 -8
View File
@@ -111,14 +111,14 @@ declare namespace dc {
}
export interface Legend {
x: IGetSet<number, number>;
y: IGetSet<number, number>;
gap: IGetSet<number, number>;
itemHeight: IGetSet<number, number>;
horizontal: IGetSet<boolean, boolean>;
legendWidth: IGetSet<number, number>;
itemWidth: IGetSet<number, number>;
autoItemWidth: IGetSet<boolean, boolean>;
x: IGetSet<number, Legend>;
y: IGetSet<number, Legend>;
gap: IGetSet<number, Legend>;
itemHeight: IGetSet<number, Legend>;
horizontal: IGetSet<boolean, Legend>;
legendWidth: IGetSet<number, Legend>;
itemWidth: IGetSet<number, Legend>;
autoItemWidth: IGetSet<boolean, Legend>;
render: () => void;
}
+8 -5
View File
@@ -1,8 +1,11 @@
import * as deepEqual from "deep-equal";
import deepEqual = require("deep-equal");
let isDeepEqual1: boolean = deepEqual({}, {});
let isDeepEqual2: boolean = deepEqual({}, {}, { strict: true });
let isDeepEqual3: boolean = deepEqual({}, {}, { strict: false });
const isDeepEqual1: boolean = deepEqual({}, {});
const isDeepEqual2: boolean = deepEqual({}, {}, { strict: true });
const isDeepEqual3: boolean = deepEqual({}, {}, { strict: false });
const isDeepEqual4: boolean = deepEqual(undefined, undefined);
const isDeepEqual5: boolean = deepEqual(3, false);
const isDeepEqual6: boolean = deepEqual("a-string", null);
console.log(isDeepEqual1, isDeepEqual2, isDeepEqual3);
console.log(isDeepEqual1, isDeepEqual2, isDeepEqual3, isDeepEqual4, isDeepEqual5, isDeepEqual6);
+6 -8
View File
@@ -1,17 +1,15 @@
// Type definitions for deep-equal
// Type definitions for deep-equal 1.0
// Project: https://github.com/substack/node-deep-equal
// Definitions by: remojansen <https://github.com/remojansen>
// Definitions by: remojansen <https://github.com/remojansen>, Jay Anslow <http://github.com/janslow>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface DeepEqualOptions {
strict: boolean;
}
declare let deepEqual: (
actual: Object,
expected: Object,
opts?: DeepEqualOptions) => boolean;
declare function deepEqual(
actual: any,
expected: any,
opts?: DeepEqualOptions): boolean;
export = deepEqual;
+1 -1
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+1
View File
@@ -184,6 +184,7 @@ declare namespace Dockerode {
Created: number;
Ports: Port[];
Labels: { [label: string]: string };
State: string;
Status: string;
HostConfig: {
NetworkMode: string;
+1
View File
@@ -88,6 +88,7 @@ declare module Elasticsearch {
export interface ConfigOptions {
host?: any;
hosts?: any;
httpAuth?: string;
log?: any;
apiVersion?: string;
plugins?: any;
+2
View File
@@ -848,6 +848,8 @@ interface Response extends http.ServerResponse, Express.Response {
*
*/
vary(field: string): Response;
app: Application;
}
interface Handler extends RequestHandler { }
@@ -22,18 +22,18 @@ configuration = {
// Extract css files
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader",
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader",
})
},
// Optionally extract less files
// or any other compile-to-css language
{
test: /\.less$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: ["css-loader", "less-loader"],
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "less-loader"],
})
}
// You could also use other loaders the same way. I. e. the autoprefixer-loader
@@ -70,10 +70,13 @@ configuration = {
// ...
module: {
rules: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
}) }
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
@@ -89,8 +92,8 @@ configuration = {
// ...
module: {
rules: [
{ test: /\.scss$/i, loader: extractCSS.extract(['css','sass']) },
{ test: /\.less$/i, loader: extractLESS.extract(['css','less']) },
{ test: /\.scss$/i, use: extractCSS.extract(['css','sass']) },
{ test: /\.less$/i, use: extractLESS.extract(['css','less']) },
]
},
plugins: [
+6 -6
View File
@@ -1,15 +1,15 @@
// Type definitions for extract-text-webpack-plugin 2.0.0
// Project: https://github.com/webpack/extract-text-webpack-plugin
// Definitions by: flying-sheep <https://github.com/flying-sheep>
// Project: https://github.com/webpack-contrib/extract-text-webpack-plugin
// Definitions by: flying-sheep <https://github.com/flying-sheep>, kayo <https://github.com/katyo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Plugin, OldLoader } from 'webpack'
import { Plugin, OldLoader, NewLoader } from 'webpack'
/**
* extract-text-webpack-plugin has no support for .options instead of .query yet.
* See https://github.com/webpack/extract-text-webpack-plugin/issues/281
*/
type Loader = string | OldLoader
type Loader = string | OldLoader | NewLoader
interface ExtractPluginOptions {
/** the filename of the result file. May contain `[name]`, `[id]` and `[contenthash]` */
@@ -24,9 +24,9 @@ interface ExtractPluginOptions {
interface ExtractOptions {
/** the loader(s) that should be used for converting the resource to a css exporting module */
loader: Loader | Loader[]
use: Loader | Loader[]
/** the loader(s) that should be used when the css is not extracted (i.e. in an additional chunk when `allChunks: false`) */
fallbackLoader?: Loader | Loader[]
fallback?: Loader | Loader[]
/** override the `publicPath` setting for this loader */
publicPath?: string
}
+21
View File
@@ -0,0 +1,21 @@
import * as Gettext from 'gettext.js';
const json: Gettext.JsonData = {
"": {
"locale": "fr",
"plural-forms": "nplurals=2; plural=n>1;"
},
"Welcome": "Bienvenue",
"There is %1 apple": [
"Il y a %1 pomme",
"Il y a %1 pommes"
]
};
const instance: Gettext.Gettext = Gettext.i18n();
instance.loadJSON(json, 'messages');
instance.setLocale('fr');
if (instance.ngettext('There is %1 apple', 'There are %1 apples', 0) === 'Il y a %1 pomme') {
throw new Error('Failed test');
}
+45
View File
@@ -0,0 +1,45 @@
// Type definitions for gettext.js 0.5
// Project: https://github.com/guillaumepotier/gettext.js
// Definitions by: Julien Crouzet <https://github.com/jucrouzet>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type PluralForm = (n: number) => number;
export type GettextStatic = (options?: GettextOptions) => Gettext;
export interface GettextOptions {
domain?: string;
locale?: string;
plural_func?: PluralForm;
ctxt_delimiter?: string;
}
export interface JsonDataHeader {
locale: string;
"plural-forms": string;
}
export interface JsonDataMessages {
[key: string]: string | string[] | JsonDataHeader;
}
export interface JsonData extends JsonDataMessages {
"": JsonDataHeader;
}
export interface Gettext {
setMessages: (domain: string, locale: string, messages: JsonDataMessages, plural_forms?: PluralForm) => Gettext;
loadJSON: (jsonData: JsonData, domain?: string) => Gettext;
setLocale: (locale: string) => Gettext;
getLocale: () => string;
textdomain: (domain?: string) => Gettext | string;
gettext: (msgid: string, ...args: any[]) => string;
ngettext: (msgid: string, msgid_plural: string, n: number, ...args: any[]) => string;
pgettext: (msgctxt: string, msgid: string, ...args: any[]) => string;
dcnpgettext: (domain: string, msgctxt: string, msgid: string, msgid_plural: string, n: number, ...args: any[]) => string;
__: (msgid: string, ...args: any[]) => string;
_n: (msgid: string, msgid_plural: string, n: number, ...args: any[]) => string;
_p: (msgctxt: string, msgid: string, ...args: any[]) => string;
}
export const i18n: GettextStatic;
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"gettext.js-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+1
View File
@@ -78,6 +78,7 @@ gm(src)
.authenticate(password)
.autoOrient()
.backdrop()
.background(color)
.bitdepth(bits)
.blackThreshold(intensity)
.blackThreshold(r, g, b)
+1
View File
@@ -108,6 +108,7 @@ declare namespace m {
authenticate(password: string): State;
autoOrient(): State;
backdrop(): State;
background(color: string): State;
bitdepth(bits: number): State;
blackThreshold(intensity: number): State;
blackThreshold(red: number, green: number, blue: number, opacity?: number): State;
+139
View File
@@ -0,0 +1,139 @@
import * as jspb from "google-protobuf";
/* This is a typescript version of a simple generated class from a proto file that is shown below. In order to make
this ES5 JS file into TypeScript there have been quite a few modifications, but the same calls are made to the library
classes.
// FILE: simple.proto
syntax = "proto3";
package examplecom;
message MySimple {
string my_string = 1;
bool my_bool = 2;
repeated string some_labels = 3;
}
*/
class MySimple extends jspb.Message {
constructor(opt_data?: any) {
super(); // This isn't actually called in the JS version of this file, but it's required by TS
jspb.Message.initialize(this, opt_data, 0, -1, MySimple.repeatedFields_, null);
};
static repeatedFields_ = [3];
toObject(opt_includeInstance: boolean) {
return MySimple.toObject(opt_includeInstance, this);
};
static toObject(includeInstance: boolean, msg: MySimple) {
const obj = {
myString: jspb.Message.getFieldWithDefault(msg, 1, ""),
myBool: jspb.Message.getFieldWithDefault(msg, 2, false),
someLabelsList: jspb.Message.getField(msg, 3),
};
if (includeInstance) {
// This is commented out because it's not valid in TS, but it's a simple append to an object
// obj['$jspbMessageInstance'] = msg;
}
return obj;
};
static deserializeBinary(bytes: Uint8Array) {
const reader = new jspb.BinaryReader(bytes);
const msg = new MySimple();
return MySimple.deserializeBinaryFromReader(msg, reader);
};
static deserializeBinaryFromReader(msg: MySimple, reader: jspb.BinaryReader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
const field = reader.getFieldNumber();
switch (field) {
case 1:
const value1 = (reader.readString());
msg.setMyString(value1);
break;
case 2:
const value2 = (reader.readBool());
msg.setMyBool(value2);
break;
case 3:
const value3 = (reader.readString());
msg.addSomeLabels(value3);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
serializeBinary(): Uint8Array {
const writer = new jspb.BinaryWriter();
MySimple.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
static serializeBinaryToWriter(message: MySimple, writer: jspb.BinaryWriter) {
let f1 = message.getMyString();
if (f1.length > 0) {
writer.writeString(
1,
f1,
);
}
const f2 = message.getMyBool();
if (f2) {
writer.writeBool(
2,
f2,
);
}
const f3 = message.getSomeLabelsList();
if (f3.length > 0) {
writer.writeRepeatedString(
3,
f3,
);
}
}
getMyString(): string {
return jspb.Message.getFieldWithDefault(this, 1, "");
}
setMyString(value: string) {
jspb.Message.setField(this, 1, value);
}
getMyBool(): boolean {
return jspb.Message.getFieldWithDefault(this, 2, false);
}
setMyBool(value: boolean) {
jspb.Message.setField(this, 2, value);
}
getSomeLabelsList(): string[] {
return jspb.Message.getField(this, 3);
}
setSomeLabelsList(value: string[]) {
jspb.Message.setField(this, 3, value || []);
}
addSomeLabels(value: string, opt_index?: number) {
jspb.Message.addToRepeatedField(this, 3, value, opt_index);
}
clearSomeLabelsList() {
this.setSomeLabelsList([]);
}
}
+675
View File
@@ -0,0 +1,675 @@
// Type definitions for google-protobuf 3.2
// Project: https://github.com/google/google-protobuf
// Definitions by: Marcus Longmuir <https://github.com/marcuslongmuir/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type ByteSource = ArrayBuffer|Uint8Array|number[]|string;
type ScalarFieldType = boolean|number|string;
type RepeatedFieldType = ScalarFieldType[] | Uint8Array[];
type AnyFieldType = ScalarFieldType | RepeatedFieldType | Uint8Array;
type FieldValue = (string|number|boolean|Uint8Array|any/*This should be Array<FieldValue>, but that isn't allowed*/|undefined)
export class Message {
getJsPbMessageId(): (string | undefined);
static initialize(msg: Message,
data: Message.MessageArray,
messageId: (string | number),
suggestedPivot: number,
repeatedFields: number[],
oneofFields?: number[][] | null): void;
static toObjectList<T extends Message>(field: T[],
toObjectFn: (includeInstance: boolean,
data: T) => {},
includeInstance?: boolean): {}[];
static toObjectExtension(msg: Message,
obj: {},
extensions: {[key: number]: ExtensionFieldInfo<Message>},
getExtensionFn: (fieldInfo: ExtensionFieldInfo<Message>) => Message,
includeInstance?: boolean): void;
serializeBinaryExtensions(proto: Message,
writer: BinaryWriter,
extensions: {[key: number]: ExtensionFieldBinaryInfo<Message>},
getExtensionFn: <T>(fieldInfo: ExtensionFieldInfo<T>) => T): void
readBinaryExtension(proto: Message,
reader: BinaryReader,
extensions: {[key: number]: ExtensionFieldBinaryInfo<Message>},
setExtensionFn: <T>(fieldInfo: ExtensionFieldInfo<T>,
val: T) => void): void
static getField(msg: Message,
fieldNumber: number): FieldValue|null;
static getOptionalFloatingPointField(msg: Message,
fieldNumber: number): (number | undefined);
static getRepeatedFloatingPointField(msg: Message,
fieldNumber: number): number[];
static bytesAsB64(bytes: Uint8Array): string;
static bytesAsU8(str: string): Uint8Array;
static bytesListAsB64(bytesList: Uint8Array[]): string[];
static bytesListAsU8(strList: string[]): Uint8Array[];
static getFieldWithDefault<T>(msg: Message,
fieldNumber: number,
defaultValue: T): T;
static getMapField(msg: Message,
fieldNumber: number,
noLazyCreate: boolean,
valueCtor: typeof Message): Map<any, any>;
static setField(msg: Message,
fieldNumber: number,
value: FieldValue): void;
static addToRepeatedField(msg: Message,
fieldNumber: number,
value: any,
index?: number): void;
static setOneofField(msg: Message,
fieldNumber: number,
oneof: number[],
value: FieldValue): void;
static computeOneofCase(msg: Message,
oneof: number[]): number;
static getWrapperField(msg: Message,
ctor: typeof Message,
fieldNumber: number,
required?: number): Message;
static getRepeatedWrapperField(msg: Message,
ctor: typeof Message,
fieldNumber: number): Message[];
static setWrapperField(msg: Message,
fieldNumber: number,
value?: (Message|Map<any, any>)): void;
static setOneofWrapperField(msg: Message,
fieldNumber: number,
oneof: number[],
value: any): void;
static setRepeatedWrapperField(msg: Message,
fieldNumber: number,
value: any): void;
static addToRepeatedWrapperField(msg: Message,
fieldNumber: number,
value: any,
ctor: typeof Message,
index: number): any;
static toMap(field: any[],
mapKeyGetterFn: (field: any) => string,
toObjectFn?: Message.StaticToObject,
includeInstance?: boolean): void;
toArray(): Message.MessageArray;
toString(): string;
getExtension<T>(fieldInfo: ExtensionFieldInfo<T>): T;
setExtension<T>(fieldInfo: ExtensionFieldInfo<T>,
value: T): void;
static difference<T extends Message>(m1: T,
m2: T): T;
static equals(m1: Message,
m2: Message): boolean;
static compareExtensions(extension1: {},
extension2: {}): boolean;
static compareFields(field1: any,
field2: any): boolean;
cloneMessage(): Message;
clone(): Message;
static clone<T extends Message>(msg: T): T;
static cloneMessage<T extends Message>(msg: T): T;
static copyInto(fromMessage: Message,
toMessage: Message): void;
static registerMessageType(id: number,
constructor: typeof Message): void;
}
export namespace Message {
export type MessageArray = any[]; // This type needs to reference itself
interface StaticToObject {
(includeInstance: boolean,
msg: Message): {};
}
}
export class ExtensionFieldInfo<T> {
fieldIndex: number;
fieldName: number;
ctor: typeof Message;
toObjectFn: Message.StaticToObject;
isRepeated: number;
constructor(fieldIndex: number,
fieldName: {[key: string]: number},
ctor: typeof Message,
toObjectFn: Message.StaticToObject,
isRepeated: number);
isMessageType(): boolean;
}
export class ExtensionFieldBinaryInfo<T> {
fieldInfo: ExtensionFieldInfo<T>;
binaryReaderFn: BinaryRead;
binaryWriterFn: BinaryWrite;
opt_binaryMessageSerializeFn: (msg: Message,
writer: BinaryWriter) => void;
opt_binaryMessageDeserializeFn: (msg: Message,
reader: BinaryReader) => Message;
opt_isPacked: boolean;
constructor(fieldInfo: ExtensionFieldInfo<T>,
binaryReaderFn: BinaryRead,
binaryWriterFn: BinaryWrite,
opt_binaryMessageSerializeFn: (msg: Message,
writer: BinaryWriter) => void,
opt_binaryMessageDeserializeFn: (msg: Message,
reader: BinaryReader) => Message,
opt_isPacked: boolean);
}
export class Map<K, V> {
constructor(arr: Array<[K, V]>,
valueCtor?: {new(init: any): V});
toArray(): Array<[K, V]>;
toObject(includeInstance: boolean,
valueToObject: (includeInstance: boolean) => any): Array<[K, V]>;
static fromObject<K, V>(entries: Array<[K, V]>,
valueCtor: any,
valueFromObject: any): Map<K, V>;
getLength(): number;
clear(): void;
del(key: K): boolean;
getEntryList(): Array<[K, V]>;
entries(): Map.Iterator<[K, V]>;
keys(): Map.Iterator<K>;
forEach(callback: (entry: V,
key: K) => void,
thisArg?: {}): void;
set(key: K,
value: V): void;
get(key: K): (V | undefined);
has(key: K): boolean;
}
export namespace Map {
// This is implemented by jspb.Map.ArrayIteratorIterable_, but that class shouldn't be exported
interface Iterator<T> {
next(): IteratorResult<T>;
}
type IteratorResult<T> = {
done: boolean,
value: T,
}
}
interface BinaryReadReader {
(msg: any,
binaryReader: BinaryReader): void;
}
interface BinaryRead {
(msg: any,
reader: BinaryReadReader): void;
}
interface BinaryWriteCallback {
(value: any,
binaryWriter: BinaryWriter): void;
}
interface BinaryWrite {
(fieldNumber: number,
value: any,
writerCallback: BinaryWriteCallback): void;
}
export class BinaryReader {
constructor(bytes?: ByteSource,
start?: number,
length?: number);
static alloc(bytes?: ByteSource,
start?: number,
length?: number): BinaryReader;
alloc(bytes?: ByteSource,
start?: number,
length?: number): BinaryReader;
free(): void;
getFieldCursor(): number;
getCursor(): number;
getBuffer(): Uint8Array;
getFieldNumber(): number;
getWireType(): BinaryConstants.WireType;
isEndGroup(): boolean;
getError(): boolean;
setBlock(bytes?: ByteSource,
start?: number,
length?: number): void;
reset(): void;
advance(count: number): void;
nextField(): boolean;
unskipHeader(): void;
skipMatchingFields(): void;
skipVarintField(): void;
skipDelimitedField(): void;
skipFixed32Field(): void;
skipFixed64Field(): void;
skipGroup(): void;
skipField(): void;
registerReadCallback(callbackName: string,
callback: (binaryReader: BinaryReader) => any): void;
runReadCallback(callbackName: string): any;
readAny(fieldType: BinaryConstants.FieldType): AnyFieldType;
readMessage: BinaryRead;
readGroup(field: number,
message: Message,
reader: BinaryReadReader): void;
getFieldDecoder(): BinaryDecoder;
readInt32(): number;
readInt32String(): string;
readInt64(): number;
readInt64String(): string;
readUint32(): number;
readUint32String(): string;
readUint64(): number;
readUint64String(): string;
readSint32(): number;
readSint64(): number;
readSint64String(): string;
readFixed32(): number;
readFixed64(): number;
readFixed64String(): string;
readSfixed32(): number;
readSfixed32String(): string;
readSfixed64(): number;
readSfixed64String(): string;
readFloat(): number;
readDouble(): number;
readBool(): boolean;
readEnum(): number;
readString(): string;
readBytes(): Uint8Array;
readVarintHash64(): string;
readFixedHash64(): string;
readPackedInt32(): number[];
readPackedInt32String(): string[];
readPackedInt64(): number[];
readPackedInt64String(): string[];
readPackedUint32(): number[];
readPackedUint32String(): string[];
readPackedUint64(): number[];
readPackedUint64String(): string[];
readPackedSint32(): number[];
readPackedSint64(): number[];
readPackedSint64String(): string[];
readPackedFixed32(): number[];
readPackedFixed64(): number[];
readPackedFixed64String(): string[];
readPackedSfixed32(): number[];
readPackedSfixed64(): number[];
readPackedSfixed64String(): string[];
readPackedFloat(): number[];
readPackedDouble(): number[];
readPackedBool(): boolean[];
readPackedEnum(): number[];
readPackedVarintHash64(): string[];
readPackedFixedHash64(): string[];
}
export class BinaryWriter {
constructor();
writeSerializedMessage(bytes: Uint8Array,
start: number,
end: number): void;
maybeWriteSerializedMessage(bytes?: Uint8Array,
start?: number,
end?: number): void;
reset(): void;
getResultBuffer(): Uint8Array;
getResultBase64String(): string;
beginSubMessage(field: number): void;
endSubMessage(field: number): void;
writeAny(fieldType: BinaryConstants.FieldType,
field: number,
value: AnyFieldType): void;
writeInt32(field: number,
value?: number): void;
writeInt32String(field: number,
value?: string): void;
writeInt64(field: number,
value?: number): void;
writeInt64String(field: number,
value?: string): void;
writeUint32(field: number,
value?: number): void;
writeUint32String(field: number,
value?: string): void;
writeUint64(field: number,
value?: number): void;
writeUint64String(field: number,
value?: string): void;
writeSint32(field: number,
value?: number): void;
writeSint64(field: number,
value?: number): void;
writeSint64String(field: number,
value?: string): void;
writeFixed32(field: number,
value?: number): void;
writeFixed64(field: number,
value?: number): void;
writeFixed64String(field: number,
value?: string): void;
writeSfixed32(field: number,
value?: number): void;
writeSfixed64(field: number,
value?: number): void;
writeSfixed64String(field: number,
value?: string): void;
writeFloat(field: number,
value?: number): void;
writeDouble(field: number,
value?: number): void;
writeBool(field: number,
value?: boolean): void;
writeEnum(field: number,
value?: number): void;
writeString(field: number,
value?: string): void;
writeBytes(field: number,
value?: ByteSource): void;
writeMessage: BinaryWrite;
writeGroup(field: number,
value: any,
writeCallback: BinaryWriteCallback): void;
writeFixedHash64(field: number,
value?: string): void;
writeVarintHash64(field: number,
value?: string): void;
writeRepeatedInt32(field: number,
value?: number[]): void;
writeRepeatedInt32String(field: number,
value?: string[]): void;
writeRepeatedInt64(field: number,
value?: number[]): void;
writeRepeatedInt64String(field: number,
value?: string[]): void;
writeRepeatedUint32(field: number,
value?: number[]): void;
writeRepeatedUint32String(field: number,
value?: string[]): void;
writeRepeatedUint64(field: number,
value?: number[]): void;
writeRepeatedUint64String(field: number,
value?: string[]): void;
writeRepeatedSint32(field: number,
value?: number[]): void;
writeRepeatedSint64(field: number,
value?: number[]): void;
writeRepeatedSint64String(field: number,
value?: string[]): void;
writeRepeatedFixed32(field: number,
value?: number[]): void;
writeRepeatedFixed64(field: number,
value?: number[]): void;
writeRepeatedFixed64String(field: number,
value?: string[]): void;
writeRepeatedSfixed32(field: number,
value?: number[]): void;
writeRepeatedSfixed64(field: number,
value?: number[]): void;
writeRepeatedSfixed64String(field: number,
value?: string[]): void;
writeRepeatedFloat(field: number,
value?: number[]): void;
writeRepeatedDouble(field: number,
value?: number[]): void;
writeRepeatedBool(field: number,
value?: boolean[]): void;
writeRepeatedEnum(field: number,
value?: number[]): void;
writeRepeatedString(field: number,
value?: string[]): void;
writeRepeatedBytes(field: number,
value?: ByteSource[]): void;
writeRepeatedMessage(field: number,
value: Message[],
writerCallback: BinaryWriteCallback): void;
writeRepeatedGroup(field: number,
value: Message[],
writerCallback: BinaryWriteCallback): void;
writeRepeatedFixedHash64(field: number,
value?: string[]): void;
writeRepeatedVarintHash64(field: number,
value?: string[]): void;
writePackedInt32(field: number,
value?: number[]): void;
writePackedInt32String(field: number,
value?: string[]): void;
writePackedInt64(field: number,
value?: number[]): void;
writePackedInt64String(field: number,
value?: string[]): void;
writePackedUint32(field: number,
value?: number[]): void;
writePackedUint32String(field: number,
value?: string[]): void;
writePackedUint64(field: number,
value?: number[]): void;
writePackedUint64String(field: number,
value?: string[]): void;
writePackedSint32(field: number,
value?: number[]): void;
writePackedSint64(field: number,
value?: number[]): void;
writePackedSint64String(field: number,
value?: string[]): void;
writePackedFixed32(field: number,
value?: number[]): void;
writePackedFixed64(field: number,
value?: number[]): void;
writePackedFixed64String(field: number,
value?: string[]): void;
writePackedSfixed32(field: number,
value?: number[]): void;
writePackedSfixed64(field: number,
value?: number[]): void;
writePackedSfixed64String(field: number,
value?: string[]): void;
writePackedFloat(field: number,
value?: number[]): void;
writePackedDouble(field: number,
value?: number[]): void;
writePackedBool(field: number,
value?: boolean[]): void;
writePackedEnum(field: number,
value?: number[]): void;
writePackedFixedHash64(field: number,
value?: string[]): void;
writePackedVarintHash64(field: number,
value?: string[]): void;
}
export class BinaryEncoder {
constructor();
length(): number;
end(): number[];
writeSplitVarint64(lowBits: number,
highBits: number): void;
writeSplitFixed64(lowBits: number,
highBits: number): void;
writeUnsignedVarint32(value: number): void;
writeSignedVarint32(value: number): void;
writeUnsignedVarint64(value: number): void;
writeSignedVarint64(value: number): void;
writeZigzagVarint32(value: number): void;
writeZigzagVarint64(value: number): void;
writeZigzagVarint64String(value: string): void;
writeUint8(value: number): void;
writeUint16(value: number): void;
writeUint32(value: number): void;
writeUint64(value: number): void;
writeInt8(value: number): void;
writeInt16(value: number): void;
writeInt32(value: number): void;
writeInt64(value: number): void;
writeInt64String(value: string): void;
writeFloat(value: number): void;
writeDouble(value: number): void;
writeBool(value: boolean): void;
writeEnum(value: number): void;
writeBytes(bytes: Uint8Array): void;
writeVarintHash64(hash: string): void;
writeFixedHash64(hash: string): void;
writeString(value: string): number;
}
export class BinaryDecoder {
constructor(bytes?: ByteSource,
start?: number,
length?: number)
static alloc(bytes?: ByteSource,
start?: number,
length?: number): BinaryDecoder;
free(): void;
clone(): BinaryDecoder;
clear(): void;
getBuffer(): Uint8Array;
setBlock(data: ByteSource,
start?: number,
length?: number): void;
getEnd(): number;
setEnd(end: number): void;
reset(): void;
getCursor(): number;
setCursor(cursor: number): void;
advance(count: number): void;
atEnd(): boolean;
pastEnd(): boolean;
getError(): boolean;
skipVarint(): void;
unskipVarint(value: number): void;
readUnsignedVarint32(): number;
readSignedVarint32(): number;
readUnsignedVarint32String(): number;
readSignedVarint32String(): number;
readZigzagVarint32(): number;
readUnsignedVarint64(): number;
readUnsignedVarint64String(): number;
readSignedVarint64(): number;
readSignedVarint64String(): number;
readZigzagVarint64(): number;
readZigzagVarint64String(): number;
readUint8(): number;
readUint16(): number;
readUint32(): number;
readUint64(): number;
readUint64String(): string;
readInt8(): number;
readInt16(): number;
readInt32(): number;
readInt64(): number;
readInt64String(): string;
readFloat(): number;
readDouble(): number;
readBool(): boolean;
readEnum(): number;
readString(length: number): string;
readStringWithLength(): string;
readBytes(length: number): Uint8Array;
readVarintHash64(): string;
readFixedHash64(): string;
}
export class BinaryIterator {
constructor(decoder?: BinaryDecoder,
next?: () => number|boolean|string|null,
elements?: Array<number|boolean|string>)
static alloc(decoder?: BinaryDecoder,
next?: () => number|boolean|string|null,
elements?: Array<number|boolean|string>): BinaryIterator;
free(): void;
clear(): void;
get(): (ScalarFieldType | null);
atEnd(): boolean;
next(): (ScalarFieldType | null);
}
export namespace BinaryConstants {
export enum FieldType {
INVALID = -1,
DOUBLE = 1,
FLOAT = 2,
INT64 = 3,
UINT64 = 4,
INT32 = 5,
FIXED64 = 6,
FIXED32 = 7,
BOOL = 8,
STRING = 9,
GROUP = 10,
MESSAGE = 11,
BYTES = 12,
UINT32 = 13,
ENUM = 14,
SFIXED32 = 15,
SFIXED64 = 16,
SINT32 = 17,
SINT64 = 18,
FHASH64 = 30,
VHASH64 = 31,
}
export enum WireType {
INVALID = -1,
VARINT = 0,
FIXED64 = 1,
DELIMITED = 2,
START_GROUP = 3,
END_GROUP = 4,
FIXED32 = 5,
}
const FieldTypeToWireType: (fieldType: FieldType) => WireType;
const INVALID_FIELD_NUMBER: number;
const FLOAT32_EPS: number;
const FLOAT32_MIN: number;
const FLOAT32_MAX: number;
const FLOAT64_EPS: number;
const FLOAT64_MIN: number;
const FLOAT64_MAX: number;
const TWO_TO_20: number;
const TWO_TO_23: number;
const TWO_TO_31: number;
const TWO_TO_32: number;
const TWO_TO_52: number;
const TWO_TO_63: number;
const TWO_TO_64: number;
const ZERO_HASH: string;
}
export namespace arith {
export class UInt64 {
lo: number;
hi: number;
constructor(lo: number,
hi: number);
cmp(other: UInt64): number;
rightShift(): UInt64;
leftShift(): UInt64;
msb(): boolean;
lsb(): boolean;
zero(): boolean;
add(other: UInt64): UInt64;
sub(other: UInt64): UInt64;
static mul32x32(a: number,
b: number): UInt64;
mul(a: number): UInt64;
div(divisor: number): [UInt64, UInt64];
toString(): string;
static fromString(str: string): UInt64;
clone(): UInt64;
}
export class Int64 {
lo: number;
hi: number;
constructor(lo: number,
hi: number);
add(other: Int64): Int64;
sub(other: Int64): Int64;
clone(): Int64;
toString(): string;
static fromString(str: string): Int64;
}
}
// jspb.utils package excluded as it likely shouldn't be called by user code
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"google-protobuf-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+2 -2
View File
@@ -1,5 +1,5 @@
/// <reference types="jasmine" />
declare function describe(desc: string, fn: () => void): void;
declare function it(desc: string, fn: () => void): void;
describe("tester Google Analytics Tracker _gat object", () => {
it("can set ga script element", () => {
+78
View File
@@ -0,0 +1,78 @@
/*
Licensed under the MIT License (MIT)
Copyright (c) 2016 David Hara
*/
import * as React from 'react';
import { render } from 'react-dom';
import Griddle, { CustomColumnComponentProps } from 'griddle-react';
import CustomColumnComponentGrid from './test/CustomColumnComponent';
import CustomHeaderComponentGrid from './test/CustomHeaderComponent';
import CustomFilterComponentGrid from './test/CustomFilterComponent';
interface MyCustomResult {
name: string,
test: string
}
class LinkComponent extends React.Component<CustomColumnComponentProps<MyCustomResult>, any> {
render() {
var url = "speakers/" + this.props.rowData.test + "/" + this.props.data;
return <a href={url}>{this.props.data}</a>
}
}
const StatelessFunctionComponent = (props: CustomColumnComponentProps<MyCustomResult>) => {
var url = "speakers/" + props.rowData.test + "/" + props.data;
return <a href={url}>{props.data}</a>
};
var columnMeta = [
{
columnName: "name",
order: 1,
locked: false,
visible: true,
customComponent: StatelessFunctionComponent
}];
var results: MyCustomResult[] = [
{
name: 'David Hara',
test: 'blah'
},
{
name: 'Hara, David',
test: 'blah2'
}
];
var rowMetaData = {
bodyCssClassName: (rowData: MyCustomResult) => {
return rowData.test;
}
};
type TypedGriddle = new () => Griddle<MyCustomResult>;
const TypedGriddle = Griddle as TypedGriddle;
render(
<div>
<h1>Custom Column Component Grid</h1>
<CustomColumnComponentGrid />
<h1>Custom Header Component Grid</h1>
<CustomHeaderComponentGrid />
<h1>Custom Filter Component Grid</h1>
<CustomFilterComponentGrid />
<TypedGriddle
results={results}
columnMetadata={columnMeta}
rowMetadata={rowMetaData}
sortAscendingComponent={<span className="fa fa-sort-alpha-asc"/>}
sortDescendingComponent={<span className="fa fa-sort-alpha-desc"/>}
customRowComponent={LinkComponent}
/>
</div>,
document.getElementById('root')
);
+170
View File
@@ -0,0 +1,170 @@
// Type definitions for griddle-react 0.7
// Project: https://github.com/griddlegriddle/griddle
// Definitions by: David Hara <https://github.com/hodavidhara>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/*
The MIT License (MIT)
Copyright (c) 2016 David Hara
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import * as React from 'react';
type ReactClass<T> = React.ComponentClass<T> | React.StatelessComponent<T>
export interface CustomColumnComponentProps<T> {
data: any;
rowData: T;
metaData: ColumnMetaData<T>;
}
export interface CustomRowComponentProps<T> {
data: T;
}
export interface CustomGridComponentProps<T> {
data: T[];
}
export interface CustomPagerComponentProps {
currentPage: number;
maxPage: number;
nextText: string;
previousText: string;
next(): void;
previous(): void;
setPage(number: number): void;
}
export interface CustomHeaderComponentProps {
filterByColumn?(filter: string, columnName: string): void;
columnName: string;
displayName: string;
}
export interface CustomFilterComponentProps {
placeholderText?: string;
changeFilter(val: any): void;
}
export interface ColumnMetaData<T> {
columnName: string;
cssClassName?: string;
customComponent?: ReactClass<CustomColumnComponentProps<T>>;
customHeaderComponent?: ReactClass<CustomHeaderComponentProps>;
customHeaderComponentProps?: {};
displayName?: string;
locked?: boolean;
order?: number;
sortable?: boolean;
visible?: boolean;
}
export interface BodyCssClassNameFunction<T> {
(rowData: T): string;
}
export interface RowMetaData<T> {
bodyCssClassName?: BodyCssClassNameFunction<T> | string;
}
export interface GriddleProps<T> {
columns?: string[];
columnMetadata?: ColumnMetaData<T>[];
rowMetadata?: RowMetaData<T>;
results?: T[];
resultsPerPage?: number;
initialSort?: string;
initialSortAscending?: boolean;
gridClassName?: string;
tableClassName?: string;
customFormatClassName?: string;
settingsText?: string;
filterPlaceholderText?: string;
nextText?: string;
previousText?: string;
maxRowsText?: string;
enableCustomFormatText?: string;
childrenColumnName?: string;
metadataColumns?: string[];
showFilter?: boolean;
showSettings?: boolean;
useCustomRowComponent?: boolean;
useCustomGridComponent?: boolean;
useCustomPagerComponent?: boolean;
useCustomFilterer?: boolean;
useCustomFilterComponent?: boolean;
useGriddleStyles?: boolean;
customRowComponent?: ReactClass<CustomRowComponentProps<T>>
customGridComponent?: ReactClass<CustomGridComponentProps<T>>
customPagerComponent?: ReactClass<CustomPagerComponentProps>
customFilterComponent?: ReactClass<CustomFilterComponentProps>
customFilterer?(items: T[], query: any): T[];
enableToggleCustom?: boolean;
noDataMessage?: string;
noDataClassName?: string;
customNoDataComponent?: ReactClass<void>
showTableHeading?: boolean;
showPager?: boolean;
useFixedHeader?: boolean;
useExternal?: boolean;
externalSetPage?(index: number): void;
externalChangeSort?(sort: string, sortAscending: boolean): void;
externalSetFilter?(filter: string): void;
externalSetPageSize?(size: number): void;
externalMaxPage?: number;
externalCurrentPage?: number;
externalSortColumn?: string;
externalSortAscending?: boolean;
externalLoadingComponent?: ReactClass<void>
externalIsLoading?: boolean;
enableInfiniteScroll?: boolean;
bodyHeight?: number;
paddingHeight?: number;
rowHeight?: number;
infiniteScrollLoadTreshold?: number;
useFixedLayout?: boolean;
isSubGriddle?: boolean;
enableSort?: boolean;
sortAscendingClassName?: string;
sortDescendingClassName?: string;
parentRowCollapsedClassName?: string;
parentRowExpandedClassName?: string;
settingsToggleClassName?: string;
nextClassName?: string;
previousClassName?: string;
sortAscendingComponent?: string | React.ReactElement<any>;
sortDescendingComponent?: string | React.ReactElement<any>;
sortDefaultComponent?: string | React.ReactElement<any>;
parentRowCollapsedComponent?: string | React.ReactElement<any>;
parentRowExpandedComponent?: string | React.ReactElement<any>;
settingsIconComponent?: string | React.ReactElement<any>;
nextIconComponent?: string | React.ReactElement<any>;
previousIconComponent?: string | React.ReactElement<any>;
onRowClick?(): void;
}
declare class Griddle<T> extends React.Component<GriddleProps<T>, any> {
}
export default Griddle;
@@ -0,0 +1,70 @@
/*
Licensed under the MIT License (MIT)
Copyright (c) 2016 David Hara
*/
import * as React from 'react';
import Griddle, { CustomColumnComponentProps } from 'griddle-react';
interface MyCustomResult {
name: string,
test: string
}
class LinkComponent extends React.Component<CustomColumnComponentProps<MyCustomResult>, any> {
render() {
var url = "speakers/" + this.props.rowData.test + "/" + this.props.data;
return <a href={url}>{this.props.data}</a>
}
}
const StatelessFunctionComponent = (props: CustomColumnComponentProps<MyCustomResult>) => {
var url = "speakers/" + props.rowData.test + "/" + props.data;
return <a href={url}>{props.data}</a>
};
var columnMeta = [
{
columnName: "name",
order: 1,
locked: false,
visible: true,
customComponent: StatelessFunctionComponent
}];
var results: MyCustomResult[] = [
{
name: 'David Hara',
test: 'blah'
},
{
name: 'Hara, David',
test: 'blah2'
}
];
var rowMetaData = {
bodyCssClassName: (rowData: MyCustomResult) => {
return rowData.test;
}
};
class CustomColumnComponentGrid extends React.Component<any, any> {
render() {
type TypedGriddle = new () => Griddle<MyCustomResult>;
const TypedGriddle = Griddle as TypedGriddle;
return (
<TypedGriddle
results={results}
columnMetadata={columnMeta}
rowMetadata={rowMetaData}
sortAscendingComponent={<span className="fa fa-sort-alpha-asc"/>}
sortDescendingComponent={<span className="fa fa-sort-alpha-desc"/>}
customRowComponent={LinkComponent} />
);
};
}
export default CustomColumnComponentGrid;
@@ -0,0 +1,91 @@
/*
Licensed under the MIT License (MIT)
Copyright (c) 2016 David Hara
*/
import * as _ from 'lodash';
import * as React from 'react';
import Griddle, { CustomFilterComponentProps } from 'griddle-react';
const CustomFilterFunction = (items: ResultType[], query: string): ResultType[] => {
return _.filter(items, (item) => {
let match = false;
_.forIn(item, (value, key) => {
if (String(value).toLowerCase().indexOf(query.toLowerCase()) >= 0) {
match = true;
return;
}
});
return match;
});
};
class CustomFilterComponent extends React.Component<CustomFilterComponentProps, any> {
query: string = '';
searchChange(event: React.FormEvent<HTMLInputElement>) {
this.query = event.currentTarget.value;
this.props.changeFilter(this.query);
}
render() {
return (
<div className="filter-container">
<input type="text"
name="search"
placeholder="Search..."
onChange={this.searchChange.bind(this)}/>
</div>
);
}
}
interface ResultType {
id: number;
name: string;
city: string;
state: string;
country: string;
company: string;
favoriteNumber: number;
}
var someData: ResultType[] = [
{
"id": 0,
"name": "Mayer Leonard",
"city": "Kapowsin",
"state": "Hawaii",
"country": "United Kingdom",
"company": "Ovolo",
"favoriteNumber": 7
},
{
"id": 1,
"name": "Koch Becker",
"city": "Johnsonburg",
"state": "New Jersey",
"country": "Madagascar",
"company": "Eventage",
"favoriteNumber": 2
}
];
class CustomFilterComponentGrid extends React.Component<any, any> {
render() {
type TypedGriddle = new () => Griddle<ResultType>;
const TypedGriddle = Griddle as TypedGriddle;
return (
<TypedGriddle results={someData} showFilter={true}
useCustomFilterer={true} customFilterer={CustomFilterFunction}
useCustomFilterComponent={true} customFilterComponent={CustomFilterComponent}/>
);
}
}
export default CustomFilterComponentGrid;
@@ -0,0 +1,95 @@
/*
Licensed under the MIT License (MIT)
Copyright (c) 2016 David Hara
*/
import * as React from 'react';
import Griddle, { ColumnMetaData, CustomHeaderComponentProps } from 'griddle-react';
interface MoreCustomHeaderComponentProps extends CustomHeaderComponentProps {
color: string;
}
class HeaderComponent extends React.Component<MoreCustomHeaderComponentProps, any> {
textOnClick(e: React.FormEvent<HTMLInputElement>) {
e.stopPropagation();
}
filterText(e: React.FormEvent<HTMLInputElement>) {
this.props.filterByColumn(e.currentTarget.value, this.props.columnName)
}
render() {
return (
<span>
<div><strong style={{color: this.props.color}}>{this.props.displayName}</strong></div>
<input type='text' onChange={this.filterText.bind(this)} onClick={this.textOnClick.bind(this)}/>
</span>
);
}
}
interface ResultType {
id: number;
name: string;
city: string;
state: string;
country: string;
company: string;
favoriteNumber: number;
}
var someData: ResultType[] = [
{
"id": 0,
"name": "Mayer Leonard",
"city": "Kapowsin",
"state": "Hawaii",
"country": "United Kingdom",
"company": "Ovolo",
"favoriteNumber": 7
},
{
"id": 1,
"name": "Koch Becker",
"city": "Johnsonburg",
"state": "New Jersey",
"country": "Madagascar",
"company": "Eventage",
"favoriteNumber": 2
}
];
var columnMeta: ColumnMetaData<ResultType>[] = [
{
columnName: 'name',
order: 1,
sortable: false,
visible: true,
},
{
columnName: 'city',
customHeaderComponent: HeaderComponent,
customHeaderComponentProps: {color: 'red'}
},
{
columnName: 'state',
customHeaderComponent: HeaderComponent,
customHeaderComponentProps: {color: 'blue'}
}
];
class CustomHeaderComponentGrid extends React.Component<any, any> {
render() {
type TypedGriddle = new () => Griddle<ResultType>;
const TypedGriddle = Griddle as TypedGriddle;
return (
<TypedGriddle results={someData} columnMetadata={columnMeta} columns={["name", "city", "state", "country"]}/>
);
}
}
export default CustomHeaderComponentGrid;
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"jsx": "preserve",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"griddle-react-tests.tsx",
"test/CustomColumnComponent.tsx",
"test/CustomFilterComponent.tsx",
"test/CustomHeaderComponent.tsx"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+35
View File
@@ -0,0 +1,35 @@
// Type definitions for isbn-utils 1.1
// Project: https://github.com/GitbookIO/isbn-utils
// Definitions by: Jørgen Elgaard Larsen <https://github.com/elhaard/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type IGroups = any;
export class ISBNcodes {
readonly source: string;
readonly prefix: string;
readonly group: string;
readonly publisher: string;
readonly article: string;
readonly check: string;
readonly check10: string;
readonly check13: string;
readonly groupname: string;
}
export class ISBN {
constructor(val: string, groups: IGroups);
asIsbn10(hyphenate?: boolean): string;
asIsbn13(hyphenate?: boolean): string;
codes: ISBNcodes;
isIsbn10(): boolean;
isIsbn13(): boolean;
isValid(): boolean;
}
export function asIsbn10(isbn: string, hyphenate?: boolean): string;
export function asIsbn13(isbn: string, hyphenate?: boolean): string;
export function parse(isbn: string, groups?: IGroups): ISBN|null;
export function hyphenate(isbn: string): string;
export function isValid(isbn: string, groups?: IGroups): boolean;
+36
View File
@@ -0,0 +1,36 @@
import * as isbn from 'isbn-utils';
const isbn10a: isbn.ISBN|null = isbn.parse('4873113369');
let b: boolean;
let s: string;
if (isbn10a !== null) {
b = isbn10a.isIsbn10();
b = isbn10a.isIsbn13();
s = isbn10a.asIsbn10();
s = isbn10a.asIsbn10(true);
s = isbn10a.asIsbn13();
s = isbn10a.asIsbn13(true);
s = isbn10a.codes.source;
s = isbn10a.codes.prefix;
s = isbn10a.codes.group;
s = isbn10a.codes.publisher;
s = isbn10a.codes.article;
s = isbn10a.codes.check;
s = isbn10a.codes.check10;
s = isbn10a.codes.check13;
s = isbn10a.codes.groupname;
}
const bad: isbn.ISBN|null = isbn.parse('invalid format');
if (bad === null) {
s = 'Bummer.';
}
s = isbn.asIsbn13('4-87311-336-9');
s = isbn.asIsbn13('4-87311-336-9', true);
s = isbn.asIsbn10('978-4-87311-336-4');
s = isbn.asIsbn10('978-4-87311-336-4', true);
s = isbn.hyphenate('9784873113364');
+23
View File
@@ -0,0 +1,23 @@
{
"files": [
"index.d.ts",
"isbn-utils-tests.ts"
],
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+34 -2
View File
@@ -2,6 +2,38 @@
// Project: https://github.com/gburghardt/jasmine-data_driven_tests
// Definitions by: Anthony MacKinnon <https://github.com/AnthonyMacKinnon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void;
declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void;
declare var all: JasmineDataDrivenTest;
declare var xall: JasmineDataDrivenTest;
interface JasmineDataDrivenTest {
<T, U, V, W, X, Y, Z>(
description: string,
dataset: Array<[T, U, V, W, X, Y, Z]>,
assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, arg6: Z, done: () => void) => void): void;
<T, U, V, W, X, Y>(
description: string,
dataset: Array<[T, U, V, W, X, Y]>,
assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, done: () => void) => void): void;
<T, U, V, W, X>(
description: string,
dataset: Array<[T, U, V, W, X]>,
assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, done: () => void) => void): void;
<T, U, V, W>(
description: string,
dataset: Array<[T, U, V, W]>,
assertion: (arg0: T, arg1: U, arg2: V, arg3: W, done: () => void) => void): void;
<T, U, V>(
description: string,
dataset: Array<[T, U, V]>,
assertion: (arg0: T, arg1: U, arg2: V, done: () => void) => void): void;
<T, U>(
description: string,
dataset: Array<[T, U]>,
assertion: (arg0: T, arg1: U, done: () => void) => void): void;
<T>(
description: string,
dataset: T[],
assertion: (value: T, done: () => void) => void): void;
}
@@ -1,9 +1,8 @@
/// <reference types="jasmine" />
all("A data driven test is a suite with multiple specs",
['a', 'b', 'c'],
(value: string) => {
value => {
expect(value).not.toBe('d');
}
);
@@ -13,7 +12,7 @@ all("A data driven test can have many arguments",
[1, 2, 3],
[2, 4, 6]
],
(a: number, b: number, c: number) => {
(a, b, c) => {
expect(c - (a + b)).toBe(0);
}
);
@@ -23,7 +22,7 @@ all("A data driven test can be asynchronous",
[3, 1],
[5, 2]
],
(a: number, b: number, done: () => void) => {
(a, b, done) => {
setTimeout(() => {
expect(a - b > 0).toBe(true);
done();
@@ -33,7 +32,7 @@ all("A data driven test can be asynchronous",
xall("A data driven test can be pending",
[1, 2, 3],
(value: number) => {
value => {
expect(value < 4).toBe(true);
}
);
@@ -47,7 +46,7 @@ describe("A suite", () => {
all("can contain data driven tests",
[1, 2, 3],
(b: number) => {
b => {
expect(a - b > 0).toBe(true);
}
);
+7 -3
View File
@@ -2,10 +2,14 @@
// Project: https://github.com/searls/jasmine-fixture
// Definitions by: Craig Brett <https://github.com/craigbrett17/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/** Affixes the given jquery selectors into the body and will be removed after each spec
* @param {string} selector The JQuery selector to be added to the dom
*/
/// <reference types="jasmine" />
/**
* Affixes the given jquery selectors into the body and will be removed after each spec
* @param {string} selector The JQuery selector to be added to the dom
*/
declare function affix(selector: string): JQuery;
interface JQuery {
-2
View File
@@ -1,8 +1,6 @@
/// <reference types="jasmine" />
/// <reference types="jquery" />
/// <reference types="jasmine-jquery" />
describe("Jasmine fixture extension", () => {
describe("Affixes dom elements to body", () => {
it("Inserts a new element on affix", () => {
+51 -47
View File
@@ -1,7 +1,7 @@
import Jimp = require('jimp')
// All code below is from node-jimp document
Jimp.read("lenna.png", function (err, data) {
Jimp.read("lenna.png", (err, data) => {
if (err) throw err;
data.resize(256, 256) // resize
.quality(60) // set JPEG quality
@@ -9,30 +9,30 @@ Jimp.read("lenna.png", function (err, data) {
.write("lena-small-bw.jpg"); // save
});
Jimp.read("lenna.png").then(function (lenna) {
Jimp.read("lenna.png").then(lenna => {
lenna.resize(256, 256) // resize
.quality(60) // set JPEG quality
.greyscale() // set greyscale
.write("lena-small-bw.jpg"); // save
}).catch(function (err) {
}).catch(err => {
console.error(err);
});
Jimp.read("./path/to/image.jpg", function (err, image) {
Jimp.read("./path/to/image.jpg", (err, image) => {
// do stuff with the image (if no exception)
});
Jimp.read("./path/to/image.jpg").then(function (image) {
Jimp.read("./path/to/image.jpg").then(image => {
// do stuff with the image
}).catch(function (err) {
}).catch(err => {
// handle an exception
});
Jimp.read(new Buffer(''), function (err, image) {
Jimp.read(new Buffer(''), (err, image) => {
// do stuff with the image (if no exception)
});
Jimp.read("http://www.example.com/path/to/lenna.jpg", function (err, image) {
Jimp.read("http://www.example.com/path/to/lenna.jpg", (err, image) => {
// do stuff with the image (if no exception)
});
@@ -51,51 +51,55 @@ var hex = 0xFFFFFFFF
var r = 0
var n = 1
/* Resize */
image.contain( w, h); // scale the image to the given width and height, some parts of the image may be letter boxed
image.cover( w, h); // scale the image to the given width and height, some parts of the image may be clipped
image.resize( w, h); // resize the image. Jimp.AUTO can be passed as one of the values.
image.scale(f ); // scale the image by the factor f
image.scaleToFit( w, h ); // scale the image to the largest size that fits inside the given width and height
image.contain(w, h); // scale the image to the given width and height, some parts of the image may be letter boxed
image.cover(w, h); // scale the image to the given width and height, some parts of the image may be clipped
image.resize(w, h); // resize the image. Jimp.AUTO can be passed as one of the values.
image.scale(f); // scale the image by the factor f
image.scaleToFit(w, h); // scale the image to the largest size that fits inside the given width and height
// An optional resize mode can be passed with all resize methods.
/* Crop */
image.autocrop(); // automatically crop same-color borders from image (if any)
image.crop( x, y, w, h ); // crop to the given region
image.crop(x, y, w, h); // crop to the given region
/* Composing */
image.blit( src, x, y );
image.blit(src, x, y);
// blit the image with another Jimp image at x, y, optionally cropped.
image.composite( src, x, y ); // composites another Jimp image over this image at x, y
image.mask( src, x, y ); // masks the image with another Jimp image at x, y using average pixel value
image.composite(src, x, y); // composites another Jimp image over this image at x, y
image.mask(src, x, y); // masks the image with another Jimp image at x, y using average pixel value
/* Flip and rotate */
image.flip( horz, vert ); // flip the image horizontally or vertically
image.mirror( horz, vert ); // an alias for flip
image.rotate( deg ); // rotate the image clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized.
image.flip(horz, vert); // flip the image horizontally or vertically
image.mirror(horz, vert); // an alias for flip
// rotate the image clockwise by a number of degrees.
// Optionally, a resize mode can be passed.
// If `false` is passed as the second parameter,
// the image width and height will not be resized.
image.rotate(deg);
// JPEG images with EXIF orientation data will be automatically re-orientated as appropriate.
/* Colour */
image.brightness( val ); // adjust the brighness by a value -1 to +1
image.contrast( val ); // adjust the contrast by a value -1 to +1
image.brightness(val); // adjust the brighness by a value -1 to +1
image.contrast(val); // adjust the contrast by a value -1 to +1
image.dither565(); // ordered dithering of the image and reduce color space to 16-bits (RGB565)
image.greyscale(); // remove colour from the image
image.invert(); // invert the image colours
image.normalize(); // normalize the channels in an image
/* Alpha channel */
image.fade( f ); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image
image.opacity( f ); // multiply the alpha channel by each pixel by the factor f, 0 - 1
image.fade(f); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image
image.opacity(f); // multiply the alpha channel by each pixel by the factor f, 0 - 1
image.opaque(); // set the alpha channel on every pixel to fully opaque
image.background( hex ); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and
image.background(hex); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and
/* Blurs */
image.gaussian( r ); // Gaussian blur the image by r pixels (VERY slow)
image.blur( r ); // fast blur the image by r pixels
image.gaussian(r); // Gaussian blur the image by r pixels (VERY slow)
image.blur(r); // fast blur the image by r pixels
/* Effects */
image.posterize( n ); // apply a posterization effect with n level
image.posterize(n); // apply a posterization effect with n level
image.sepia(); // apply a sepia wash to the image
image.clone(); // returns a clone of the image
@@ -110,35 +114,35 @@ image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP);
var path = ''
var str = ''
var width = 0
Jimp.loadFont( path ).then(function (font) { // load font from .fnt file
Jimp.loadFont(path).then(font => { // load font from .fnt file
image.print(font, x, y, str); // print a message on an image
image.print(font, x, y, str, width); // print a message on an image with text wrapped at width
});
var cb = (err: Error, data: any) => {}
Jimp.loadFont( path, cb ); // using a callback pattern
Jimp.loadFont(path, cb); // using a callback pattern
Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(function (font) {
Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(font => {
image.print(font, 10, 10, "Hello world!");
});
image.write( path, cb ); // Node-style callback will be fired when write is successful
image.write(path, cb); // Node-style callback will be fired when write is successful
var file = "new_name." + image.getExtension();
image.write(file)
var mime = 'image/png'
image.getBuffer( mime, cb ); // Node-style callback will be fired with result
image.getBase64( mime, cb ); // Node-style callback will be fired with result
image.quality( n ); // set the quality of saved JPEG, 0 - 100
image.getBuffer(mime, cb); // Node-style callback will be fired with result
image.getBase64(mime, cb); // Node-style callback will be fired with result
image.quality(n); // set the quality of saved JPEG, 0 - 100
var bool = true
var number = 0
image.rgba( bool ); // set whether PNGs are saved as RGBA (true, default) or RGB (false)
image.filterType( number ); // set the filter type for the saved PNG
image.deflateLevel( number ); // set the deflate level for the saved PNG
Jimp.deflateStrategy( number ); // set the deflate for the saved PNG (0-3)
image.rgba(bool); // set whether PNGs are saved as RGBA (true, default) or RGB (false)
image.filterType(number); // set the filter type for the saved PNG
image.deflateLevel(number); // set the deflate level for the saved PNG
Jimp.deflateStrategy(number); // set the deflate for the saved PNG (0-3)
image.color([
{ apply: 'hue', params: [ -90 ] },
@@ -146,11 +150,11 @@ image.color([
{ apply: 'xor', params: [ '#06D' ] }
]);
image.convolution([
[-2,-1, 0],
[-2, -1, 0],
[-1, 1, 1],
[ 0, 1, 2]
])
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) {
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
// x, y is the position of this pixel on the image
// idx is the position start position of this rgba tuple in the bitmap Buffer
// this is the image
@@ -172,11 +176,11 @@ var a = 0
Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF
Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255}
var image = new Jimp(256, 256, function (err, image) {
var image = new Jimp(256, 256, (err, image) => {
// this image is 256 x 256, every pixel is set to 0x00000000
});
var image = new Jimp(256, 256, 0xFF0000FF, function (err, image) {
var image = new Jimp(256, 256, 0xFF0000FF, (err, image) => {
// this image is 256 x 256, every pixel is set to 0xFF0000FF
});
@@ -202,13 +206,13 @@ if (distance < 0.15 || diff.percent < 0.15) {
// not a match
}
Jimp.read("lenna.png", function (err, image) {
Jimp.read("lenna.png", function(err, image) {
this.greyscale().scale(0.5).write("lena-half-bw.png");
});
Jimp.read("lenna.png", function (err, image) {
image.greyscale(function(err, image) {
image.scale(0.5, function (err, image) {
Jimp.read("lenna.png", (err, image) => {
image.greyscale((err, image) => {
image.scale(0.5, (err, image) => {
image.write("lena-half-bw.png");
});
});
+7 -1
View File
@@ -91,6 +91,12 @@ export interface IpOptions {
cidr?: string;
}
export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5'
export interface GuidOptions {
version: GuidVersions[] | GuidVersions
}
export interface UriOptions {
/**
* Specifies one or more acceptable Schemes, should only include the scheme name.
@@ -443,7 +449,7 @@ export interface StringSchema extends AnySchema<StringSchema> {
/**
* Requires the string value to be a valid GUID.
*/
guid(): StringSchema;
guid(options?: GuidOptions): StringSchema;
/**
* Requires the string value to be a valid hexadecimal string.
+2
View File
@@ -691,6 +691,8 @@ strSchema = strSchema.ip(ipOpts);
strSchema = strSchema.uri();
strSchema = strSchema.uri(uriOpts);
strSchema = strSchema.guid();
strSchema = strSchema.guid({version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5']});
strSchema = strSchema.guid({version: 'uuidv4'});
strSchema = strSchema.hex();
strSchema = strSchema.hostname();
strSchema = strSchema.isoDate();
+58 -2
View File
@@ -156,6 +156,15 @@ declare namespace joint {
findView(paper: Paper): ElementView;
isElement(): boolean;
scale(scaleX: number, scaleY: number, origin?: Point, options?: any): this;
addPort(port: any, opt?: any): this;
addPorts(ports: any[], opt?: any): this;
removePort(port: any, opt?: any): this;
hasPorts(): boolean;
hasPort(id: string): boolean;
getPorts(): any[];
getPort(id: string): any;
getPortIndex(port: any): number;
portProp(portId: string, path: any, value?: any, opt?: any): joint.dia.Element;
}
interface CSSSelector {
@@ -511,6 +520,7 @@ declare namespace joint {
polyline?: ShapeAttrs;
}
class Polyline extends Generic {
constructor(attributes?: GenericAttributes<PolylineAttrs>, options?: Object);
}
class Image extends Generic {
constructor(attributes?: GenericAttributes<dia.TextAttrs>, options?: Object);
@@ -539,28 +549,40 @@ declare namespace joint {
namespace chess {
class KingWhite extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class KingBlack extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class QueenWhite extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class QueenBlack extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class RookWhite extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class RookBlack extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class BishopWhite extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class BishopBlack extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class KnightWhite extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class KnightBlack extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class PawnWhite extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class PawnBlack extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
}
@@ -582,23 +604,28 @@ declare namespace joint {
removeInPort(port: string, opt?: any): this;
}
class Coupled extends Model {
constructor(attributes?: ModelAttributes, options?: Object);
}
class Atomic extends Model {
constructor(attributes?: ModelAttributes, options?: Object);
}
class Link extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
}
namespace erd {
class Entity extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.TextAttrs>, options?: Object);
constructor(attributes?: GenericAttributes<dia.TextAttrs>, options?: Object);
}
class WeakEntity extends Entity {
constructor(attributes?: GenericAttributes<dia.TextAttrs>, options?: Object);
}
class Relationship extends dia.Element {
constructor(attributes?: GenericAttributes<dia.TextAttrs>, options?: Object);
}
class IdentifyingRelationship extends Relationship {
constructor(attributes?: GenericAttributes<dia.TextAttrs>, options?: Object);
}
interface AttributeAttrs extends dia.TextAttrs {
ellipse?: ShapeAttrs;
@@ -607,12 +634,16 @@ declare namespace joint {
constructor(attributes?: GenericAttributes<AttributeAttrs>, options?: Object);
}
class Multivalued extends Attribute {
constructor(attributes?: GenericAttributes<AttributeAttrs>, options?: Object);
}
class Derived extends Attribute {
constructor(attributes?: GenericAttributes<AttributeAttrs>, options?: Object);
}
class Key extends Attribute {
constructor(attributes?: GenericAttributes<AttributeAttrs>, options?: Object);
}
class Normal extends Attribute {
constructor(attributes?: GenericAttributes<AttributeAttrs>, options?: Object);
}
interface ISAAttrs extends dia.Element {
polygon?: ShapeAttrs;
@@ -621,19 +652,23 @@ declare namespace joint {
constructor(attributes?: GenericAttributes<ISAAttrs>, options?: Object);
}
class Line extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
cardinality(value: string | number): void;
}
}
namespace fsa {
class State extends basic.Circle {
constructor(attributes?: GenericAttributes<basic.CircleAttrs>, options?: Object);
}
class StartState extends dia.Element {
constructor(attributes?: GenericAttributes<basic.CircleAttrs>, options?: Object);
}
class EndState extends dia.Element {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class Arrow extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
}
@@ -655,14 +690,19 @@ declare namespace joint {
constructor(attributes?: GenericAttributes<IOAttrs>, options?: Object);
}
class IO extends Gate {
constructor(attributes?: GenericAttributes<IOAttrs>, options?: Object);
}
class Input extends IO {
constructor(attributes?: GenericAttributes<IOAttrs>, options?: Object);
}
class Output extends IO {
constructor(attributes?: GenericAttributes<IOAttrs>, options?: Object);
}
class Gate11 extends Gate {
constructor(attributes?: GenericAttributes<IOAttrs>, options?: Object);
}
class Gate21 extends Gate {
constructor(attributes?: GenericAttributes<IOAttrs>, options?: Object);
}
interface Image {
'xlink:href'?: string;
@@ -720,11 +760,13 @@ declare namespace joint {
constructor(attributes?: GenericAttributes<MemberAttrs>, options?: Object);
}
class Arrow extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
}
namespace pn {
class Place extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class PlaceView extends dia.ElementView {
renderTokens(): void;
@@ -733,6 +775,7 @@ declare namespace joint {
constructor(attributes?: GenericAttributes<basic.RectAttrs>, options?: Object);
}
class Link extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
}
@@ -750,36 +793,49 @@ declare namespace joint {
class ClassView extends dia.ElementView {
}
class Abstract extends Class {
constructor(attributes?: ClassAttributes, options?: Object);
}
class AbstractView extends ClassView {
constructor(attributes?: ClassAttributes, options?: Object);
}
class Interface extends Class {
constructor(attributes?: ClassAttributes, options?: Object);
}
class InterfaceView extends ClassView {
constructor(attributes?: ClassAttributes, options?: Object);
}
class Generalization extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
class Implementation extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
class Aggregation extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
class Composition extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
class Association extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
interface StateAttributes extends GenericAttributes<ShapeAttrs> {
events?: string[];
}
class State extends basic.Generic {
constructor(attributes?: GenericAttributes<basic.CircleAttrs>, options?: Object);
updateName(): void;
updateEvents(): void;
updatePath(): void;
}
class StartState extends basic.Circle {
constructor(attributes?: GenericAttributes<basic.CircleAttrs>, options?: Object);
}
class EndState extends basic.Generic {
constructor(attributes?: GenericAttributes<dia.SVGAttributes>, options?: Object);
}
class Transition extends dia.Link {
constructor(attributes?: dia.LinkAttributes, options?: Object);
}
}
}
@@ -833,7 +889,7 @@ declare namespace joint {
setLinkVertices?: (link: dia.Link, vertices: Position[]) => void;
}
class DirectedGraph {
export class DirectedGraph {
static layout(graph: dia.Graph | dia.Cell[], options?: LayoutOptions): dia.BBox;
}
}
+16 -1
View File
@@ -1,6 +1,21 @@
/// <reference types="jasmine" />
import Qty from "js-quantities";
declare function describe(desc: string, fn: () => void): void;
declare function it(desc: string, fn: () => void): void;
interface Expect<T> {
not: this;
toBe(y: T): void;
toEqual(y: T): void;
toBeTruthy(): void;
toBeNull(): void;
toBeCloseTo(this: Expect<number>, x: number, sigFigs: number): void;
toThrow(this: Expect<() => void>, msg?: string): void;
toContain<U>(this: Expect<U[]>, x: U): void;
};
declare function expect<T>(x: T): Expect<T>;
declare function beforeEach(f: () => void): void;
declare function afterEach(f: () => void): void;
// From project readme
let qty: Qty;
+803 -620
View File
File diff suppressed because it is too large Load Diff
+2692
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,137 @@
/// <reference types="knuddels-userapps-api" />
class Server implements App {
private usersPlaying: { [nick: string]: number } = {};
private isShuttingDown: boolean = false;
private htmlFile: HTMLFile = new HTMLFile('start.html');
private appContent: AppContent = AppContent.overlayContent(this.htmlFile, 243, 266);
onAppStart() {
KnuddelsServer.getChannel()
.getOnlineUsers(UserType.Human)
.forEach((user) => {
this.onUserJoined(user)
});
};
onUserJoined(user: User) {
const botNick = KnuddelsServer.getDefaultBotUser()
.getNick()
.escapeKCode();
user.sendPrivateMessage('Lust auf ne Runde Ziegenphobie? Mit nur _°BB>_h1 Knuddel|/appknuddel ' + botNick + '<°°°_ bist du dabei!');
};
onUserLeft(user: User) {
if (this.usersPlaying[user.getNick()] == 1) {
KnuddelsServer.getDefaultBotUser()
.transferKnuddel(user, new KnuddelAmount(1), 'Du hast den Channel verlassen.');
delete this.usersPlaying[user.getNick()];
}
};
onPrepareShutdown() {
if (!this.isShuttingDown) {
this.isShuttingDown = true;
for (let key in this.usersPlaying) {
const userId = KnuddelsServer.getUserAccess()
.getUserId(key);
const user = KnuddelsServer.getUserAccess()
.getUserById(userId);
KnuddelsServer.getDefaultBotUser()
.transferKnuddel(user, new KnuddelAmount(1), 'Die App fährt gleich herunter.');
user.getAppContentSessions()
.forEach((session: AppContentSession) => {
session.remove();
});
delete this.usersPlaying[key];
}
}
}
onBeforeKnuddelReceived(knuddelTransfer: KnuddelTransfer) {
const sender = knuddelTransfer.getSender();
if (!sender.canSendAppContent(this.appContent)) {
knuddelTransfer.reject('Sorry, mit diesem Gerät kannst du gerade nicht spielen.');
} else if (sender.isChannelOwner() && knuddelTransfer.getKnuddelAmount()
.asNumber() != 1) {
knuddelTransfer.accept();
} else if (this.isShuttingDown) {
knuddelTransfer.reject('Du App nimmt gerade keine neuen Spieler an.');
} else if (this.usersPlaying[sender.getNick()]) {
knuddelTransfer.reject('Du spielst bereits.');
} else if (knuddelTransfer.getKnuddelAmount()
.asNumber() != 1) {
const botNick = KnuddelsServer.getDefaultBotUser()
.getNick()
.escapeKCode();
knuddelTransfer.reject('Du musst genau _°BB>_h1 Knuddel senden|/appknuddel ' + botNick + '<°°°_...');
} else {
knuddelTransfer.accept();
}
};
onKnuddelReceived(user: User, receiver: User, knuddelAmount: KnuddelAmount) {
if (knuddelAmount.asNumber() == 1) {
this.usersPlaying[user.getNick()] = 1;
user.sendAppContent(this.appContent);
} else {
user.sendPrivateMessage('Vielen Dank für die Einzahlung.');
}
};
onEventReceived(user: User, key: string, data: string) {
if (key == 'selectedEntry' && this.usersPlaying[user.getNick()] == 1) {
this.usersPlaying[user.getNick()] = 2;
setTimeout(() => {
let doorNumber = parseInt(data[data.length - 1], 10);
let winningDoorNumber = RandomOperations.nextInt(0, 2) + 1;
let hasWon = winningDoorNumber == doorNumber;
let text = hasWon
? 'Richtig getippt'
: 'Knapp daneben';
user.getAppContentSession(AppViewMode.Overlay)
.getAppContent()
.sendEvent('openDoor', {
'door': doorNumber,
'winningDoor': winningDoorNumber,
'text': text,
});
if (hasWon) {
KnuddelsServer.getDefaultBotUser()
.transferKnuddel(user, new KnuddelAmount(2), 'Richtig getippt...');
}
setTimeout(() => {
const botNick = KnuddelsServer.getDefaultBotUser()
.getNick()
.escapeKCode();
user.sendPrivateMessage('Na, Lust auf _°BB>_hnoch eine Runde|/appknuddel ' + botNick + '<°°°_?');
user.getAppContentSessions()
.forEach((session: AppContentSession) => {
session.remove();
});
delete this.usersPlaying[user.getNick()];
}, 4000);
}, 1500);
}
};
}
declare let App: Server; // tell the compiler that "App" will be available
App = new Server();
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"knuddels-userapps-api-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+2 -2
View File
@@ -1466,7 +1466,7 @@ declare namespace L {
export function divIcon(options?: DivIconOptions): DivIcon;
export interface MarkerOptions extends InteractiveLayerOptions {
icon?: Icon;
icon?: Icon | DivIcon;
clickable?: boolean;
draggable?: boolean;
keyboard?: boolean;
@@ -1483,7 +1483,7 @@ declare namespace L {
getLatLng(): LatLng;
setLatLng(latlng: LatLngExpression): this;
setZIndexOffset(offset: number): this;
setIcon(icon: Icon): this;
setIcon(icon: Icon | DivIcon): this;
setOpacity(opacity: number): this;
getElement(): HTMLElement;
+12
View File
@@ -448,6 +448,17 @@ L.marker([1, 2], {
})
}).bindPopup('<p>Hi</p>');
L.marker([1, 2], {
icon: L.divIcon({
className: 'my-icon-class'
})
}).setIcon(L.icon({
iconUrl: 'my-icon.png'
})).setIcon(L.divIcon({
className: 'my-div-icon'
}));;
L.Util.extend({});
L.Util.create({});
L.Util.bind(() => {}, {});
@@ -466,3 +477,4 @@ L.Util.indexOf([], {});
L.Util.requestAnimFrame(() => {});
L.Util.cancelAnimFrame(1);
L.Util.emptyImageUrl;
+7
View File
@@ -10387,6 +10387,13 @@ declare namespace _ {
* @param funcs Functions to invoke.
* @return Returns the new function.
*/
// 0-argument first function
flow<R1, R2>(f1: () => R1, f2: (a: R1) => R2): () => R2;
flow<R1, R2, R3>(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): () => R3;
flow<R1, R2, R3, R4>(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): () => R4;
flow<R1, R2, R3, R4, R5>(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5;
flow<R1, R2, R3, R4, R5, R6>(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6;
flow<R1, R2, R3, R4, R5, R6, R7>(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7;
// 1-argument first function
flow<A1, R1, R2>(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2;
flow<A1, R1, R2, R3>(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3;
+7 -7
View File
@@ -245,7 +245,7 @@ declare namespace l {
* @header app.middleware(name, handler
*/
middleware(name: string, paths?: any[]|string|RegExp, handler?: () => void): any;
middleware(name: string, paths?: any[]|string|RegExp, handler?: core.Handler): any;
}
// interface CookieOptions extends core.CookieOptions { }
@@ -1067,7 +1067,7 @@ declare namespace l {
* @class PersistedModel
*/
class PersistedModel {
class PersistedModel extends Model {
/**
* Apply an update list
@@ -1270,7 +1270,7 @@ declare namespace l {
* @param {Array} model First model instance that matches the filter or null if none found
*/
static findOne(filter?: {fields: string|any|any[]; include: string|any|any[]; order: string; skip: number; where: any; }, callback?: (err: Error, model: any[]) => void): void;
static findOne(filter?: {fields?: string|any|any[]; include?: string|any|any[]; order?: string; skip?: number; where?: any; }, callback?: (err: Error, model: any) => void): void;
/**
* Finds one record matching the optional filter object. If not found, creates
@@ -1741,7 +1741,7 @@ declare namespace l {
created: Date;
/** Extends the `Model.settings` object. */
settings: { http: { path: string }; acls: ACL, accessTokenIdLength: number};
settings: { http: { path: string }; acls: ACL[], accessTokenIdLength: number};
/**
* Create a cryptographically random access token id
@@ -1838,7 +1838,7 @@ declare namespace l {
principalId: string;
/** settings Extends the `Model.settings` object. */
settings: { http: { path: string }; acls: ACL, defaultPermission: 'DENY'};
settings: { http: { path: string }; acls: ACL[], defaultPermission: 'DENY'};
/**
* Check if the request has the permission to access.
@@ -2125,7 +2125,7 @@ declare namespace l {
* settings.ignoreErrors By default, when changes are rectified, an error will throw an exception.
* However, if this setting is true, then errors will not throw exceptions.
*/
settings: { http: { path: string }; acls: ACL; hashAlgorithm: string; ignoreErrors: boolean; };
settings: { http: { path: string }; acls: ACL[]; hashAlgorithm: string; ignoreErrors: boolean; };
/**
* Are both changes deletes?
@@ -2800,7 +2800,7 @@ declare namespace l {
*/
settings: {
http: { path: string };
acls: ACL;
acls: ACL[];
emailVerificationRequired: boolean;
ttl: number;
maxTTL: number;
+99 -16
View File
@@ -1,4 +1,4 @@
// Type definitions for Maker.js 0.9.31
// Type definitions for Maker.js 0.9.33
// Project: https://github.com/Microsoft/maker.js
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -66,6 +66,17 @@ declare namespace MakerJs {
* @returns String of the flattened array.
*/
function createRouteKey(route: string[]): string;
/**
* Travel along a route inside of a model to extract a specific node in its tree.
*
* @param modelContext Model to travel within.
* @param routeKeyOrRoute String of a flattened route, or a string array of route segments.
* @returns Model or Path object within the modelContext tree.
*/
function travel(modelContext: IModel, routeKeyOrRoute: string | string[]): {
path: IPath | IModel;
offset: IPoint;
};
/**
* Clone an object.
*
@@ -139,6 +150,15 @@ declare namespace MakerJs {
*/
high: IPoint;
}
/**
* A measurement of extents, with a center point.
*/
interface IMeasureWithCenter extends IMeasure {
/**
* The center point of the rectangle containing the item being measured.
*/
center: IPoint;
}
/**
* A map of measurements.
*/
@@ -926,7 +946,7 @@ declare namespace MakerJs.path {
*
* @param pathToMove The path to move.
* @param origin The new origin for the path.
* @returns The original path (for chaining).
* @returns The original path (for cascading).
*/
function move(pathToMove: IPath, origin: IPoint): IPath;
/**
@@ -935,7 +955,7 @@ declare namespace MakerJs.path {
* @param pathToMove The path to move.
* @param delta The x & y adjustments as a point object.
* @param subtract Optional boolean to subtract instead of add.
* @returns The original path (for chaining).
* @returns The original path (for cascading).
*/
function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath;
/**
@@ -952,7 +972,7 @@ declare namespace MakerJs.path {
* @param pathToRotate The path to rotate.
* @param angleInDegrees The amount of rotation, in degrees.
* @param rotationOrigin The center point of rotation.
* @returns The original path (for chaining).
* @returns The original path (for cascading).
*/
function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin?: IPoint): IPath;
/**
@@ -960,7 +980,7 @@ declare namespace MakerJs.path {
*
* @param pathToScale The path to scale.
* @param scaleValue The amount of scaling.
* @returns The original path (for chaining).
* @returns The original path (for cascading).
*/
function scale(pathToScale: IPath, scaleValue: number): IPath;
/**
@@ -1215,11 +1235,11 @@ declare namespace MakerJs.model {
*/
function mirror(modelToMirror: IModel, mirrorX: boolean, mirrorY: boolean): IModel;
/**
* Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for chaining.
* Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for cascading.
*
* @param modelToMove The model to move.
* @param origin The new position of the model.
* @returns The original model (for chaining).
* @returns The original model (for cascading).
*/
function move(modelToMove: IModel, origin: IPoint): IModel;
/**
@@ -1227,7 +1247,7 @@ declare namespace MakerJs.model {
*
* @param modelToMove The model to move.
* @param delta The x & y adjustments as a point object.
* @returns The original model (for chaining).
* @returns The original model (for cascading).
*/
function moveRelative(modelToMove: IModel, delta: IPoint): IModel;
/**
@@ -1235,7 +1255,7 @@ declare namespace MakerJs.model {
*
* @param modelToPrefix The model to prefix.
* @param prefix The prefix to prepend on paths ids.
* @returns The original model (for chaining).
* @returns The original model (for cascading).
*/
function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel;
/**
@@ -1244,7 +1264,7 @@ declare namespace MakerJs.model {
* @param modelToRotate The model to rotate.
* @param angleInDegrees The amount of rotation, in degrees.
* @param rotationOrigin The center point of rotation.
* @returns The original model (for chaining).
* @returns The original model (for cascading).
*/
function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin?: IPoint): IModel;
/**
@@ -1253,7 +1273,7 @@ declare namespace MakerJs.model {
* @param modelToScale The model to scale.
* @param scaleValue The amount of scaling.
* @param scaleOrigin Optional boolean to scale the origin point. Typically false for the root model.
* @returns The original model (for chaining).
* @returns The original model (for cascading).
*/
function scale(modelToScale: IModel, scaleValue: number, scaleOrigin?: boolean): IModel;
/**
@@ -1261,7 +1281,7 @@ declare namespace MakerJs.model {
*
* @param modeltoConvert The model to convert.
* @param destUnitType The unit system.
* @returns The scaled model (for chaining).
* @returns The scaled model (for cascading).
*/
function convertUnits(modeltoConvert: IModel, destUnitType: string): IModel;
/**
@@ -1373,7 +1393,7 @@ declare namespace MakerJs.model {
*
* @param modelContext The originated model to search for similar paths.
* @param options Optional options object.
* @returns The simplified model (for chaining).
* @returns The simplified model (for cascading).
*/
function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel;
}
@@ -1478,7 +1498,7 @@ declare namespace MakerJs.measure {
* @param baseMeasure The measurement to increase.
* @param addMeasure The additional measurement.
* @param addOffset Optional offset point of the additional measurement.
* @returns The increased original measurement (for chaining).
* @returns The increased original measurement (for cascading).
*/
function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure;
/**
@@ -1583,7 +1603,7 @@ declare namespace MakerJs.measure {
* @param atlas Optional atlas to save measurements.
* @returns object with low and high points.
*/
function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure;
function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasureWithCenter;
/**
* A list of maps of measurements.
*
@@ -1612,6 +1632,22 @@ declare namespace MakerJs.measure {
constructor(modelContext: IModel);
measureModels(): void;
}
/**
* A hexagon which surrounds a model.
*/
interface IBoundingHex extends IModel {
/**
* Radius of the hexagon, which is also the length of a side.
*/
radius: number;
}
/**
* Measures the minimum bounding hexagon surrounding a model. The hexagon is oriented such that the right and left sides are vertical, and the top and bottom are pointed.
*
* @param modelToMeasure The model to measure.
* @returns IBoundingHex object which is a hexagon model, with an additional radius property.
*/
function boundingHexagon(modelToMeasure: IModel): IBoundingHex;
}
declare namespace MakerJs.exporter {
/**
@@ -1787,6 +1823,29 @@ declare namespace MakerJs.model {
function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void;
}
declare namespace MakerJs.chain {
/**
* Shift the links of an endless chain.
*
* @param chainContext Chain to cycle through. Must be endless.
* @param amount Optional number of links to shift. May be negative to cycle backwards.
* @returns The chainContext for cascading.
*/
function cycle(chainContext: IChain, amount?: number): IChain;
/**
* Reverse the links of a chain.
*
* @param chainContext Chain to reverse.
* @returns The chainContext for cascading.
*/
function reverse(chainContext: IChain): IChain;
/**
* Set the beginning of an endless chain to a known routeKey of a path.
*
* @param chainContext Chain to cycle through. Must be endless.
* @param routeKey RouteKey of the desired path to start the chain with.
* @returns The chainContext for cascading.
*/
function startAt(chainContext: IChain, routeKey: string): IChain;
/**
* Get points along a chain of paths.
*
@@ -1825,7 +1884,7 @@ declare namespace MakerJs.model {
*
* @param modelContext The model to search for dead ends.
* @param options Optional options object.
* @returns The input model (for chaining).
* @returns The input model (for cascading).
*/
function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: any, keep?: IWalkPathBooleanCallback): IModel;
}
@@ -2123,6 +2182,18 @@ declare namespace MakerJs.models {
* @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed).
*/
constructor(numericList: string);
/**
* Create a model by connecting points designated in a string. The model will be 'closed' - i.e. the last point will connect to the first point.
*
* Example:
* ```
* var c = new makerjs.models.ConnectTheDots(false, '-10 0 10 0 0 20'); // 3 coordinates to form a polyline
* ```
*
* @param isClosed Flag to specify if last point should connect to the first point.
* @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed).
*/
constructor(isClosed: boolean, numericList: string);
/**
* Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point.
*
@@ -2134,6 +2205,18 @@ declare namespace MakerJs.models {
* @param coords Array of coordinates.
*/
constructor(coords: number[]);
/**
* Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point.
*
* Example:
* ```
* var c = new makerjs.models.ConnectTheDots(false, [-10, 0, 10, 0, 0, 20]); // 3 coordinates to form a polyline
* ```
*
* @param isClosed Flag to specify if last point should connect to the first point.
* @param coords Array of coordinates.
*/
constructor(isClosed: boolean, coords: number[]);
/**
* Create a model by connecting points designated in an array of points. The model may be closed, or left open.
*
+10
View File
@@ -51,6 +51,7 @@ function test() {
makerjs.isPoint([]);
makerjs.pathType.Circle;
makerjs.round(44.44444, .01);
makerjs.travel(model, '');
makerjs.unitType.Millimeter;
new makerjs.Collector();
}
@@ -105,6 +106,7 @@ function test() {
}
function testMeasure() {
makerjs.measure.boundingHexagon(model).radius;
makerjs.measure.increase(mp, mm);
makerjs.measure.isPointEqual(p1, p2);
makerjs.measure.isPathEqual(paths.line, paths.circle, 4);
@@ -123,6 +125,7 @@ function test() {
makerjs.measure.pointDistance([0,0], [9,9]);
new makerjs.measure.Atlas(model);
mm.low[0];
mm.center;
mp.high[1];
var s = makerjs.measure.lineSlope(paths.line);
makerjs.measure.isPointOnSlope([], s);
@@ -172,6 +175,10 @@ function test() {
new makerjs.models.BoltCircle(7, 7, 7, 7),
new makerjs.models.BoltRectangle(2, 2, 2),
new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]),
new makerjs.models.ConnectTheDots([0, 0, 1, 1]),
new makerjs.models.ConnectTheDots(true, [0, 0, 1, 1]),
new makerjs.models.ConnectTheDots(true, '0, 0, 1, 1'),
new makerjs.models.ConnectTheDots('0, 0, 1, 1'),
new makerjs.models.Dogbone(1,1,1),
new makerjs.models.Dome(5, 7),
new makerjs.models.Ellipse(2,2),
@@ -255,7 +262,10 @@ function test() {
}
function testChain() {
makerjs.chain.cycle(chain, 7);
makerjs.chain.fillet(chain, 1);
makerjs.chain.reverse(chain);
makerjs.chain.startAt(chain, '');
makerjs.chain.toKeyPoints(chain);
makerjs.chain.toPoints(chain, 1);
}
+5 -1
View File
@@ -533,7 +533,7 @@ declare namespace __MaterialUI {
type cornersAndCenter = 'bottom-center' | 'bottom-left' | 'bottom-right' | 'top-center' | 'top-left' | 'top-right';
}
interface AutoCompleteProps<DataItem> {
interface AutoCompleteProps<DataItem> extends TextFieldProps {
anchorOrigin?: propTypes.origin;
animated?: boolean;
animation?: React.ComponentClass<Popover.PopoverAnimationProps>;
@@ -723,6 +723,7 @@ declare namespace __MaterialUI {
className?: string;
disableTouchRipple?: boolean;
disabled?: boolean;
hoveredStyle?: React.CSSProperties;
iconClassName?: string;
iconStyle?: React.CSSProperties;
onBlur?: React.FocusEventHandler<{}>;
@@ -1331,6 +1332,9 @@ declare namespace __MaterialUI {
className?: string;
maxHeight?: number;
menuStyle?: any;
listStyle?: React.CSSProperties;
menuItemStyle?: React.CSSProperties;
selectedMenuItemStyle?: React.CSSProperties;
openImmediately?: boolean;
}
export class SelectField extends React.Component<SelectFieldProps, {}> {
+2 -9
View File
@@ -1,15 +1,8 @@
# Meteor Type Definitions [DEPRECATED]
## Deprecated
These definitions for Meteor are now deprecated. They should still work for versions of Meteor up to 1.2.1.
The canonical TypeScript definitions for Meteor can now be found using the NPM [Typings definition manager](https://www.npmjs.com/package/typings). If you prefer to view the definitions directly, or contribute to them, they can be found here: <https://github.com/meteor-typings/meteor>.
# Meteor Type Definitions
## Description
These are the definitions for version 1.3 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/).
These are the definitions for version 1.4 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/).
## Upcoming Meteor `typescript` package
+2060 -832
View File
File diff suppressed because it is too large Load Diff
+323 -264
View File
@@ -6,11 +6,24 @@
/*********************************** Begin setup for tests ******************************/
import { Mongo } from "meteor/mongo";
import { Meteor } from "meteor/meteor";
import { check, Match } from "meteor/check";
import { Tracker } from "meteor/tracker";
import { Template } from "meteor/templating";
import { Blaze } from "meteor/blaze";
import { Session } from "meteor/session";
import { HTTP } from "meteor/http";
import { ReactiveVar } from "meteor/reactive-var";
import { Accounts } from "meteor/accounts-base";
import { BrowserPolicy } from "meteor/browser-policy-common";
import { DDPRateLimiter } from "meteor/ddp-rate-limiter";
var Rooms = new Mongo.Collection('rooms');
var Messages = new Mongo.Collection('messages');
interface MonkeyDAO {
_id: string;
name: string;
_id: string;
name: string;
}
var Monkeys = new Mongo.Collection<MonkeyDAO>('monkeys');
//var x = new Mongo.Collection<xDAO>('x');
@@ -23,72 +36,73 @@ var Monkeys = new Mongo.Collection<MonkeyDAO>('monkeys');
* Tests Meteor.isServer, Meteor.startup, Collection.insert(), Collection.find()
*/
if (Meteor.isServer) {
Meteor.startup(function () {
if (Rooms.find().count() === 0) {
Rooms.insert({name: "Initial room"});
}
});
Meteor.startup(function () {
if (Rooms.find().count() === 0) {
Rooms.insert({ name: "Initial room" });
}
});
}
/**
* From Publish and Subscribe, Meteor.publish section
**/
Meteor.publish("rooms", function () {
return Rooms.find({}, {fields: {secretInfo: 0}});
return Rooms.find({}, { fields: { secretInfo: 0 } });
});
Meteor.publish("adminSecretInfo", function () {
return Rooms.find({admin: this.userId}, {fields: {secretInfo: 1}});
return Rooms.find({ admin: this.userId }, { fields: { secretInfo: 1 } });
});
Meteor.publish("roomAndMessages", function (roomId: string) {
check(roomId, String);
return [
Rooms.find({_id: roomId}, {fields: {secretInfo: 0}}),
Messages.find({roomId: roomId})
];
check(roomId, String);
return [
Rooms.find({ _id: roomId }, { fields: { secretInfo: 0 } }),
Messages.find({ roomId: roomId })
];
});
/**
* Also from Publish and Subscribe, Meteor.publish section
*/
Meteor.publish("counts-by-room", function (roomId: string) {
var self = this;
check(roomId, String);
var count = 0;
var initializing = true;
var handle = Messages.find({roomId: roomId}).observeChanges({
added: function (id: any) {
count++;
// if (!initializing)
var self = this;
check(roomId, String);
var count = 0;
var initializing = true;
var handle = Messages.find({ roomId: roomId }).observeChanges({
added: function (id: any) {
count++;
// if (!initializing)
// this.changed("counts", roomId, {count: count});
},
removed: function (id: any) {
count--;
// Todo: Not sure how to define in typescript
// self.changed("counts", roomId, {count: count});
}
});
// Todo: Not sure how to define in typescript
// self.changed("counts", roomId, {count: count});
},
removed: function (id: any) {
count--;
// Todo: Not sure how to define in typescript
// self.changed("counts", roomId, {count: count});
}
});
initializing = false;
initializing = false;
// Todo: Not sure how to define in typescript
// self.added("counts", roomId, {count: count});
self.ready();
// Todo: Not sure how to define in typescript
// self.added("counts", roomId, {count: count});
self.ready();
self.onStop(function () {
handle.stop();
});
self.onStop(function () {
handle.stop();
});
});
var Counts = new Mongo.Collection("counts");
Tracker.autorun(function () {
Meteor.subscribe("counts-by-room", Session.get("roomId"));
Meteor.subscribe("counts-by-room", Session.get("roomId"));
});
// Checking status
let status: DDP.Status = 'connected';
console.log("Current room has " +
Counts.find(Session.get("roomId")).count +
" messages.");
@@ -102,47 +116,47 @@ Meteor.subscribe("allplayers");
* Also from Meteor.subscribe section
*/
Tracker.autorun(function () {
Meteor.subscribe("chat", {room: Session.get("current-room")});
Meteor.subscribe("privateMessages");
Meteor.subscribe("chat", { room: Session.get("current-room") });
Meteor.subscribe("privateMessages");
});
/**
* From Methods, Meteor.methods section
*/
Meteor.methods({
foo: function (arg1: string, arg2: number[]) {
check(arg1, String);
check(arg2, [Number]);
foo: function (arg1: string, arg2: number[]) {
check(arg1, String);
check(arg2, [Number]);
var you_want_to_throw_an_error = true;
if (you_want_to_throw_an_error)
throw new Meteor.Error("404", "Can't find my pants");
return "some return value";
},
var you_want_to_throw_an_error = true;
if (you_want_to_throw_an_error)
throw new Meteor.Error("404", "Can't find my pants");
return "some return value";
},
bar: function () {
// .. do other stuff ..
return "baz";
}
bar: function () {
// .. do other stuff ..
return "baz";
}
});
/**
* From Methods, Meteor.Error section
*/
function meteorErrorTestFunction1() {
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
}
function meteorErrorTestFunction2() {
throw new Meteor.Error(403,
"The user must be logged in to post a comment.");
throw new Meteor.Error(403,
"The user must be logged in to post a comment.");
}
Meteor.call("methodName", function (error: Meteor.Error) {
if (error.error === "logged-out") {
Session.set("errorMessage", "Please log in to post a comment.");
}
if (error.error === "logged-out") {
Session.set("errorMessage", "Please log in to post a comment.");
}
});
var error = new Meteor.Error("logged-out", "The user must be logged in to post a comment.");
console.log(error.error === "logged-out");
@@ -152,7 +166,7 @@ console.log(error.details !== "");
/**
* From Methods, Meteor.call section
*/
Meteor.call('foo', 1, 2, function (error:any, result:any) {} );
Meteor.call('foo', 1, 2, function (error: any, result: any) { });
var result = Meteor.call('foo', 1, 2);
/**
@@ -161,22 +175,22 @@ var result = Meteor.call('foo', 1, 2);
// DA: I added the "var" keyword in there
interface ChatroomsDAO {
_id?: string;
_id?: string;
}
interface MessagesDAO {
_id?: string;
_id?: string;
}
var Chatrooms = new Mongo.Collection<ChatroomsDAO>("chatrooms");
Messages = new Mongo.Collection<MessagesDAO>("messages");
var myMessages:any[] = Messages.find({userId: Session.get('myUserId')}).fetch();
var myMessages: any[] = Messages.find({ userId: Session.get('myUserId') }).fetch();
Messages.insert({text: "Hello, world!"});
Messages.insert({ text: "Hello, world!" });
Messages.update(myMessages[0]._id, {$set: {important: true}});
Messages.update(myMessages[0]._id, { $set: { important: true } });
var Posts = new Mongo.Collection("posts");
Posts.insert({title: "Hello world", body: "First post"});
Posts.insert({ title: "Hello world", body: "First post" });
// Couldn't find assert() in the meteor docs
//assert(Posts.find().count() === 1);
@@ -192,30 +206,30 @@ Posts.insert({title: "Hello world", body: "First post"});
**/
class Animal {
private sound:string;
constructor(doc:any) {
private sound: string;
constructor(doc: any) {
}
makeNoise() {
console.log(this.sound)
console.log(this.sound)
}
}
interface AnimalDAO {
_id?: string;
name: string;
sound: string;
makeNoise?: () => void;
_id?: string;
name: string;
sound: string;
makeNoise?: () => void;
}
// Define a Collection that uses Animal as its document
var Animals = new Mongo.Collection<AnimalDAO>("Animals", {
transform: function (doc:any): Animal { return new Animal(doc); }
transform: function (doc: any): Animal { return new Animal(doc); }
});
// Create an Animal and call its makeNoise method
Animals.insert({name: "raptor", sound: "roar"});
Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar"
Animals.insert({ name: "raptor", sound: "roar" });
Animals.findOne({ name: "raptor" }).makeNoise(); // prints "roar"
/**
* From Collections, Collection.insert section
@@ -224,9 +238,9 @@ Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar"
var Lists = new Mongo.Collection('Lists');
var Items = new Mongo.Collection('Lists');
var groceriesId = Lists.insert({name: "Groceries"});
Items.insert({list: groceriesId, name: "Watercress"});
Items.insert({list: groceriesId, name: "Persimmons"});
var groceriesId = Lists.insert({ name: "Groceries" });
Items.insert({ list: groceriesId, name: "Watercress" });
Items.insert({ list: groceriesId, name: "Persimmons" });
/**
* From Collections, collection.update section
@@ -234,39 +248,39 @@ Items.insert({list: groceriesId, name: "Persimmons"});
var Players = new Mongo.Collection('Players');
Template['adminDashboard'].events({
'click .givePoints': function () {
Players.update(Session.get("currentPlayer"), {$inc: {score: 5}});
}
'click .givePoints': function () {
Players.update(Session.get("currentPlayer"), { $inc: { score: 5 } });
}
});
/**
* Also from Collections, collection.update section
*/
Meteor.methods({
declareWinners: function () {
Players.update({score: {$gt: 10}},
{$addToSet: {badges: "Winner"}},
{multi: true});
}
declareWinners: function () {
Players.update({ score: { $gt: 10 } },
{ $addToSet: { badges: "Winner" } },
{ multi: true });
}
});
/**
* From Collections, collection.remove section
*/
Template['chat'].events({
'click .remove': function () {
Messages.remove(this._id);
}
'click .remove': function () {
Messages.remove(this._id);
}
});
// DA: I added this next line
var Logs = new Mongo.Collection('logs');
Meteor.startup(function () {
if (Meteor.isServer) {
Logs.remove({});
Players.remove({karma: {$lt: -2}});
}
if (Meteor.isServer) {
Logs.remove({});
Players.remove({ karma: { $lt: -2 } });
}
});
/***
@@ -274,50 +288,50 @@ Meteor.startup(function () {
*/
interface iPost {
_id: string;
owner: string;
userId: string;
locked: boolean;
_id: string;
owner: string;
userId: string;
locked: boolean;
}
Posts = new Mongo.Collection<iPost>("posts");
Posts.allow({
insert: function (userId:string, doc: iPost) {
// the user must be logged in, and the document must be owned by the user
return (userId && doc.owner === userId);
},
update: function (userId:string, doc: iPost, fields:string[], modifier:any) {
// can only change your own documents
return doc.owner === userId;
},
remove: function (userId:string, doc: iPost) {
// can only remove your own documents
return doc.owner === userId;
},
fetch: ['owner']
insert: function (userId: string, doc: iPost) {
// the user must be logged in, and the document must be owned by the user
return (userId && doc.owner === userId);
},
update: function (userId: string, doc: iPost, fields: string[], modifier: any) {
// can only change your own documents
return doc.owner === userId;
},
remove: function (userId: string, doc: iPost) {
// can only remove your own documents
return doc.owner === userId;
},
fetch: ['owner']
});
Posts.deny({
update: function (userId:string, doc: iPost, fields:string[], modifier:any) {
// can't change owners
return doc.userId !== userId;
},
remove: function (userId:string, doc: iPost) {
// can't remove locked documents
return doc.locked;
},
fetch: ['locked'] // no need to fetch 'owner'
update: function (userId: string, doc: iPost, fields: string[], modifier: any) {
// can't change owners
return doc.userId !== userId;
},
remove: function (userId: string, doc: iPost) {
// can't remove locked documents
return doc.locked;
},
fetch: ['locked'] // no need to fetch 'owner'
});
/**
* From Collections, cursor.forEach section
*/
var topPosts = Posts.find({}, {sort: {score: -1}, limit: 5});
var topPosts = Posts.find({}, { sort: { score: -1 }, limit: 5 });
var count = 0;
topPosts.forEach(function (post:{title:string}) {
console.log("Title of post " + count + ": " + post.title);
count += 1;
topPosts.forEach(function (post: { title: string }) {
console.log("Title of post " + count + ": " + post.title);
count += 1;
});
/**
@@ -327,26 +341,28 @@ topPosts.forEach(function (post:{title:string}) {
var Users = new Mongo.Collection('users');
var count1 = 0;
var query = Users.find({admin: true, onlineNow: true});
var query = Users.find({ admin: true, onlineNow: true });
var handle = query.observeChanges({
added: function (id:string, user:{name:string}) {
count1++;
console.log(user.name + " brings the total to " + count1 + " admins.");
},
removed: function () {
count1--;
console.log("Lost one. We're now down to " + count1 + " admins.");
}
added: function (id: string, user: { name: string }) {
count1++;
console.log(user.name + " brings the total to " + count1 + " admins.");
},
removed: function () {
count1--;
console.log("Lost one. We're now down to " + count1 + " admins.");
}
});
let cursor: Mongo.Cursor<Object>;
// After five seconds, stop keeping the count.
setTimeout(function () {handle.stop();}, 5000);
setTimeout(function () { handle.stop(); }, 5000);
/**
* From Sessions, Session.set section
*/
Tracker.autorun(function () {
Meteor.subscribe("chat-history", {room: Session.get("currentRoomId")});
Meteor.subscribe("chat-history", { room: Session.get("currentRoomId") });
});
// Causes the function passed to Tracker.autorun to be re-run, so
@@ -375,59 +391,59 @@ Session.equals("key", value);
* From Accounts, Meteor.users section
*/
Meteor.publish("userData", function () {
return Meteor.users.find({_id: this.userId},
{fields: {'other': 1, 'things': 1}});
return Meteor.users.find({ _id: this.userId },
{ fields: { 'other': 1, 'things': 1 } });
});
Meteor.users.deny({update: function () { return true; }});
Meteor.users.deny({ update: function () { return true; } });
/**
* From Accounts, Meteor.loginWithExternalService section
*/
Meteor.loginWithGithub({
requestPermissions: ['user', 'public_repo']
requestPermissions: ['user', 'public_repo']
}, function (err: Meteor.Error) {
if (err)
Session.set('errorMessage', err.reason || 'Unknown error');
if (err)
Session.set('errorMessage', err.reason || 'Unknown error');
});
/**
* From Accounts, Accounts.ui.config section
*/
Accounts.ui.config({
requestPermissions: {
facebook: ['user_likes'],
github: ['user', 'repo']
},
requestOfflineToken: {
google: true
},
passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL'
requestPermissions: {
facebook: ['user_likes'],
github: ['user', 'repo']
},
requestOfflineToken: {
google: true
},
passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL'
});
/**
* From Accounts, Accounts.validateNewUser section
*/
Accounts.validateNewUser(function (user:{username:string}) {
if (user.username && user.username.length >= 3)
return true;
throw new Meteor.Error("403", "Username must have at least 3 characters");
Accounts.validateNewUser(function (user: { username: string }) {
if (user.username && user.username.length >= 3)
return true;
throw new Meteor.Error("403", "Username must have at least 3 characters");
});
// Validate username, without a specific error message.
Accounts.validateNewUser(function (user:{username:string}) {
return user.username !== "root";
Accounts.validateNewUser(function (user: { username: string }) {
return user.username !== "root";
});
/**
* From Accounts, Accounts.onCreateUser section
*/
Accounts.onCreateUser(function(options:{profile:any}, user:{profile:any, dexterity:number}) {
var d6 = function () { return Math.floor(Math.random() * 6) + 1; };
user.dexterity = d6() + d6() + d6();
// We still want the default hook's 'profile' behavior.
if (options.profile)
user.profile = options.profile;
return user;
Accounts.onCreateUser(function (options: { profile: any }, user: { profile: any, dexterity: number }) {
var d6 = function () { return Math.floor(Math.random() * 6) + 1; };
user.dexterity = d6() + d6() + d6();
// We still want the default hook's 'profile' behavior.
if (options.profile)
user.profile = options.profile;
return user;
});
/**
@@ -435,26 +451,27 @@ Accounts.onCreateUser(function(options:{profile:any}, user:{profile:any, dexteri
*/
Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <accounts@example.com>";
Accounts.emailTemplates.enrollAccount.subject = function (user:{ profile:{name: string} }) {
return "Welcome to Awesome Town, " + user.profile.name;
Accounts.emailTemplates.enrollAccount.subject = function (user: { profile: { name: string } }) {
return "Welcome to Awesome Town, " + user.profile.name;
};
Accounts.emailTemplates.enrollAccount.text = function (user:any, url:string) {
return "You have been selected to participate in building a better future!"
+ " To activate your account, simply click the link below:\n\n"
+ url;
Accounts.emailTemplates.enrollAccount.text = function (user: any, url: string) {
return "You have been selected to participate in building a better future!"
+ " To activate your account, simply click the link below:\n\n"
+ url;
};
/**
* From Templates, Template.myTemplate.helpers section
*/
Template['adminDashboard'].helpers({
foo: function () {
return Session.get("foo");
}
foo: function () {
return Session.get("foo");
}
});
Template['newTemplate'].helpers({
helperName: function () {
}
helperName: function () {
}
});
Template['newTemplate'].created = function () {
@@ -470,12 +487,12 @@ Template['newTemplate'].destroyed = function () {
};
Template['newTemplate'].events({
'click .something': function (event: Meteor.Event, template: Blaze.TemplateInstance) {
}
'click .something': function (event: Meteor.Event, template: Blaze.TemplateInstance) {
}
});
Template.registerHelper('testHelper', function() {
return 'tester';
Template.registerHelper('testHelper', function () {
return 'tester';
});
var instance = Template.instance();
@@ -488,23 +505,25 @@ var body = Template.body;
*/
var Chats = new Mongo.Collection('chats');
Meteor.publish("chats-in-room", function (roomId:string) {
// Make sure roomId is a string, not an arbitrary mongo selector object.
check(roomId, String);
return Chats.find({room: roomId});
Meteor.publish("chats-in-room", function (roomId: string) {
// Make sure roomId is a string, not an arbitrary mongo selector object.
check(roomId, String);
return Chats.find({ room: roomId });
});
Meteor.methods({addChat: function (roomId:string, message:{text:string, timestamp:Date, tags:string}) {
check(roomId, String);
check(message, {
text: String,
timestamp: Date,
// Optional, but if present must be an array of strings.
tags: Match.Optional('Test String')
});
Meteor.methods({
addChat: function (roomId: string, message: { text: string, timestamp: Date, tags: string }) {
check(roomId, String);
check(message, {
text: String,
timestamp: Date,
// Optional, but if present must be an array of strings.
tags: Match.Optional('Test String')
});
// ... do something with the message ...
}});
// ... do something with the message ...
}
});
/**
* From Match patterns section
@@ -521,27 +540,27 @@ check(undefined, Match.Optional('test')); // OK
* From Deps, Tracker.autorun section
*/
Tracker.autorun(function () {
var oldest = Monkeys.findOne('age = 20');
var oldest = Monkeys.findOne('age = 20');
if (oldest)
Session.set("oldest", oldest.name);
if (oldest)
Session.set("oldest", oldest.name);
});
Tracker.autorun(function (c) {
if (! Session.equals("shouldAlert", true))
return;
if (!Session.equals("shouldAlert", true))
return;
c.stop();
alert("Oh no!");
c.stop();
alert("Oh no!");
});
/**
* From Deps, Deps.Computation
*/
if (Tracker.active) {
Tracker.onInvalidate(function () {
console.log('invalidated');
});
Tracker.onInvalidate(function () {
console.log('invalidated');
});
}
/**
@@ -551,50 +570,52 @@ var weather = "sunny";
var weatherDep = new Tracker.Dependency;
var getWeather = function () {
weatherDep.depend();
return weather;
weatherDep.depend();
return weather;
};
var setWeather = function (w:string) {
weather = w;
// (could add logic here to only call changed()
// if the new value is different from the old)
weatherDep.changed();
var setWeather = function (w: string) {
weather = w;
// (could add logic here to only call changed()
// if the new value is different from the old)
weatherDep.changed();
};
/**
* From HTTP, HTTP.call section
*/
Meteor.methods({checkTwitter: function (userId:string) {
check(userId, String);
this.unblock();
var result = HTTP.call("GET", "http://api.twitter.com/xyz",
{params: {user: userId}});
if (result.statusCode === 200)
return true
return false;
}});
Meteor.methods({
checkTwitter: function (userId: string) {
check(userId, String);
this.unblock();
var result = HTTP.call("GET", "http://api.twitter.com/xyz",
{ params: { user: userId } });
if (result.statusCode === 200)
return true
return false;
}
});
HTTP.call("POST", "http://api.twitter.com/xyz",
{data: {some: "json", stuff: 1}},
function (error: Meteor.Error, result:any) {
if (result.statusCode === 200) {
Session.set("twizzled", true);
}
{ data: { some: "json", stuff: 1 } },
function (error: Meteor.Error, result: any) {
if (result.statusCode === 200) {
Session.set("twizzled", true);
}
});
/**
* From Email, Email.send section
*/
Meteor.methods({
sendEmail: function (to:string, from:string, subject:string, text:string) {
check([to, from, subject, text], [String]);
sendEmail: function (to: string, from: string, subject: string, text: string) {
check([to, from, subject, text], [String]);
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
}
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
}
});
// In your client code: asynchronously send an email
@@ -603,74 +624,112 @@ Meteor.call('sendEmail',
'Hello from Meteor!',
'This is a test of Email.send.');
var testTemplate = new Blaze.Template();
var testView = new Blaze.View();
var testTemplate = new Blaze.Template('foo');
var testView = new Blaze.View('foo');
Blaze.Template.instance();
declare var el: HTMLElement;
Blaze.render(testTemplate, el);
Blaze.renderWithData(testTemplate, {testData: 123}, el);
Blaze.renderWithData(testTemplate, { testData: 123 }, el);
Blaze.remove(testView);
Blaze.getData(el);
Blaze.getData(testView);
Blaze.toHTML(testTemplate);
Blaze.toHTML(testView);
Blaze.toHTMLWithData(testTemplate, {test: 1});
Blaze.toHTMLWithData(testTemplate, function() {});
Blaze.toHTMLWithData(testView, {test: 1});
Blaze.toHTMLWithData(testView, function() {});
Blaze.toHTMLWithData(testTemplate, { test: 1 });
Blaze.toHTMLWithData(testTemplate, function () { });
Blaze.toHTMLWithData(testView, { test: 1 });
Blaze.toHTMLWithData(testView, function () { });
var reactiveVar1 = new ReactiveVar<string>('test value');
var reactiveVar2 = new ReactiveVar<string>('test value', function(oldVal:any) { return true; });
var reactiveVar2 = new ReactiveVar<string>('test value', function (oldVal: any) { return true; });
var varValue: string = reactiveVar1.get();
reactiveVar1.set('new value');
// Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8233
var isConfigured: boolean = Accounts.loginServicesConfigured();
Accounts.onPageLoadLogin(function() {
// do something
Accounts.onPageLoadLogin(function () {
// do something
});
// Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065
var loginOpts: Meteor.LoginWithExternalServiceOptions = {
requestPermissions: ["a", "b"],
requestOfflineToken: true,
loginUrlParameters: {asdf: 1, qwer: "1234"},
loginHint: "Help me",
loginStyle: "Bold and powerful",
redirectUrl: "popup",
profile: "asdfasdf",
email: "asdf@ASDf.com"
var loginOpts = <Meteor.LoginWithExternalServiceOptions>{
requestPermissions: ["a", "b"],
requestOfflineToken: true,
loginUrlParameters: { asdf: 1, qwer: "1234" },
loginHint: "Help me",
loginStyle: "Bold and powerful",
redirectUrl: "popup",
profile: "asdfasdf"
};
Meteor.loginWithMeteorDeveloperAccount(loginOpts, function(error: Meteor.Error) {});
Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { });
Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <accounts@example.com>";
Accounts.emailTemplates.headers = { asdf: 'asdf', qwer: 'qwer' };
Accounts.emailTemplates.enrollAccount.subject = function (user: Meteor.User) {
return "Welcome to Awesome Town, " + user.profile.name;
return "Welcome to Awesome Town, " + user.profile.name;
};
Accounts.emailTemplates.enrollAccount.html = function (user: Meteor.User, url: string) {
return "<h1>Some html here</h1>";
return "<h1>Some html here</h1>";
};
Accounts.emailTemplates.enrollAccount.from = function() {
return "asdf@asdf.com";
Accounts.emailTemplates.enrollAccount.from = function () {
return "asdf@asdf.com";
};
Accounts.emailTemplates.enrollAccount.text = function (user: Meteor.User, url: string) {
return "You have been selected to participate in building a better future!"
return "You have been selected to participate in building a better future!"
+ " To activate your account, simply click the link below:\n\n"
+ url;
};
var handle = Accounts.validateLoginAttempt(function(attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) {
var type: string = attemptInfoObject.type;
var allowed: boolean = attemptInfoObject.allowed;
var error: Meteor.Error = attemptInfoObject.error;
var user: Meteor.User = attemptInfoObject.user;
var connection: Meteor.Connection = attemptInfoObject.connection;
var methodName: string = attemptInfoObject.methodName;
var methodArguments: any[] = attemptInfoObject.methodArguments;
return true;
var handle = Accounts.validateLoginAttempt(function (attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) {
var type: string = attemptInfoObject.type;
var allowed: boolean = attemptInfoObject.allowed;
var error: Meteor.Error = attemptInfoObject.error;
var user: Meteor.User = attemptInfoObject.user;
var connection: Meteor.Connection = attemptInfoObject.connection;
var methodName: string = attemptInfoObject.methodName;
var methodArguments: any[] = attemptInfoObject.methodArguments;
return true;
});
handle.stop();
// Covers https://github.com/meteor-typings/meteor/issues/8
const publicSetting = Meteor.settings.public['somePublicSetting'];
const deeperPublicSetting = Meteor.settings.public['somePublicSetting']['deeperSetting'];
const privateSetting = Meteor.settings['somePrivateSetting'];
const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetting'];
// Covers https://github.com/meteor-typings/meteor/issues/9
const username = (<HTMLInputElement>Template.instance().find('#username')).value;
// Covers https://github.com/meteor-typings/meteor/issues/3
BrowserPolicy.framing.disallow();
BrowserPolicy.content.allowEval();
// Covers https://github.com/meteor-typings/meteor/issues/18
if (Meteor.isDevelopment) {
Rooms._dropIndex({ field: 1 });
}
// Covers https://github.com/meteor-typings/meteor/issues/20
Rooms.find().count(true);
// Covers https://github.com/meteor-typings/meteor/issues/21
if (Meteor.isTest) {
// do something
}
DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000);
DDPRateLimiter.addRule((userId: string) => userId == 'foo', 5, 1000);
Template.instance().autorun(() => { }).stop();
+5
View File
@@ -385,6 +385,9 @@ declare module "mongoose" {
* If connecting to multiple mongos servers, set the mongos option to true.
*/
mongos?: boolean;
/** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */
promiseLibrary?: any;
}
interface ConnectionOptions extends
@@ -720,6 +723,8 @@ declare module "mongoose" {
validateBeforeSave?: boolean;
/** defaults to "__v" */
versionKey?: string|boolean;
/** defaults to false */
retainKeyOrder?: boolean;
/**
* skipVersioning allows excluding paths from
* versioning (the internal revision will not be
+38
View File
@@ -1,6 +1,7 @@
// Type definitions for node-forge 0.6.42
// Project: https://github.com/digitalbazaar/forge
// Definitions by: Seth Westphal <https://github.com/westy92>
// Kay Schecker <https://github.com/flynetworks>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "node-forge" {
@@ -23,6 +24,7 @@ declare module "node-forge" {
function privateKeyToPem(key: Key, maxline?: number): PEM;
function publicKeyToPem(key: Key, maxline?: number): PEM;
function certificateToPem(cert: Certificate, maxline?: number): PEM;
interface oids {
[key: string]: string;
@@ -234,4 +236,40 @@ declare module "node-forge" {
}
}
}
namespace pkcs12 {
interface BagsFilter {
localKeyId?: string;
localKeyIdHex?: string;
friendlyName?: string;
bagType?: string;
}
interface Bag {
type: string;
attributes: any;
key?: pki.Key;
cert?: pki.Certificate;
asn1: asn1.Asn1
}
interface Pkcs12Pfx {
version: string;
safeContents: [{
encrypted: boolean;
safeBags: Bag[];
}];
getBags: (filter: BagsFilter) => {
[key: string]: Bag[];
localKeyId?: Bag[];
friendlyName?: Bag[];
};
getBagsByFriendlyName: (fiendlyName: string, bagType: string) => Bag[]
getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[]
}
function pkcs12FromAsn1(obj:any, strict?: boolean, password?: string) : Pkcs12Pfx;
function pkcs12FromAsn1(obj:any, password?: string) : Pkcs12Pfx;
}
}
+12
View File
@@ -305,6 +305,18 @@
"typingsPackageName": "gaea-model",
"sourceRepoURL": "https://github.com/ascoders/gaea-model",
"asOfVersion": "0.0.0"
},
{
"libraryName": "Raven JS",
"typingsPackageName": "raven-js",
"sourceRepoURL": "https://github.com/getsentry/raven-js",
"asOfVersion": "3.10.0"
},
{
"libraryName": "antd",
"typingsPackageName": "antd",
"sourceRepoURL": "https://github.com/ant-design/ant-design",
"asOfVersion": "1.0.0"
}
]
}
+1597 -413
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
// Type definitions for parse-unit 1.0
// Project: https://github.com/mattdesl/parse-unit
// Definitions by: Jack Works <https://github.com/Jack-Works>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function parse(value: string): [number, string];
export = parse;
+4
View File
@@ -0,0 +1,4 @@
import parse = require('parse-unit')
let [number, length] = parse('10px')
number === 50
length === 'px'
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"parse-unit-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+22 -3
View File
@@ -31,12 +31,31 @@ interface IStrategyOption {
scopeSeparator?: string;
enableProof?: boolean;
profileFields?: string[];
passReqToCallback?: boolean;
}
interface IStrategyOptionWithRequest {
clientID: string;
clientSecret: string;
callbackURL: string;
scopeSeparator?: string;
enableProof?: boolean;
profileFields?: string[];
passReqToCallback: boolean;
}
interface VerifyFunction {
(accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void;
}
interface VerifyFunctionWithRequest {
(req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void;
}
declare class Strategy implements passport.Strategy {
constructor(options: IStrategyOption,
verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void);
constructor(options: IStrategyOptionWithRequest, verify: VerifyFunctionWithRequest);
constructor(options: IStrategyOption, verify: VerifyFunction);
name: string;
authenticate: (req: express.Request, options?: Object) => void;
}

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