From 0a29ae08a9b78bd701e323a41ca99cbed5937c95 Mon Sep 17 00:00:00 2001 From: Yousef Date: Mon, 1 May 2017 21:29:24 +0200 Subject: [PATCH 001/109] fix null in sequelize find (#16219) --- types/sequelize/v3/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index e823a926e2..d24cad3cdd 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -3724,15 +3724,15 @@ declare namespace sequelize { * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will * always be called with a single instance. */ - findById(identifier?: number | string, options?: FindOptions): Promise; - findByPrimary(identifier?: number | string, options?: FindOptions): Promise; + findById(identifier?: number | string, options?: FindOptions): Promise; + findByPrimary(identifier?: number | string, options?: FindOptions): Promise; /** * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single * instance. */ - findOne(options?: FindOptions): Promise; - find(options?: FindOptions): Promise; + findOne(options?: FindOptions): Promise; + find(options?: FindOptions): Promise; /** * Run an aggregation method on the specified field From 0cefb71e500b0cda3dc04c07e3d2c8cb280b02de Mon Sep 17 00:00:00 2001 From: Mike Cook Date: Mon, 1 May 2017 20:34:37 +0100 Subject: [PATCH 002/109] Add type definitions for koa-websocket (#16221) --- types/koa-websocket/index.d.ts | 36 ++++++++++++++++++++++ types/koa-websocket/koa-websocket-tests.ts | 14 +++++++++ types/koa-websocket/tsconfig.json | 22 +++++++++++++ types/koa-websocket/tslint.json | 1 + 4 files changed, 73 insertions(+) create mode 100644 types/koa-websocket/index.d.ts create mode 100644 types/koa-websocket/koa-websocket-tests.ts create mode 100644 types/koa-websocket/tsconfig.json create mode 100644 types/koa-websocket/tslint.json diff --git a/types/koa-websocket/index.d.ts b/types/koa-websocket/index.d.ts new file mode 100644 index 0000000000..115dbb43f6 --- /dev/null +++ b/types/koa-websocket/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for koa-websocket 2.1 +// Project: https://github.com/kudos/koa-websocket +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Koa from 'koa'; +import * as ws from 'ws'; +import * as http from 'http'; +import * as https from 'https'; + +type KoaWebsocketConnectionHandler = (socket: ws) => void; +type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise) => any; +interface KoaWebsocketMiddlewareContext extends Koa.Context { + websocket: ws; + path: string; +} + +declare class KoaWebsocketServer { + app: Koa; + middleware: Koa.Middleware[]; + + constructor(app: Koa); + listen(server: http.Server | https.Server): ws.Server; + onConnection(handler: KoaWebsocketConnectionHandler): void; + use(middleware: KoaWebsocketMiddleware): this; +} + +interface KoaWebsocketApp extends Koa { + ws: KoaWebsocketServer; +} + +type KoaWebsockets = (app: Koa) => KoaWebsocketApp; + +declare const websockets: KoaWebsockets; +export = websockets; diff --git a/types/koa-websocket/koa-websocket-tests.ts b/types/koa-websocket/koa-websocket-tests.ts new file mode 100644 index 0000000000..66bd4bf4d2 --- /dev/null +++ b/types/koa-websocket/koa-websocket-tests.ts @@ -0,0 +1,14 @@ +import * as Koa from 'koa'; +import * as websocket from 'koa-websocket'; + +const app = websocket(new Koa()); + +app.ws.use(async function(context, next) { + this.websocket.on('message', (message) => { + console.log(message); + }); + this.websocket.send('Hello world'); + await next(); +}); + +app.listen(3000); diff --git a/types/koa-websocket/tsconfig.json b/types/koa-websocket/tsconfig.json new file mode 100644 index 0000000000..effcb59356 --- /dev/null +++ b/types/koa-websocket/tsconfig.json @@ -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", + "koa-websocket-tests.ts" + ] +} diff --git a/types/koa-websocket/tslint.json b/types/koa-websocket/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-websocket/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 7547cd219a1ecadf923d72d6ca995e827ecfa320 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Tue, 2 May 2017 03:35:36 +0800 Subject: [PATCH 003/109] Add React navigation (#16223) * Add react-navigation Types * Add actions Functions : https://reactnavigation.org/docs/navigators/navigation-actions Note: the `type` option has to be optional because if not, we have to add it when we use one of actions. * Support of Screen Navigation Options For Stack, Tab and Drawer * Add Generic for NavigationNavigatorProps params * NavigationParams: any type of param * Add Tab and Drawer Navigators * Use of ViewStyle and TextStyle * Improve tsconfig.json && tslint.json * Add Test * fix test * fix lint --- types/react-navigation/index.d.ts | 603 ++++++++++++++++++ .../react-navigation-tests.tsx | 30 + types/react-navigation/tsconfig.json | 23 + types/react-navigation/tslint.json | 22 + 4 files changed, 678 insertions(+) create mode 100644 types/react-navigation/index.d.ts create mode 100644 types/react-navigation/react-navigation-tests.tsx create mode 100644 types/react-navigation/tsconfig.json create mode 100644 types/react-navigation/tslint.json diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts new file mode 100644 index 0000000000..6b263642ff --- /dev/null +++ b/types/react-navigation/index.d.ts @@ -0,0 +1,603 @@ +// Type definitions for react-navigation 1.0 +// Project: https://github.com/react-community/react-navigation +// Definitions by: Huhuanming +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from 'react' +import { + Animated, + ViewStyle, + TextStyle +} from 'react-native' + +export type HeaderMode = 'float' | 'screen' | 'none' + +export function addNavigationHelpers(params: any): any + +type SubViewProps = NavigationSceneRendererProps & { + onNavigateBack?: () => void, +} + +type SubViewRenderer = (subViewProps: SubViewProps) => React.ReactElement | undefined + +export type HeaderProps = NavigationSceneRendererProps & { + mode: HeaderMode, + onNavigateBack?: () => void, + renderLeftComponent: SubViewRenderer, + renderRightComponent: SubViewRenderer, + renderTitleComponent: SubViewRenderer, + tintColor?: string, + router: NavigationRouter, +} + +/** + * NavigationState is a tree of routes for a single navigator, where each child + * route may either be a NavigationScreenRoute or a NavigationRouterRoute. + * NavigationScreenRoute represents a leaf screen, while the + * NavigationRouterRoute represents the state of a child navigator. + * + * NOTE: NavigationState is a state tree local to a single navigator and + * its child navigators (via the routes field). + * If we're in navigator nested deep inside the app, the state will only be the + * state for that navigator. + * The state for the root navigator of our app represents the whole navigation + * state for the whole app. + */ +export interface NavigationState { + /** + * Index refers to the active child route in the routes array. + */ + index: number, + routes: any[], +} + +export interface NavigationRoute

{ + /** + * React's key used by some navigators. No need to specify these manually, + * they will be defined by the router. + */ + key: string, + /** + * For example 'Home'. + * This is used as a key in a route config when creating a navigator. + */ + routeName: string, + /** + * Path is an advanced feature used for deep linking and on the web. + */ + path?: string, + /** + * Params passed to this route when navigating to it, + * e.g. `{ car_id: 123 }` in a route that displays a car. + */ + params: P, +} + +export interface NavigationRouter { + /** + * The reducer that outputs the new navigation state for a given action, with + * an optional previous state. When the action is considered handled but the + * state is unchanged, the output state is null. + */ + getStateForAction: ( + action: NavigationAction, + lastState?: NavigationState, + ) => NavigationState | undefined, + + /** + * Maps a URI-like string to an action. This can be mapped to a state + * using `getStateForAction`. + */ + getActionForPathAndParams: (path: string, params?: NavigationParams) => NavigationAction | undefined, + + getPathAndParamsForState: (state: NavigationState) => { path: string, params?: NavigationParams }, + + getComponentForRouteName: (routeName: string) => NavigationComponent, + + getComponentForState: (state: NavigationState) => NavigationComponent, + + /** + * Gets the screen config for a given navigation screen prop. + * + * For example, we could get the config for a 'Foo' screen when the + * `navigation.state` is: + * + * {routeName: 'Foo', key: '123'} + */ + getScreenConfig: ( + navigation: NavigationScreenProp, + optionName: string, + ) => any, // todo, fix this any type to become a key of NavigationScreenConfig +} + +type NavigationFunc = (navigation: NavigationScreenProp, config: E) => E + +export type NavigationScreenOption = T | NavigationFunc + +export interface HeaderConfig { + /** + * Title string used by the navigation bar, or a custom component + */ + title?: string | React.ReactElement; + + /** + * Whether the navigation bar is visible. + */ + visible?: boolean; + + /** + * Renders a custom right component + */ + right?: React.ReactElement, + + /** + * Renders a custom left component + */ + left?: React.ReactElement + + /** + * Style passed into navigation bar container + */ + style?: ViewStyle, + + /** + * Style passed into navigation bar title + */ + titleStyle?: TextStyle, + + // // Style of title text + // titleTextStyle?: $NavigationThunk, + // // Tint color of navigation bar contents + // tintColor?: $NavigationThunk, + // // Navigation bar height + // height?: $NavigationThunk, + // // Navigation bar translucentcy + // translucent?: $NavigationThunk, + // // Renders a custom left component + // renderLeft?: React.Element<*> | + // (navigation: NavigationProp<*>, canGoBack: boolean) => React.Element<*>, + // // Renders a custom navigation bar background + // renderBackground?: $NavigationThunk>, +} + +export interface TabBarConfig { + /** + * Icon used by the tab bar. + */ + icon?: (options: { tintColor: string, focused: boolean }) => React.ReactElement | undefined; + /** + * Label text used by the tab bar. + */ + label?: string | React.ReactElement; +} + +export interface DrawerConfig { + /** + * Icon used by the drawer. + */ + icon?: (options: { tintColor: string, focused: boolean }) => React.ReactElement | undefined; + /** + * Label text used by the drawer. + */ + label?: string; +} + +export interface CardStackConfig { + /** + * Whether you can use gestures to dismiss this screen. + * Defaults to true on iOS, false on Android. + */ + gesturesEnabled?: boolean; +} + +export interface NavigationScreenOptions { + /** + * Title is rendered by certain navigators, e.g. the tab navigator, + * or on web as the title of the browser tab. + */ + title?: NavigationScreenOption; + /** + * Options passed to the navigation bar for this screen. + */ + header?: NavigationScreenOption; + /** + * Options passed to the tab bar for this screen. + */ + tabBar?: NavigationScreenOption; + /** + * Options passed to the drawer for this screen. + */ + drawer?: NavigationScreenOption; + /** + * Options passed to the card stack for this screen. + */ + cardStack?: NavigationScreenOption; +} + +export interface NavigationScreenConfig { + title?: string, + header?: HeaderConfig, + tabBar?: TabBarConfig, + drawer?: DrawerConfig; +} + +export type NavigationComponent = NavigationScreenComponent | NavigationNavigator + +export type NavigationScreenComponent = React.ComponentClass & { + navigationOptions?: NavigationScreenOptions, +} + +export type NavigationNavigator = React.ComponentClass & { + router?: NavigationRouter, + navigationOptions?: NavigationScreenOptions, +} + +export interface NavigationParams { + [key: string]: any, +} + +export interface NavigationNavigateAction { + type?: 'Navigation/NAVIGATE', + routeName: string, + params?: NavigationParams, + + // The action to run inside the sub-router + action?: NavigationNavigateAction, +} + +export interface NavigationBackAction { + type?: 'Navigation/BACK', + key?: string, +} + +export interface NavigationSetParamsAction { + type?: 'Navigation/SET_PARAMS', + + // The key of the route where the params should be set + key: string, + + // The new params to merge into the existing route params + params?: NavigationParams, +} + +export interface NavigationInitAction { + type?: 'Navigation/INIT', + params?: NavigationParams, +} + +export interface NavigationResetAction { + type?: 'Navigation/RESET', + index: number, + actions: NavigationNavigateAction[], +} + +export interface NavigationUriAction { + type?: 'Navigation/URI', + uri: string, +} + +export interface NavigationContainerOptions { + // This is used to extract the path from the URI passed to the app for a deep link + URIPrefix?: string, +} + +export interface NavigationContainerConfig { + containerOptions?: NavigationContainerOptions, +} + +export interface NavigationStackViewConfig { + mode?: 'card' | 'modal', + headerMode?: HeaderMode, + headerComponent?: React.ComponentClass, + cardStyle?: ViewStyle, + onTransitionStart?: () => void, + onTransitionEnd?: () => void, +} + +export interface NavigationStackRouterConfig { + initialRouteName?: string, + initialRouteParams?: NavigationParams, + paths?: NavigationPathsConfig, + navigationOptions?: NavigationScreenOptions, +} + +export type NavigationStackAction = + NavigationInitAction + | NavigationNavigateAction + | NavigationBackAction + | NavigationSetParamsAction + | NavigationResetAction + +export type NavigationTabAction = + NavigationInitAction + | NavigationNavigateAction + | NavigationBackAction + +export type NavigationAction = + NavigationInitAction + | NavigationStackAction + | NavigationTabAction + +export namespace NavigationActions { + function navigate(options: NavigationNavigateAction): any; + function reset(options: NavigationResetAction): any; + function back(options: NavigationBackAction): any; + function setParams(options: NavigationSetParamsAction): any; +} + +export type NavigationRouteConfig = T & { + navigationOptions?: NavigationScreenOptions, + path?: string, +} + +export interface NavigationPathsConfig { + [routeName: string]: string, +} + +export interface NavigationTabRouterConfig { + initialRouteName?: string, + paths?: NavigationPathsConfig, + navigationOptions?: NavigationScreenOptions, + order?: string[], // todo: type these as the real route names rather than 'string' + + // Does the back button cause the router to switch to the initial tab + backBehavior?: 'none' | 'initialRoute', // defaults `initialRoute` +} + +export interface NavigationRouteConfigMap { + [routeName: string]: NavigationRouteConfig, +} + +export type NavigationDispatch = (action: A) => boolean + +export interface NavigationProp { + state: S, + dispatch: NavigationDispatch, +} + +export type NavigationScreenProp = NavigationProp & { + goBack: (routeKey?: string) => boolean, + navigate: (routeName: string, params?: NavigationParams, action?: NavigationAction) => boolean, + setParams: (newParams: NavigationParams) => boolean, +} + +export interface NavigationNavigatorProps

{ + navigation: NavigationProp, NavigationAction>, +} + +/** + * Gestures, Animations, and Interpolators + */ + +export type NavigationAnimatedValue = Animated.Value + +export type NavigationGestureDirection = 'horizontal' | 'vertical' + +export interface NavigationLayout { + height: NavigationAnimatedValue, + initHeight: number, + initWidth: number, + isMeasured: boolean, + width: NavigationAnimatedValue, +} + +export interface NavigationScene { + index: number, + isActive: boolean, + isStale: boolean, + key: string, + route: any, +} + +export interface NavigationTransitionProps { + // The layout of the transitioner of the scenes. + layout: NavigationLayout, + + // The navigation state of the transitioner. + navigationState: NavigationState, + + // The progressive index of the transitioner's navigation state. + position: NavigationAnimatedValue, + + // The value that represents the progress of the transition when navigation + // state changes from one to another. Its numberic value will range from 0 + // to 1. + // progress.__getAnimatedValue() < 1 : transtion is happening. + // progress.__getAnimatedValue() == 1 : transtion completes. + progress: NavigationAnimatedValue, + + // All the scenes of the transitioner. + scenes: NavigationScene[], + + // The active scene, corresponding to the route at + // `navigationState.routes[navigationState.index]`. When rendering + // NavigationSceneRendererPropsIndex, the scene does not refer to the active + // scene, but instead the scene that is being rendered. The index always + // is the index of the scene + scene: NavigationScene, + index: number, + navigation: NavigationScreenProp, + + // The gesture distance for `horizontal` and `vertical` transitions + gestureResponseDistance?: number, +} + +// The scene renderer props are nearly identical to the props used for rendering +// a transition. The exception is that the passed scene is not the active scene +// but is instead the scene that the renderer should render content for. +export type NavigationSceneRendererProps = NavigationTransitionProps + +export interface NavigationPanHandlers { + onMoveShouldSetResponder: () => void, + onMoveShouldSetResponderCapture: () => void, + onResponderEnd: () => void, + onResponderGrant: () => void, + onResponderMove: () => void, + onResponderReject: () => void, + onResponderRelease: () => void, + onResponderStart: () => void, + onResponderTerminate: () => void, + onResponderTerminationRequest: () => void, + onStartShouldSetResponder: () => void, + onStartShouldSetResponderCapture: () => void, +} + +export interface NavigationTransitionSpec { + duration?: number, + // An easing function from `Easing`. + easing?: () => any, + // A timing function such as `Animated.timing`. + timing?: (value: NavigationAnimatedValue, config: any) => any, +} + +export type NavigationAnimationSetter = ( + position: NavigationAnimatedValue, + newState: NavigationState, + lastState: NavigationState, +) => void + +export type NavigationSceneRenderer = ( + props: NavigationSceneRendererProps, +) => React.ReactElement + +export type NavigationStyleInterpolator = ( + props: NavigationSceneRendererProps, +) => ViewStyle + +export interface LayoutEvent { + nativeEvent: { + layout: { + x: number; + y: number; + width: number; + height: number; + }, + } +} + +interface NavigationContainerProps { + navigation: NavigationProp + onNavigationStateChange?: ( + preNavigationState: NavigationState, + nextNavigationState: NavigationState, + ) => void +} + +interface NavigationContainerState { + nav?: NavigationState +} + +export interface NavigationContainer extends React.ComponentClass< + NavigationContainerProps +> { + router: any +} + +export type StackNavigatorConfig = + NavigationContainerConfig + & NavigationStackViewConfig + & NavigationStackRouterConfig; + +// Return createNavigationContainer +export function StackNavigator( + routeConfigMap: NavigationRouteConfigMap, + stackConfig?: StackNavigatorConfig, +): NavigationContainer + +/** + * Drawer Navigator + */ +export interface DrawNavigatorConfig { + drawerWidth?: number, + drawerPosition?: 'left'|'right', + contentComponent?: React.ReactElement, + contentOptions?: { + activeTintColor?: string, + activeBackgroundColor?: string, + inactiveTintColor?: string, + inactiveBackgroundColor?: string, + style?: ViewStyle, + labelStyle?: TextStyle + } +} + +export function DrawerNavigator( + routeConfigMap: NavigationRouteConfigMap, + drawConfig?: DrawNavigatorConfig, +): NavigationContainer; + +/** + * Tab Navigator + */ +export interface TabNavigatorConfig { + tabBarComponent?: React.ReactElement, + tabBarPosition?: 'top'|'bottom', + swipeEnabled?: boolean, + animationEnabled?: boolean, + lazy?: boolean, + tabBarOptions?: { + activeTintColor?: string, + activeBackgroundColor?: string, + inactiveTintColor?: string, + inactiveBackgroundColor?: string, + showLabel?: boolean, + style?: ViewStyle, + labelStyle?: TextStyle, + + // Top + showIcon?: boolean, + upperCaseLabel?: boolean, + pressColor?: string, + pressOpacity?: number, + scrollEnabled?: boolean, + tabStyle?: ViewStyle, + indicatorStyle?: ViewStyle + } + initialRouteName?: string, + order?: string[], + paths?: any // TODO: better def + backBehavior?: 'initialRoute'|'none' +} + +export function TabNavigator( + routeConfigMap: NavigationRouteConfigMap, + drawConfig?: TabNavigatorConfig, +): NavigationContainer; +/** + * Screen Options + */ +export interface StackNavigatorScreenOptions { + title?: string; + headerVisible?: boolean; + headerTitle?: string|React.ReactElement; + headerBackTitle?: string|null; + headerTruncatedBackTitle?: string; + headerRight?: React.ReactElement; + headerLeft?: React.ReactElement; + headerStyle?: ViewStyle; + headerTitleStyle?: ViewStyle; + headerTintColor?: string; + headerPressColorAndroid?: string; + gesturesEnabled?: boolean; +} + +export interface TabNavigatorScreenOptions { + title?: string; + tabBarVisible?: boolean; + tabBarIcon?: React.ReactElement; + tabBarLaben?: string + |React.ReactElement + | ((options: {focused: boolean, tintColor: string}) => React.ReactElement) + ; +} + +export interface DrawerNavigatorScreenOptions { + title?: string; + drawerLabel?: string + |React.ReactElement + | ((options: {focused: boolean, tintColor: string}) => React.ReactElement) + ; + drawerIcon?: React.ReactElement + | ((options: {focused: boolean, tintColor: string}) => React.ReactElement) + ; +} diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx new file mode 100644 index 0000000000..d01ae62640 --- /dev/null +++ b/types/react-navigation/react-navigation-tests.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import { View } from 'react-native'; +import { + addNavigationHelpers, + StackNavigator, +} from 'react-navigation'; + +const Start = ( + +); + +export const AppNavigator = StackNavigator({ + StartImage: { + path: 'startImage', + screen: Start, + }, +}, { + initialRouteName: 'StartImage', +}); + +const Router = (props: any) => ( + +); diff --git a/types/react-navigation/tsconfig.json b/types/react-navigation/tsconfig.json new file mode 100644 index 0000000000..e670f06667 --- /dev/null +++ b/types/react-navigation/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-navigation-tests.tsx" + ] +} diff --git a/types/react-navigation/tslint.json b/types/react-navigation/tslint.json new file mode 100644 index 0000000000..0a6488b194 --- /dev/null +++ b/types/react-navigation/tslint.json @@ -0,0 +1,22 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Lowercase `object` is available in TypeScript 2.2 only. + "ban-types": false, + // Below are all TODO + "align": false, + "array-type": false, + "comment-format": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "no-misused-new": false, + "no-consecutive-blank-lines": false, + "no-empty-interface": false, + "no-padding": false, + "no-var": false, + "prefer-declare-function": false, + "prefer-method-signature": false, + "semicolon": false, + "strict-export-declare-modifiers": false + } +} From e8d4865015c4e6eb0a195abbe33937c461ff7b30 Mon Sep 17 00:00:00 2001 From: Paul Murray Date: Mon, 1 May 2017 16:12:09 -0400 Subject: [PATCH 004/109] fix CollectionAggregationOptions.maxTimeMS (#16226) `maxTimeMS` on `CollectionAggregationOptions` should be `number` not `boolean` --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 859dc87b26..4c4106c7a6 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -634,7 +634,7 @@ export interface CollectionAggregationOptions { allowDiskUse?: boolean; // specifies a cumulative time limit in milliseconds for processing operations // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - maxTimeMS?: boolean; + maxTimeMS?: number; // Allow driver to bypass schema validation in MongoDB 3.2 or higher. bypassDocumentValidation?: boolean; } From 55d680e198f84727ef2f0011632f1cff1f82497d Mon Sep 17 00:00:00 2001 From: Oden Date: Mon, 1 May 2017 13:13:41 -0700 Subject: [PATCH 005/109] Remove unneeded and broken react-router dependency from react-i18next (#16228) --- types/react-i18next/index.d.ts | 3 +-- types/react-i18next/tsconfig.json | 5 ----- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/types/react-i18next/index.d.ts b/types/react-i18next/index.d.ts index 7114087cd6..930fa7ae3c 100644 --- a/types/react-i18next/index.d.ts +++ b/types/react-i18next/index.d.ts @@ -6,7 +6,6 @@ import * as I18next from "i18next"; import * as React from "react"; -import * as ReactRouter from "react-router"; export type TranslationFunction = I18next.TranslationFunction; @@ -53,6 +52,6 @@ interface TranslateOptions { export function translate(namespaces?: string[] | string, options?: TranslateOptions): (WrappedComponent: C) => C; -export function loadNamespaces({ components, i18n }: { components: ReactRouter.RouteComponent[], i18n: I18next.I18n }): Promise; +export function loadNamespaces({ components, i18n }: { components: (React.ComponentClass | React.StatelessComponent)[], i18n: I18next.I18n }): Promise; export as namespace ReactI18Next; diff --git a/types/react-i18next/tsconfig.json b/types/react-i18next/tsconfig.json index c64579c2e8..ad5bca544b 100644 --- a/types/react-i18next/tsconfig.json +++ b/types/react-i18next/tsconfig.json @@ -9,11 +9,6 @@ "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", - "paths": { - "history": ["history/v2"], - "history/*": ["history/v2/*"], - "react-router": ["react-router/v2"] - }, "typeRoots": [ "../" ], From f532d39637dfd4c272b504794fe2ff0bfb704b81 Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Mon, 1 May 2017 22:15:37 +0200 Subject: [PATCH 006/109] node: add pauseOnConnect to createServer options (#16230) Documentation: https://nodejs.org/api/net.html#net_net_createserver_options_connectionlistener --- types/node/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 0f2a6e663e..9985d61ccc 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2122,7 +2122,7 @@ declare module "net" { prependOnceListener(event: "listening", listener: () => void): this; } export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; From 5a71b4961f39b3b8b72c72622395ef251006ffc3 Mon Sep 17 00:00:00 2001 From: Michael Aird Date: Mon, 1 May 2017 16:16:20 -0400 Subject: [PATCH 007/109] Add missing scheduler properties/method (#16231) --- types/kendo-ui/index.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index f1d3fa0437..9848335e49 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -5409,6 +5409,7 @@ declare namespace kendo.ui { slotByElement(element: Element): any; slotByElement(element: JQuery): any; view(type?: string): void; + view(): kendo.ui.SchedulerView; viewName(): string; } @@ -5627,7 +5628,8 @@ declare namespace kendo.ui { dateHeaderTemplate?: string|Function; dayTemplate?: string|Function; editable?: boolean|SchedulerViewEditable; - endTime?: Date; + endDate?(): Date; + endTime?: Date; eventHeight?: number; eventTemplate?: string|Function; eventTimeTemplate?: string|Function; @@ -5641,6 +5643,7 @@ declare namespace kendo.ui { selectedShortDateFormat?: string; showWorkHours?: boolean; slotTemplate?: string|Function; + startDate?(): Date; startTime?: Date; title?: string; type?: string; From 4d4b29f5630b01e7a42be4f77cb8c7d2ec4afd69 Mon Sep 17 00:00:00 2001 From: spacejack Date: Mon, 1 May 2017 16:16:42 -0400 Subject: [PATCH 008/109] Fixes for RouteResolver type and ClassComponent view method. (#16232) --- types/mithril/index.d.ts | 8 ++--- types/mithril/test/test-class-component.ts | 11 ++++--- types/mithril/test/test-route.ts | 38 ++++++++++++++++++++-- 3 files changed, 46 insertions(+), 11 deletions(-) diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index 1115d7c1f5..46fbb061ab 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -61,11 +61,11 @@ declare namespace Mithril { trust(html: string): Vnode; } - interface RouteResolver { + interface RouteResolver { /** The onmatch hook is called when the router needs to find a component to render. */ - render?(this: State, vnode: Vnode): Children; + onmatch?(this: this, args: Attrs, requestedPath: string): Component | Promise | void; /** The render method is called on every redraw for a matching route. */ - onmatch?(args: Params, requestedPath: string): Component | Promise | void; + render?(this: this, vnode: Vnode): Children; } /** This represents a key-value mapping linking routes to components. */ @@ -232,7 +232,7 @@ declare namespace Mithril { /** The onremove hook is called before a DOM element is removed from the document. */ onupdate?(vnode: VnodeDOM): any; /** Creates a view out of virtual elements. */ - view(vnode: CVnode): Children | null | void; + view(vnode: Vnode): Children | null | void; } /** diff --git a/types/mithril/test/test-class-component.ts b/types/mithril/test/test-class-component.ts index 7c1348683e..19f3aa343a 100644 --- a/types/mithril/test/test-class-component.ts +++ b/types/mithril/test/test-class-component.ts @@ -1,5 +1,5 @@ import * as m from 'mithril'; -import {ClassComponent, CVnode, CVnodeDOM} from 'mithril'; +import {ClassComponent, Vnode, CVnode, CVnodeDOM} from 'mithril'; /////////////////////////////////////////////////////////// // 0. @@ -95,12 +95,13 @@ class Comp4 implements ClassComponent { add(num: number) { this.count += num; } - view({attrs}: CVnode) { + view(vnode: Vnode) { return [ - m('h1', `This ${attrs.name} has been clicked ${this.count} times`), + m('h1', `This ${vnode.attrs.name} has been clicked ${this.count} times`), m('button', { - onclick: () => this.add(1) + // Can access 'this' via vnode.state + onclick: () => vnode.state.add(1) }, "Click me") ]; @@ -129,7 +130,7 @@ export interface Attrs { export default class MyComponent implements ClassComponent { count = 0; - view({attrs}: CVnode) { + view({attrs}: Vnode) { return m('span', `name: ${attrs.name}, count: ${this.count}`); } } diff --git a/types/mithril/test/test-route.ts b/types/mithril/test/test-route.ts index 5e584a8184..b18a92212c 100644 --- a/types/mithril/test/test-route.ts +++ b/types/mithril/test/test-route.ts @@ -1,4 +1,4 @@ -import {Component} from 'mithril'; +import {Component, Comp, RouteResolver} from 'mithril'; import * as h from 'mithril/hyperscript'; import * as route from 'mithril/route'; @@ -14,6 +14,39 @@ const component2 = { } } as Component<{title: string}, {}>; +interface Attrs { + id: string; +} + +interface State { + text: string; +} + +const component3: Comp = { + text: "Uninitialized", + oninit({state}) { + state.text = "Initialized"; + }, + view({attrs}) { + return h('p', 'id: ' + attrs.id); + } +}; + +// RouteResolver example using Attrs type and this context +const routeResolver: RouteResolver & {message: string} = { + message: "", + onmatch(attrs, path) { + this.message = "Match"; + const id: string = attrs.id; + return component3; + }, + render(vnode) { + this.message = "Render"; + vnode.key = vnode.attrs.id; + return vnode; + } +}; + route(document.body, '/', { '/': component1, '/test1': { @@ -41,7 +74,8 @@ route(document.body, '/', { resolve(component2); }); } - } + }, + 'test5/:id': routeResolver }); route.prefix('/app'); From 0edf649dcb4322d6695de3c1e0f7c421b60dd6bb Mon Sep 17 00:00:00 2001 From: valepu Date: Mon, 1 May 2017 22:17:01 +0200 Subject: [PATCH 009/109] Autobahn: Add missing Publish Options (#16233) Add all the missing publish options to interface IPublishOptions (according to documentation https://github.com/crossbario/autobahn-js/blob/master/doc/programming.md#publishing-events ). "disclose_me" is undocumented but it is indeed used inside autobahn's code --- types/autobahn/index.d.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 8a37bdf21b..6741bcccd1 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -167,8 +167,14 @@ declare namespace autobahn { interface IPublishOptions { acknowledge?: boolean; exclude?: number[]; + exclude_authid?: string[]; + exclude_authrole?: string[]; eligible?: number[]; - disclose_me?: Boolean; + eligible_authid?: string[]; + eligible_authrole?: string[]; + retain?: boolean; + disclose_me?: boolean; + exclude_me?: boolean; } interface ISubscribeOptions { From 15d14159bac65d42872f78bf70138ee8f2efb7e3 Mon Sep 17 00:00:00 2001 From: Budi Irawan Date: Tue, 2 May 2017 06:44:20 +1000 Subject: [PATCH 010/109] improve fallback language (#16236) - add def for array of string - add def for object list --- types/i18next/i18next-tests.ts | 28 ++++++++++++++++++++++++++++ types/i18next/index.d.ts | 14 ++++++++++---- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index 744fd950d4..2d3f6d3b04 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -59,6 +59,18 @@ i18n.init({ wait: false }); +i18n.init({ + fallbackLng: ['en', 'ru'], +}); + +i18n.init({ + fallbackLng: { + 'de-CH': ['fr', 'it'], + 'zh-HANT': ['zh-HANS', 'en'], + 'default': ['en'] + }, +}); + i18n.t('helloWorld', { defaultValue: 'default', count: 10 @@ -70,6 +82,22 @@ i18n.t('helloWorldInterpolated', { name: "world" }); +i18n.t('helloSingleFallbackLng', { + fallbackLng: 'en' +}); + +i18n.t('helloMultiFallbackLng', { + fallbackLng: ['en', 'ru'] +}); + +i18n.t('helloObjectFallbackLng', { + fallbackLng: { + 'de-CH': ['fr', 'it'], + 'zh-HANT': ['zh-HANS', 'en'], + 'default': ['en'] + }, +}); + i18n.exists("helloWorld"); const options:i18n.Options = i18n.options; diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index c0b0c82d81..1cacdeb7c3 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for i18next v2.3.4 +// Type definitions for i18next v2.3.5 // Project: http://i18next.com -// Definitions by: Michael Ledin +// Definitions by: Michael Ledin , Budi Irawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Sources: https://github.com/i18next/i18next/ @@ -19,6 +19,12 @@ declare namespace i18n { [key: string]: any; } + interface FallbackLngObjList { + [language: string]: string[] + } + + type FallbackLng = string | string[] | FallbackLngObjList; + interface InterpolationOptions { escapeValue?: boolean; prefix?: string; @@ -41,7 +47,7 @@ declare namespace i18n { replace?: any; lng?: string; lngs?: string[]; - fallbackLng?: string; + fallbackLng?: FallbackLng; ns?: string | string[]; keySeparator?: string; nsSeparator?: string; @@ -57,7 +63,7 @@ declare namespace i18n { debug?: boolean; resources?: ResourceStore; lng?: string; - fallbackLng?: string; + fallbackLng?: FallbackLng; ns?: string | string[]; defaultNS?: string; fallbackNS?: string | string[]; From 3440a18e98cb7845e53ca37114bb3a9910c2fc7b Mon Sep 17 00:00:00 2001 From: sclassen Date: Mon, 1 May 2017 22:46:11 +0200 Subject: [PATCH 011/109] ngStorage: improve definitions and update to newest tslint (#16238) * update ngstorage to new linter configuration * update ngStorage interfaces - remove the method StorageService.get() as it does not exist - add the method StorageService.$supported() which was missing - StorageService.$default() and StorageService.$reset() return an intersection type of its argument and StorageService - add the method StorageProvider.remove() which was missing - add the method StorageProvider.supported which was missing --- types/ngstorage/index.d.ts | 45 ++++++++--- types/ngstorage/ngstorage-tests.ts | 125 +++++++++++++++-------------- types/ngstorage/tsconfig.json | 2 +- types/ngstorage/tslint.json | 1 + 4 files changed, 101 insertions(+), 72 deletions(-) create mode 100644 types/ngstorage/tslint.json diff --git a/types/ngstorage/index.d.ts b/types/ngstorage/index.d.ts index 15fb3c0481..83c740ff0e 100644 --- a/types/ngstorage/index.d.ts +++ b/types/ngstorage/index.d.ts @@ -1,23 +1,48 @@ -// Type definitions for ngstorage 0.3.11 +// Type definitions for ngstorage 0.3 // Project: https://github.com/gsklee/ngStorage // Definitions by: Jakub Pistek // Definitions: https://github.com/kubiq/DefinitelyTyped -declare module 'ngstorage' { +export namespace ngStorage { + interface StorageService { + /** + * @return true if the storage service is supported by the browser. + */ + $supported(): boolean; + + /** + * Adds default values to the store. + * Copies all properties of the default items to the store. + * If the store already has one of these properties it will skip it. + * + * @param items object holding the default values. + * @return the modified storage service. + */ + $default(items: T): StorageService & T; + + /** + * Removes all properties from the store. + * + * @param items optional object holding the default values to initialize the store after reset. + * @return the modified storage service. + */ + $reset(items?: T): StorageService & T; - interface IStorageService { - $default(items: {}): IStorageService; - $reset(items?: {}): IStorageService; $apply(): void; $sync(): void; - get(key: string): T; + + /** + * Access to the properties of the store. + */ + [key: string]: any; } - interface IStorageProvider extends angular.IServiceProvider { - - get(key: string): T; - set(key: string, value: T): T; + interface StorageProvider extends angular.IServiceProvider { + get(key: string): T | boolean; + set(key: string, value: T): T | boolean; + remove(key: string): void; + supported(): boolean; setKeyPrefix(prefix: string): void; setSerializer(serializer: (value: any) => string): void; setDeserializer(deserializer: (value: string) => any): void; diff --git a/types/ngstorage/ngstorage-tests.ts b/types/ngstorage/ngstorage-tests.ts index abddf19bb7..a69d905a55 100644 --- a/types/ngstorage/ngstorage-tests.ts +++ b/types/ngstorage/ngstorage-tests.ts @@ -1,78 +1,81 @@ -/// +import * as angular from "angular"; +import { ngStorage } from "ngstorage"; -import {IStorageService, IStorageProvider} from "ngstorage"; +let app: angular.IModule = angular.module('at', ['ngStorage']); -var app: any; -app.controller('LocalCtrl', function ($localStorage: IStorageService) { +app.controller('LocalCtrl', ($localStorage: ngStorage.StorageService) => { + if ($localStorage.$supported()) { + const store: MyStore & ngStorage.StorageService = $localStorage.$default({ + counter: 1 + }); - $localStorage.$default({ - counter: 1 - }); + store.$reset({ + counter: 1 + }); - $localStorage.$reset({ - counter: 1 - }); - - $localStorage.$reset(); - - $localStorage.$apply(); - - $localStorage.$sync(); + store.$reset(); + store.$apply(); + store.$sync(); + } }); -app.controller('SessionCtrl', function ($sessionStorage: IStorageService) { +app.controller('SessionCtrl', ($sessionStorage: ngStorage.StorageService) => { + if ($sessionStorage.$supported()) { + const store: MyStore & ngStorage.StorageService = $sessionStorage.$default({ + counter: 1 + }); - $sessionStorage.$default({ - counter: 1 - }); + store.$reset({ + counter: 1 + }); - $sessionStorage.$reset({ - counter: 1 - }); - - $sessionStorage.$reset(); - - $sessionStorage.$apply(); - - $sessionStorage.$sync(); + store.$reset(); + store.$apply(); + store.$sync(); + } }); -app.config(['$localStorageProvider', function ($localStorageProvider: IStorageProvider) { +app.config(($localStorageProvider: ngStorage.StorageProvider) => { + if ($localStorageProvider.supported()) { + $localStorageProvider.setKeyPrefix('NewPrefix'); + $localStorageProvider.set('MyKey', { counter: 'value' }); + $localStorageProvider.get('MyKey'); + $localStorageProvider.remove('MyKey'); - $localStorageProvider.setKeyPrefix('NewPrefix'); + const mySerializer = (value: any): string => { + return value.toString(); + }; - $localStorageProvider.get('MyKey'); + const myDeserializer = (value: string): any => { + return value; + }; - $localStorageProvider.set('MyKey', {counter: 'value'}); + $localStorageProvider.setSerializer(mySerializer); + $localStorageProvider.setDeserializer(myDeserializer); + } +}); - var mySerializer = function (value: any): string { - return value.toString(); - }; +app.config(($sessionStorageProvider: ngStorage.StorageProvider) => { + if ($sessionStorageProvider.supported()) { + $sessionStorageProvider.setKeyPrefix('NewPrefix'); + $sessionStorageProvider.set('MyKey', { counter: 'value' }); + $sessionStorageProvider.get('MyKey'); + $sessionStorageProvider.remove('MyKey'); - var myDeserializer = function (value: string): any { - return value; - }; + const mySerializer = (value: any): string => { + return value.toString(); + }; - $localStorageProvider.setSerializer(mySerializer); - $localStorageProvider.setDeserializer(myDeserializer); + const myDeserializer = (value: string): any => { + return value; + }; + + $sessionStorageProvider.setSerializer(mySerializer); + $sessionStorageProvider.setDeserializer(myDeserializer); + } +}); + +interface MyStore { + counter?: number; + foo?: string; } -]).config(['$sessionStorageProvider', function ($sessionStorageProvider: IStorageProvider) { - - $sessionStorageProvider.setKeyPrefix('NewPrefix'); - - $sessionStorageProvider.get('MyKey'); - - $sessionStorageProvider.set('MyKey', {counter: 'value'}); - - var mySerializer = function (value: any): string { - return value.toString(); - }; - - var myDeserializer = function (value: string): any { - return value; - }; - - $sessionStorageProvider.setSerializer(mySerializer); - $sessionStorageProvider.setDeserializer(myDeserializer); -} -]); diff --git a/types/ngstorage/tsconfig.json b/types/ngstorage/tsconfig.json index a3cdb4a204..fffe367328 100644 --- a/types/ngstorage/tsconfig.json +++ b/types/ngstorage/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/ngstorage/tslint.json b/types/ngstorage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ngstorage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ddb6d939c3ad40e3e22fdf2d6c6d4fee3af29262 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 1 May 2017 16:47:36 -0400 Subject: [PATCH 012/109] TS Linting react-router (#16240) - Using default `dtslint/dt.json` for linting --- types/react-router/index.d.ts | 184 ++++++++---------- types/react-router/test/Ambiguous.tsx | 14 +- types/react-router/test/Animation.tsx | 26 +-- types/react-router/test/Auth.tsx | 42 ++-- types/react-router/test/Basic.tsx | 16 +- types/react-router/test/CustomLink.tsx | 14 +- types/react-router/test/MemoryRouter.tsx | 14 +- types/react-router/test/ModalGallery.tsx | 52 ++--- .../react-router/test/NavigateWithContext.tsx | 54 ++--- types/react-router/test/NoMatch.tsx | 14 +- types/react-router/test/Params.tsx | 10 +- .../test/PreventingTransitions.tsx | 20 +- types/react-router/test/Recursive.tsx | 18 +- types/react-router/test/RouteConfig.tsx | 26 +-- types/react-router/test/Sidebar.tsx | 16 +- types/react-router/test/Switch.tsx | 10 +- types/react-router/tslint.json | 15 +- 17 files changed, 251 insertions(+), 294 deletions(-) diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 2c21ac742b..07e22c26d5 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -15,112 +15,82 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -declare module 'react-router' { - import * as React from 'react'; - import * as H from 'history'; +import * as React from 'react'; +import * as H from 'history'; - // This is the type of the context object that will be passed down to all children of - // a `Router` component: - interface RouterChildContext

{ - router: { - history: H.History - route: { - location: H.Location, - match: match

- } - } - } - interface MemoryRouterProps { - initialEntries?: H.LocationDescriptor[]; - initialIndex?: number; - getUserConfirmation?: () => void; - keyLength?: number; - } - class MemoryRouter extends React.Component {} - - - interface PromptProps { - message: string | ((location: H.Location) => void); - when?: boolean; - } - class Prompt extends React.Component {} - - - interface RedirectProps { - to: H.LocationDescriptor; - push?: boolean; - from?: string; - path?: string; - exact?: boolean; - strict?: boolean; - } - class Redirect extends React.Component {} - - - interface RouteComponentProps

{ - match: match

; - location: H.Location; - history: H.History; - } - - interface RouteProps { - location?: H.Location; - component?: React.SFC | void> | React.ComponentClass | void>; - render?: (props: RouteComponentProps) => React.ReactNode; - children?: (props: RouteComponentProps) => React.ReactNode | React.ReactNode; - path?: string; - exact?: boolean; - strict?: boolean; - } - class Route extends React.Component {} - - - interface RouterProps { - history: any; - } - class Router extends React.Component {} - - - interface StaticRouterProps { - basename?: string; - location?: string | object; - context?: object; - } - class StaticRouter extends React.Component {} - - - interface SwitchProps extends RouteProps { - } - class Switch extends React.Component {} - - - interface match

{ - params: P; - isExact: boolean; - path: string; - url: string; - } - - - function matchPath

(pathname: string, props: RouteProps): match

| null; - - - function withRouter(component: React.SFC> | React.ComponentClass>): React.ComponentClass; - - - export { - MemoryRouter, - Prompt, - Redirect, - RouteComponentProps, // TypeScript specific, not from React Router itself - RouteProps, // TypeScript specific, not from React Router itself - Route, - Router, - StaticRouter, - Switch, - match, // TypeScript specific, not from React Router itself - matchPath, - withRouter, - RouterChildContext - } +// This is the type of the context object that will be passed down to all children of +// a `Router` component: +export interface RouterChildContext

{ + router: { + history: H.History + route: { + location: H.Location + match: match

+ } + }; } +export interface MemoryRouterProps { + initialEntries?: H.LocationDescriptor[]; + initialIndex?: number; + getUserConfirmation?: (() => void); + keyLength?: number; +} + +export class MemoryRouter extends React.Component {} + +export interface PromptProps { + message: string | ((location: H.Location) => void); + when?: boolean; +} +export class Prompt extends React.Component {} + +export interface RedirectProps { + to: H.LocationDescriptor; + push?: boolean; + from?: string; + path?: string; + exact?: boolean; + strict?: boolean; +} +export class Redirect extends React.Component {} + +export interface RouteComponentProps

{ + match: match

; + location: H.Location; + history: H.History; +} + +export interface RouteProps { + location?: H.Location; + component?: React.SFC | undefined> | React.ComponentClass | undefined>; + render?: ((props: RouteComponentProps) => React.ReactNode); + children?: ((props: RouteComponentProps) => React.ReactNode | React.ReactNode); + path?: string; + exact?: boolean; + strict?: boolean; +} +export class Route extends React.Component {} + +export interface RouterProps { + history: any; +} +export class Router extends React.Component {} + +export interface StaticRouterProps { + basename?: string; + location?: string | object; + context?: object; +} + +export class StaticRouter extends React.Component {} +export class Switch extends React.Component {} + +export interface match

{ + params: P; + isExact: boolean; + path: string; + url: string; +} + +export function matchPath

(pathname: string, props: RouteProps): match

| null; +export function withRouter(component: React.SFC> | React.ComponentClass>): React.ComponentClass; diff --git a/types/react-router/test/Ambiguous.tsx b/types/react-router/test/Ambiguous.tsx index 971636a1e0..6e6598fd71 100644 --- a/types/react-router/test/Ambiguous.tsx +++ b/types/react-router/test/Ambiguous.tsx @@ -1,11 +1,11 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, Route, Link, Switch -} from 'react-router-dom' +} from 'react-router-dom'; const AmbiguousExample = () => ( @@ -37,14 +37,14 @@ const AmbiguousExample = () => ( -) +); -const About = () =>

About

-const Company = () =>

Company

+const About = () =>

About

; +const Company = () =>

Company

; const User: React.SFC> = ({ match }) => (

User: {match.params.user}

-) +); -export default AmbiguousExample \ No newline at end of file +export default AmbiguousExample; diff --git a/types/react-router/test/Animation.tsx b/types/react-router/test/Animation.tsx index 1696dfd6fd..d303f29a97 100644 --- a/types/react-router/test/Animation.tsx +++ b/types/react-router/test/Animation.tsx @@ -1,5 +1,5 @@ -import * as React from 'react' -import * as ReactCSSTransitionGroup from 'react-addons-css-transition-group' +import * as React from 'react'; +import * as ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import { BrowserRouter as Router, RouteComponentProps, @@ -7,7 +7,7 @@ import { LinkProps, Link, Redirect -} from 'react-router-dom' +} from 'react-router-dom'; /* you'll need this CSS somewhere .fade-enter { @@ -58,13 +58,13 @@ const AnimationExample = () => ( )}/> -) +); const NavLink: React.SFC = (props) => (
  • -) +); interface HSLParams { h: number; @@ -78,9 +78,9 @@ const HSL: React.SFC> = ({ match: { params } }) = ...styles.hsl, background: `hsl(${params.h}, ${params.s}%, ${params.l}%)` }}>hsl({params.h}, {params.s}%, {params.l}%) -) +); -const styles: any = {} +const styles: any = {}; styles.fill = { position: 'absolute', @@ -88,13 +88,13 @@ styles.fill = { right: 0, top: 0, bottom: 0 -} +}; styles.content = { ...styles.fill, top: '40px', textAlign: 'center' -} +}; styles.nav = { padding: 0, @@ -104,20 +104,20 @@ styles.nav = { height: '40px', width: '100%', display: 'flex' -} +}; styles.navItem = { textAlign: 'center', flex: 1, listStyleType: 'none', padding: '10px' -} +}; styles.hsl = { ...styles.fill, color: 'white', paddingTop: '20px', fontSize: '30px' -} +}; -export default AnimationExample \ No newline at end of file +export default AnimationExample; diff --git a/types/react-router/test/Auth.tsx b/types/react-router/test/Auth.tsx index 86dffe2b63..c57251f9ef 100644 --- a/types/react-router/test/Auth.tsx +++ b/types/react-router/test/Auth.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, @@ -7,7 +7,7 @@ import { Link, Redirect, withRouter -} from 'react-router-dom' +} from 'react-router-dom'; //////////////////////////////////////////////////////////// // 1. Click the public page @@ -28,31 +28,31 @@ const AuthExample = () => ( -) +); const fakeAuth = { isAuthenticated: false, authenticate(this: any, cb: () => void) { - this.isAuthenticated = true - setTimeout(cb, 100) // fake async + this.isAuthenticated = true; + setTimeout(cb, 100); // fake async }, signout(this: any, cb: () => void) { - this.isAuthenticated = false - setTimeout(cb, 100) + this.isAuthenticated = false; + setTimeout(cb, 100); } -} +}; const AuthButton = withRouter(({ history }) => ( fakeAuth.isAuthenticated ? (

    Welcome!

    ) : (

    You are not logged in.

    ) -)) +)); const PrivateRoute: React.SFC = ({ component, ...rest }) => ( ( @@ -63,30 +63,30 @@ const PrivateRoute: React.SFC = ({ component, ...rest }) => ( }}/> ) )}/> -) +); -const Public: React.SFC> = () =>

    Public

    -const Protected: React.SFC> = () =>

    Protected

    +const Public: React.SFC> = () =>

    Public

    ; +const Protected: React.SFC> = () =>

    Protected

    ; class Login extends React.Component, {redirectToReferrer: boolean}> { state = { redirectToReferrer: false - } + }; login = () => { fakeAuth.authenticate(() => { - this.setState({ redirectToReferrer: true }) - }) + this.setState({ redirectToReferrer: true }); + }); } render() { - const { from } = this.props.location.state || { from: { pathname: '/' } } - const { redirectToReferrer } = this.state + const { from } = this.props.location.state || { from: { pathname: '/' } }; + const { redirectToReferrer } = this.state; if (redirectToReferrer) { return ( - ) + ); } return ( @@ -94,8 +94,8 @@ class Login extends React.Component, {redirectToReferr

    You must log in to view the page at {from.pathname}

    - ) + ); } } -export default AuthExample \ No newline at end of file +export default AuthExample; diff --git a/types/react-router/test/Basic.tsx b/types/react-router/test/Basic.tsx index 16ff86947a..c2b6c58405 100644 --- a/types/react-router/test/Basic.tsx +++ b/types/react-router/test/Basic.tsx @@ -1,10 +1,10 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, Route, Link -} from 'react-router-dom' +} from 'react-router-dom'; const BasicExample = () => ( @@ -22,19 +22,19 @@ const BasicExample = () => ( -) +); const Home = () => (

    Home

    -) +); const About = () => (

    About

    -) +); const Topics: React.SFC> = ({ match }) => (
    @@ -62,12 +62,12 @@ const Topics: React.SFC> = ({ match }) => (

    Please select a topic.

    )}/>
    -) +); const Topic: React.SFC> = ({ match }) => (

    {match.params.topicId}

    -) +); -export default BasicExample \ No newline at end of file +export default BasicExample; diff --git a/types/react-router/test/CustomLink.tsx b/types/react-router/test/CustomLink.tsx index 2159cf039a..4ec8be4c87 100644 --- a/types/react-router/test/CustomLink.tsx +++ b/types/react-router/test/CustomLink.tsx @@ -1,10 +1,10 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, Route, LinkProps, Link -} from 'react-router-dom' +} from 'react-router-dom'; const CustomLinkExample = () => ( @@ -16,7 +16,7 @@ const CustomLinkExample = () => ( -) +); interface OldSchoolMenuLinkProps extends LinkProps { activeOnlyWhenExact?: boolean; @@ -28,18 +28,18 @@ const OldSchoolMenuLink: React.SFC = ({ label, to, activ {match ? '> ' : ''}{label} )}/> -) +); const Home = () => (

    Home

    -) +); const About = () => (

    About

    -) +); -export default CustomLinkExample \ No newline at end of file +export default CustomLinkExample; diff --git a/types/react-router/test/MemoryRouter.tsx b/types/react-router/test/MemoryRouter.tsx index 1dd247acb2..7d947e436e 100644 --- a/types/react-router/test/MemoryRouter.tsx +++ b/types/react-router/test/MemoryRouter.tsx @@ -1,16 +1,16 @@ -import * as React from 'react' +import * as React from 'react'; import { MemoryRouter, Route, Link -} from 'react-router-dom' +} from 'react-router-dom'; const initialRouterEntries = [ '/', { pathname: '/about' } -] +]; const MemoryRouterExample = () => ( @@ -26,18 +26,18 @@ const MemoryRouterExample = () => ( -) +); const Home = () => (

    Home

    -) +); const About = () => (

    About

    -) +); -export default MemoryRouterExample +export default MemoryRouterExample; diff --git a/types/react-router/test/ModalGallery.tsx b/types/react-router/test/ModalGallery.tsx index ae817e0cc9..7236ea19a1 100644 --- a/types/react-router/test/ModalGallery.tsx +++ b/types/react-router/test/ModalGallery.tsx @@ -1,11 +1,11 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, Switch, RouteComponentProps, Route, Link -} from 'react-router-dom' +} from 'react-router-dom'; // This example shows how to render two different screens // (or the same screen in a different context) at the same url, @@ -29,26 +29,26 @@ class ModalSwitch extends React.Component, void> { // So, to get both screens to render, we can save the old // location and pass it to Switch, so it will think the location // is still `/` even though its `/images/2`. - previousLocation = this.props.location + previousLocation = this.props.location; componentWillUpdate(nextProps: RouteComponentProps) { - const { location } = this.props + const { location } = this.props; // set previousLocation if props.location is not modal if ( nextProps.history.action !== 'POP' && (!location.state || !location.state.modal) ) { - this.previousLocation = this.props.location + this.previousLocation = this.props.location; } } render() { - const { location } = this.props + const { location } = this.props; const isModal = !!( location.state && location.state.modal && this.previousLocation !== location // not initial render - ) + ); return (
    @@ -58,7 +58,7 @@ class ModalSwitch extends React.Component, void> { {isModal ? : null}
    - ) + ); } } @@ -68,21 +68,21 @@ const IMAGES = [ { id: 2, title: 'Tomato', color: 'Tomato' }, { id: 3, title: 'Seven Ate Nine', color: '#789' }, { id: 4, title: 'Crimson', color: 'Crimson' } -] +]; const Thumbnail: React.SFC<{color: string}> = ({ color }) =>
    + }}/>; const Image: React.SFC<{color: string}> = ({ color }) =>
    + }}>
    ; const Home = () => (
    @@ -93,7 +93,7 @@ const Home = () => (
  • Crimson
  • -) +); const Gallery = () => (
    @@ -111,12 +111,12 @@ const Gallery = () => ( ))}
    -) +); const ImageView: React.SFC> = ({ match }) => { - const image = IMAGES[parseInt(match.params.id, 10)] + const image = IMAGES[parseInt(match.params.id, 10)]; if (!image) { - return
    Image not found
    + return
    Image not found
    ; } return ( @@ -124,18 +124,18 @@ const ImageView: React.SFC> = ({ match }) => {

    {image.title}

    - ) -} + ); +}; const Modal: React.SFC> = ({ match, history }) => { - const image = IMAGES[parseInt(match.params.id, 10)] + const image = IMAGES[parseInt(match.params.id, 10)]; if (!image) { - return null! + return null!; } const back = (e: React.MouseEvent) => { - e.stopPropagation() - history.goBack() - } + e.stopPropagation(); + history.goBack(); + }; return (
    > = ({ match, history })
    - ) -} + ); +}; const ModalGallery = () => ( -) +); -export default ModalGallery \ No newline at end of file +export default ModalGallery; diff --git a/types/react-router/test/NavigateWithContext.tsx b/types/react-router/test/NavigateWithContext.tsx index 6f7dfa9f4a..89b53aef58 100644 --- a/types/react-router/test/NavigateWithContext.tsx +++ b/types/react-router/test/NavigateWithContext.tsx @@ -1,42 +1,42 @@ import * as React from 'react'; import { - RouterChildContext, - RouteComponentProps + RouterChildContext, + RouteComponentProps } from 'react-router'; import { - BrowserRouter as Router, - Route, -} from 'react-router-dom' + BrowserRouter as Router, + Route, +} from 'react-router-dom'; interface Params { - id?: string + id?: string; } -type Props = RouteComponentProps +type Props = RouteComponentProps; class ComponentThatUsesContext extends React.Component { - static contextTypes = { - router: React.PropTypes.object.isRequired - } - context: RouterChildContext - private onClick = () => { - const { - history, - route: { - location, - match - } - } = this.context.router; - history.push('/some/url'); - } - render() { - return
    - } + static contextTypes = { + router: React.PropTypes.object.isRequired + }; + context: RouterChildContext; + private onClick = () => { + const { + history, + route: { + location, + match + } + } = this.context.router; + history.push('/some/url'); + } + render() { + return
    ; + } } const Test = () => ( - - - + + + ); export default Test; diff --git a/types/react-router/test/NoMatch.tsx b/types/react-router/test/NoMatch.tsx index 10b7a64fa9..83c359d33e 100644 --- a/types/react-router/test/NoMatch.tsx +++ b/types/react-router/test/NoMatch.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, @@ -6,7 +6,7 @@ import { Link, Switch, Redirect -} from 'react-router-dom' +} from 'react-router-dom'; const NoMatchExample = () => ( @@ -26,7 +26,7 @@ const NoMatchExample = () => (
    -) +); const Home = () => (

    @@ -35,14 +35,14 @@ const Home = () => ( matches. A <Route> with no path always matches.

    -) +); -const WillMatch = () =>

    Matched!

    +const WillMatch = () =>

    Matched!

    ; const NoMatch: React.SFC> = ({ location }) => (

    No match for {location.pathname}

    -) +); -export default NoMatchExample \ No newline at end of file +export default NoMatchExample; diff --git a/types/react-router/test/Params.tsx b/types/react-router/test/Params.tsx index 148161c317..a6d0bded7f 100644 --- a/types/react-router/test/Params.tsx +++ b/types/react-router/test/Params.tsx @@ -1,10 +1,10 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, Route, Link -} from 'react-router-dom' +} from 'react-router-dom'; const ParamsExample = () => ( @@ -20,12 +20,12 @@ const ParamsExample = () => (
    -) +); const Child: React.SFC> = ({ match }) => (

    ID: {match.params.id}

    -) +); -export default ParamsExample \ No newline at end of file +export default ParamsExample; diff --git a/types/react-router/test/PreventingTransitions.tsx b/types/react-router/test/PreventingTransitions.tsx index b23ba65608..bd5d76ae2b 100644 --- a/types/react-router/test/PreventingTransitions.tsx +++ b/types/react-router/test/PreventingTransitions.tsx @@ -1,11 +1,11 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, Route, Link, Prompt -} from 'react-router-dom' +} from 'react-router-dom'; const PreventingTransitionsExample = () => ( @@ -20,15 +20,15 @@ const PreventingTransitionsExample = () => (

    Two

    }/>
    -) +); -class Form extends React.Component { +class Form extends React.Component { state = { isBlocking: false - } + }; render() { - const { isBlocking } = this.state + const { isBlocking } = this.state; return (
    { (event.target as HTMLFormElement).reset(); this.setState({ isBlocking: false - }) + }); }} > { onChange={event => { this.setState({ isBlocking: event.target.value.length > 0 - }) + }); }} />

    @@ -67,8 +67,8 @@ class Form extends React.Component {

    - ) + ); } } -export default PreventingTransitionsExample \ No newline at end of file +export default PreventingTransitionsExample; diff --git a/types/react-router/test/Recursive.tsx b/types/react-router/test/Recursive.tsx index 31b7c5fe29..64c0f690dc 100644 --- a/types/react-router/test/Recursive.tsx +++ b/types/react-router/test/Recursive.tsx @@ -1,11 +1,11 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, Route, Link, match -} from 'react-router-dom' +} from 'react-router-dom'; import * as H from 'history'; const PEEPS = [ @@ -13,15 +13,15 @@ const PEEPS = [ { id: 1, name: 'Sean', friends: [ 0, 3 ] }, { id: 2, name: 'Kim', friends: [ 0, 1, 3 ], }, { id: 3, name: 'David', friends: [ 1, 2 ] } -] +]; -const find = (id: number) => PEEPS.find(p => p.id === id) +const find = (id: number) => PEEPS.find(p => p.id === id); const RecursiveExample = () => ( -) +); interface InitialPersonProps { match: { @@ -35,7 +35,7 @@ interface InitialPersonProps { type PersonProps = RouteComponentProps<{ id: number }>; const Person: React.SFC = ({ match }) => { - const person = find(match.params.id) + const person = find(match.params.id); return (
    @@ -51,7 +51,7 @@ const Person: React.SFC = ({ match }) => { }/>
    - ) -} + ); +}; -export default RecursiveExample +export default RecursiveExample; diff --git a/types/react-router/test/RouteConfig.tsx b/types/react-router/test/RouteConfig.tsx index 1dffdc1527..b723821080 100644 --- a/types/react-router/test/RouteConfig.tsx +++ b/types/react-router/test/RouteConfig.tsx @@ -1,11 +1,11 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteComponentProps, RouteProps, Route, Link -} from 'react-router-dom' +} from 'react-router-dom'; // Some folks find value in a centralized route config. // A route config is just data. React is great at mapping @@ -13,12 +13,12 @@ import { //////////////////////////////////////////////////////////// // first our route components -const Main = () =>

    Main

    +const Main = () =>

    Main

    ; -const Sandwiches = () =>

    Sandwiches

    +const Sandwiches = () =>

    Sandwiches

    ; interface PropsWithRoutes extends RouteComponentProps { - routes: Array; + routes: MyRouteProps[]; } const Tacos: React.SFC = ({ routes }) => ( @@ -33,10 +33,10 @@ const Tacos: React.SFC = ({ routes }) => ( ))} -) +); -const Bus = () =>

    Bus

    -const Cart = () =>

    Cart

    +const Bus = () =>

    Bus

    ; +const Cart = () =>

    Cart

    ; //////////////////////////////////////////////////////////// // then our route config @@ -44,7 +44,7 @@ interface MyRouteProps extends RouteProps { component: React.SFC; routes?: MyRouteProps[]; } -const routes: Array = [ +const routes: MyRouteProps[] = [ { path: '/sandwiches', component: Sandwiches }, @@ -59,7 +59,7 @@ const routes: Array = [ } ] } -] +]; // wrap and use this everywhere instead, then when // sub routes are added to any route it'll work @@ -68,7 +68,7 @@ const RouteWithSubRoutes = (route: MyRouteProps) => ( // pass the sub-routes down to keep nesting )}/> -) +); const RouteConfigExample = () => ( @@ -83,6 +83,6 @@ const RouteConfigExample = () => ( ))} -) +); -export default RouteConfigExample \ No newline at end of file +export default RouteConfigExample; diff --git a/types/react-router/test/Sidebar.tsx b/types/react-router/test/Sidebar.tsx index fb81829dfb..921db7eca0 100644 --- a/types/react-router/test/Sidebar.tsx +++ b/types/react-router/test/Sidebar.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; import { BrowserRouter as Router, RouteProps, Route, Link -} from 'react-router-dom' +} from 'react-router-dom'; // Each logical "route" has two components, one for // the sidebar and one for the main area. We want to // render both of them in different places when the // path matches the current URL. interface MyRoute extends RouteProps { - sidebar: () => JSX.Element; - main: () => JSX.Element; + sidebar: (() => JSX.Element); + main: (() => JSX.Element); } -const routes: Array = [ +const routes: MyRoute[] = [ { path: '/', exact: true, sidebar: () =>
    home!
    , @@ -28,7 +28,7 @@ const routes: Array = [ sidebar: () =>
    shoelaces!
    , main: () =>

    Shoelaces

    } -] +]; const SidebarExample = () => ( @@ -75,6 +75,6 @@ const SidebarExample = () => ( -) +); -export default SidebarExample \ No newline at end of file +export default SidebarExample; diff --git a/types/react-router/test/Switch.tsx b/types/react-router/test/Switch.tsx index 626b0f6f7e..6a8b50f247 100644 --- a/types/react-router/test/Switch.tsx +++ b/types/react-router/test/Switch.tsx @@ -1,7 +1,7 @@ -import * as React from 'react' -import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom' +import * as React from 'react'; +import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom'; -const Home = () =>

    Home

    +const Home = () =>

    Home

    ; const SwitchTest = () => ( @@ -10,6 +10,6 @@ const SwitchTest = () => ( -) +); -export default SwitchTest +export default SwitchTest; diff --git a/types/react-router/tslint.json b/types/react-router/tslint.json index 53121f8387..2750cc0197 100644 --- a/types/react-router/tslint.json +++ b/types/react-router/tslint.json @@ -1,14 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "align": false, - "array-type": false, - "eofline": false, - "no-consecutive-blank-lines": false, - "no-empty-interface": false, - "prefer-method-signature": false, - "void-return": false, - "no-single-declare-module": false, - "semicolon": false - } -} +{ "extends": "dtslint/dt.json" } \ No newline at end of file From be0d3f97cb6760e29c13fc0910bc1f3b6758e52c Mon Sep 17 00:00:00 2001 From: Iain McGinniss Date: Mon, 1 May 2017 13:49:02 -0700 Subject: [PATCH 013/109] Typescript 2.3 fixes for credential management API (#16241) Removes the copied (now out of date) definition of RequestInit. Once 2.3 is "stable" for DefinitelyTyped (early June), CMRequestInit will be updated to match the latest lib.dom.d.ts definition. --- .../index.d.ts | 26 +++---------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index 36e6bf5c6a..d316572aab 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.1 +// Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.2 // Project: https://github.com/w3c/webappsec-credential-management // Definitions by: Iain McGinniss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -27,27 +27,9 @@ interface GlobalFetch { } /** - * Original definition from TS 2.2 dom. - */ -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: string; - mode?: string; - credentials?: string; - cache?: string; - redirect?: string; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -/** - * Variant of {@link RequestInit} that permits a {@link PasswordCredential} to - * be used in the {@code credentials} property. All other properties are - * identical to {@link RequestInit}. + * Variant of TS 2.2 {@link RequestInit} that permits a + * {@link PasswordCredential} to be used in the {@code credentials} property. + * All other properties are identical to {@link RequestInit}. */ interface CMRequestInit { method?: string; From 950c9cdca99ccc97dd09cb05609da679063584c5 Mon Sep 17 00:00:00 2001 From: beeme1mr Date: Mon, 1 May 2017 16:49:14 -0400 Subject: [PATCH 014/109] Added a code property to MongoError (#16242) Added missing code property to MongoError. http://thecodebarbarian.com/mongoose-error-handling --- types/mongodb/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 4c4106c7a6..5fe6332350 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -35,6 +35,7 @@ export interface MongoCallback { export class MongoError extends Error { constructor(message: string); static create(options: Object): MongoError; + code?: number; } //http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html#.connect From 3ff7e25c70b2e4cac8d6dde11fc227d172338681 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 1 May 2017 22:56:02 +0200 Subject: [PATCH 015/109] feat(fs-extra): update typings to `3.0.x` (#16218) * feat(fs-extra): update typyings to `3.0.x` * feat(fs-extra): update typings to `3.0.x` * test(fs-extra): add more test coverage * add `pathExists` * fix lint issues * fix lint issues * add `TypeScript Version: 2.2' * add more tests * change `interface` to `type` * add typescript version * add missing semicolon * add universalify fs async methods * add `fs` methods * feat(fs-extra): update typings to `3.0.x` * fix lint issues * fix more lint issues * fs-extra: add `mkdtemp` * remove extra breakline * remove `walk` and overall improvments * fix tests * add options to test * remove `CopyFilterFunction` and `CopyFilter` * remove `CopyFilterFunction` and `CopyFilter` * fix test * re add `CopyFilter` * fs-extra: fix CopyFilter * fs-extra: remove `MkdirOptions` * fs-extra: remove exra interfaces * feat(fs-extra): update typings to --- types/fs-extra-promise/index.d.ts | 8 +- types/fs-extra/fs-extra-tests.ts | 158 +++++++++++--- types/fs-extra/index.d.ts | 328 +++++++++++++++++++++--------- types/fs-extra/tsconfig.json | 42 ++-- types/fs-extra/tslint.json | 3 + 5 files changed, 391 insertions(+), 148 deletions(-) create mode 100644 types/fs-extra/tslint.json diff --git a/types/fs-extra-promise/index.d.ts b/types/fs-extra-promise/index.d.ts index a03512a577..b4c9a648ac 100644 --- a/types/fs-extra-promise/index.d.ts +++ b/types/fs-extra-promise/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/overlookmotel/fs-extra-promise // Definitions by: midknight41 , Jason Swearingen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// /// @@ -10,10 +11,15 @@ import * as stream from 'stream'; import { Stats } from 'fs'; import * as Promise from 'bluebird'; -import { CopyFilter, CopyOptions, ReadOptions, WriteOptions, MkdirOptions, MoveOptions } from 'fs-extra'; +import { CopyFilter, CopyOptions, ReadOptions, WriteOptions, MoveOptions } from 'fs-extra'; export * from 'fs-extra'; +export interface MkdirOptions { + fs?: any; + mode?: number; +} + //promisified versions export declare function copyAsync(src: string, dest: string): Promise; export declare function copyAsync(src: string, dest: string, filter: CopyFilter): Promise; diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index d39cae8d6f..005857e48c 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -1,106 +1,214 @@ import * as fs from 'fs-extra'; import * as Path from 'path'; +const len = 2; const src = ""; const dest = ""; const file = ""; const dir = ""; const path = ""; const data = ""; +const uid = 0; +const gid = 0; +const fd = 0; +const modeNum = 0; +const modeStr = ""; const object = {}; -const errorCallback = (err: Error) => {}; +const errorCallback = (err: Error) => { }; const readOptions: fs.ReadOptions = { - reviver : {} + reviver: {} }; const writeOptions: fs.WriteOptions = { - replacer: {} + replacer: {} }; +fs.moveSync(src, dest, {}); +fs.move(src, dest, {}).then(() => { + // stub +}); +fs.move(src, dest).then(() => { + // stub +}); +fs.move(src, dest, {}, () => { + // stub +}); +fs.move(src, dest, () => { + // stub +}); + +fs.copy(src, dest).then(() => { + // stub +}); +fs.copy(src, dest, { overwrite: true }).then(() => { + // stub +}); fs.copy(src, dest, errorCallback); -fs.copy(src, dest, (src: string) => { - return false; -}, errorCallback); +fs.copy(src, dest, (src: string) => false, errorCallback); fs.copy(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, - filter: (src: string) => { return false; } + filter: (src: string) => false }, errorCallback ); fs.copy(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, filter: /.*/ }, errorCallback ); fs.copySync(src, dest); -fs.copySync(src, dest, (src: string) => { - return false; -}); +fs.copySync(src, dest, (src: string) => false); fs.copySync(src, dest, /.*/); fs.copySync(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, - filter: (src: string) => { return false; } + filter: (src: string) => false } ); fs.copySync(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, filter: /.*/ } ); +fs.createFile(file).then(() => { + // stub +}); fs.createFile(file, errorCallback); fs.createFileSync(file); +fs.mkdirs(dir).then(() => { + // stub +}); +fs.mkdirp(dir).then(() => { + // stub +}); fs.mkdirs(dir, errorCallback); -fs.mkdirs(dir, {}, errorCallback); fs.mkdirsSync(dir); -fs.mkdirsSync(dir, {}); fs.mkdirp(dir, errorCallback); -fs.mkdirp(dir, {}, errorCallback); fs.mkdirpSync(dir); -fs.mkdirpSync(dir, {}); +fs.outputFile(file, data).then(() => { + // stub +}); fs.outputFile(file, data, errorCallback); fs.outputFileSync(file, data); -fs.outputJson(file, data, errorCallback); + +fs.outputJson(file, data, { + spaces: 2 +}).then(() => { + // stub +}); +fs.outputJson(file, data, { + spaces: 2 +}, errorCallback); fs.outputJSON(file, data, errorCallback); +fs.outputJSON(file, data).then(() => { + // stub +}); fs.outputJsonSync(file, data); fs.outputJSONSync(file, data); -fs.readJson(file, (error: Error, jsonObject: any) => {}); -fs.readJson(file, readOptions, (error: Error, jsonObject: any) => {}); -fs.readJSON(file, (error: Error, jsonObject: any) => {}); -fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => {}); +fs.readJson(file).then(() => { + // stub +}); + +fs.readJson(file, readOptions).then(() => { + // stub +}); +fs.readJson(file, (error: Error, jsonObject: any) => { }); +fs.readJson(file, readOptions, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => { }); fs.readJsonSync(file, readOptions); fs.readJSONSync(file, readOptions); fs.remove(dir, errorCallback); +fs.remove(dir).then(() => { + // stub +}); fs.removeSync(dir); +fs.writeJson(file, object).then(() => { + // stub +}); +fs.writeJSON(file, object).then(() => { + // stub +}); fs.writeJson(file, object, errorCallback); fs.writeJson(file, object, writeOptions, errorCallback); fs.writeJSON(file, object, errorCallback); fs.writeJSON(file, object, writeOptions, errorCallback); - +fs.writeJson(file, object, writeOptions).then(() => { + // stub +}); +fs.writeJSON(file, object, writeOptions).then(() => { + // stub +}); fs.writeJsonSync(file, object, writeOptions); fs.writeJSONSync(file, object, writeOptions); +fs.ensureDir(path).then(() => { + // stub +}); fs.ensureDir(path, errorCallback); fs.ensureDirSync(path); + +fs.ensureFile(path).then(() => { + // stub +}); fs.ensureFile(path, errorCallback); fs.ensureFileSync(path); +fs.ensureLink(path).then(() => { + // stub +}); fs.ensureLink(path, errorCallback); fs.ensureLinkSync(path); +fs.ensureSymlink(path).then(() => { + // stub +}); fs.ensureSymlink(path, errorCallback); fs.ensureSymlinkSync(path); +fs.emptyDir(path).then(() => { + // stub +}); fs.emptyDir(path, errorCallback); fs.emptyDirSync(path); +fs.pathExists(path).then((_exist: boolean) => { + // stub +}); +fs.pathExists(path, (_err: Error, _exists: boolean) => { }); +const x: boolean = fs.pathExistsSync(path); + +fs.rename(src, dest, errorCallback); +fs.renameSync(src, dest); +fs.truncate(path, len, errorCallback); +fs.truncateSync(path, len); +fs.chown(path, uid, gid, errorCallback); +fs.chownSync(path, uid, gid); +fs.fchown(fd, uid, gid, errorCallback); +fs.fchownSync(fd, uid, gid); +fs.lchown(path, uid, gid, errorCallback); +fs.lchownSync(path, uid, gid); +fs.chmod(path, modeNum, errorCallback); +fs.chmod(path, modeStr, errorCallback); +fs.chmodSync(path, modeNum); +fs.chmodSync(path, modeStr); +fs.fchmod(fd, modeNum, errorCallback); +fs.fchmod(fd, modeStr, errorCallback); +fs.fchmodSync(fd, modeNum); +fs.fchmodSync(fd, modeStr); +fs.lchmod(path, modeStr, errorCallback); +fs.lchmod(path, modeNum, errorCallback); +fs.lchmodSync(path, modeNum); +fs.lchmodSync(path, modeStr); +fs.statSync(path); +fs.lstatSync(path); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index c46dddba85..3d65d617b0 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,9 +1,8 @@ -// Type definitions for fs-extra 2.1 +// Type definitions for fs-extra 3.0 // Project: https://github.com/jprichardson/node-fs-extra -// Definitions by: midknight41 , Brendan Forster +// Definitions by: Alan Agius , midknight41 , Brendan Forster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts +// TypeScript Version: 2.2 /// @@ -11,123 +10,255 @@ import { Stats } from "fs"; export * from "fs"; -export declare function copy(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, filter: CopyFilter, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, options: CopyOptions, callback?: (err: Error) => void): void; +export function copy(src: string, dest: string, options?: CopyOptions): Promise; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; +export function copySync(src: string, dest: string, options?: CopyOptions): void; -export declare function copySync(src: string, dest: string): void; -export declare function copySync(src: string, dest: string, filter: CopyFilter): void; -export declare function copySync(src: string, dest: string, options: CopyOptions): void; +export function move(src: string, dest: string, options?: MoveOptions): Promise; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; +export function moveSync(src: string, dest: string, options?: MoveOptions): void; -export declare function move(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function move(src: string, dest: string, options: MoveOptions, callback?: (err: Error) => void): void; +export function createFile(file: string): Promise; +export function createFile(file: string, callback: (err: Error) => void): void; +export function createFileSync(file: string): void; -export declare function createFile(file: string, callback?: (err: Error) => void): void; -export declare function createFileSync(file: string): void; +export function ensureDir(path: string): Promise; +export function ensureDir(path: string, callback: (err: Error) => void): void; +export function ensureDirSync(path: string): void; -export declare function mkdirs(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirs(dir: string, options?: MkdirOptions, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, options?: MkdirOptions, callback?: (err: Error) => void): void; -export declare function mkdirsSync(dir: string, options?: MkdirOptions): void; -export declare function mkdirpSync(dir: string, options?: MkdirOptions): void; +export function mkdirs(dir: string): Promise; +export function mkdirs(dir: string, callback: (err: Error) => void): void; +export function mkdirp(dir: string): Promise; +export function mkdirp(dir: string, callback: (err: Error) => void): void; +export function mkdirsSync(dir: string): void; +export function mkdirpSync(dir: string): void; -export declare function outputFile(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputFileSync(file: string, data: any): void; +export function outputFile(file: string, data: any): Promise; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFileSync(file: string, data: any): void; -export declare function outputJson(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJsonSync(file: string, data: any): void; -export declare function outputJSONSync(file: string, data: any): void; +export function readJson(file: string, options?: ReadOptions): Promise; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options?: ReadOptions): Promise; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJsonSync(file: string, options?: ReadOptions): any; +export function readJSONSync(file: string, options?: ReadOptions): any; -export declare function readJsonSync(file: string, options?: ReadOptions): any; -export declare function readJSONSync(file: string, options?: ReadOptions): any; +export function remove(dir: string): Promise; +export function remove(dir: string, callback: (err: Error) => void): void; +export function removeSync(dir: string): void; -export declare function remove(dir: string, callback?: (err: Error) => void): void; -export declare function removeSync(dir: string): void; +export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, options?: WriteOptions): Promise; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; +export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; +export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; -export declare function writeJson(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJson(file: string, object: any, options?: WriteOptions, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, options?: WriteOptions, callback?: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options?: WriteOptions): Promise; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; -export declare function writeJsonSync(file: string, object: any, options?: WriteOptions): void; -export declare function writeJSONSync(file: string, object: any, options?: WriteOptions): void; +export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; +export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; -export declare function ensureDir(path: string, callback: (err: Error) => void): void; -export declare function ensureDirSync(path: string): void; +export function ensureFile(path: string): Promise; +export function ensureFile(path: string, callback: (err: Error) => void): void; +export function ensureFileSync(path: string): void; -export declare function ensureFile(path: string, callback: (err: Error) => void): void; -export declare function ensureFileSync(path: string): void; +export function ensureLink(path: string): Promise; +export function ensureLink(path: string, callback: (err: Error) => void): void; +export function ensureLinkSync(path: string): void; -export declare function ensureLink(path: string, callback: (err: Error) => void): void; -export declare function ensureLinkSync(path: string): void; +export function ensureSymlink(path: string): Promise; +export function ensureSymlink(path: string, callback: (err: Error) => void): void; +export function ensureSymlinkSync(path: string): void; -export declare function ensureSymlink(path: string, callback: (err: Error) => void): void; -export declare function ensureSymlinkSync(path: string): void; +export function emptyDir(path: string): Promise; +export function emptyDir(path: string, callback: (err: Error) => void): void; +export function emptyDirSync(path: string): void; -export declare function emptyDir(path: string, callback?: (err: Error) => void): void; -export declare function emptyDirSync(path: string): boolean; +export function pathExists(path: string): Promise; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; +export function pathExistsSync(path: string): boolean; -export interface WalkEventEmitter extends NodeJS.ReadableStream { - on(event: 'data', callback: (file: WalkEventFile) => void): this; - on(event: 'readable', callback: (this: PathEntryStream) => void): this; - on(event: 'error', callback: (error: Error, item: PathEntry) => void): this; - on(event: 'end', callback: () => void): this; - on(event: string | symbol, callback: Function): this; -} +// fs async methods +// copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts -export interface WalkEventFile { +/** Tests a user's permissions for the file specified by path. */ +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode?: number): Promise; + +export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(filename: string, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(filename: string, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; + +export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function chmod(path: string | Buffer, mode: string | number): Promise; + +export function chown(path: string | Buffer, uid: number, gid: number): Promise; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; + +export function close(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function close(fd: number): Promise; + +export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchmod(fd: number, mode: string | number): Promise; + +export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchown(fd: number, uid: number, gid: number): Promise; + +export function fdatasync(fd: number, callback: () => void): void; +export function fdatasync(fd: number): Promise; + +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function fstat(fd: number): Promise; + +export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fsync(fd: number): Promise; + +export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len?: number): Promise; + +export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: number, mtime: number): Promise; +export function futimes(fd: number, atime: Date, mtime: Date): Promise; + +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number): Promise; + +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; + +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function lstat(path: string | Buffer): Promise; + +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function mkdir(path: string | Buffer): Promise; + +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; + +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<[number, Buffer]>; + +export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; +export function readFile(filename: string, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(filename: string, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; +// tslint:disable-next-line:unified-signatures +export function readFile(filename: string, encoding: string): Promise; +export function readFile(filename: string): Promise; + +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; +export function readdir(path: string | Buffer): Promise; + +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; +export function readlink(path: string | Buffer): Promise; + +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; + +export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rename(oldPath: string, newPath: string): Promise; + +/** + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rmdir(path: string | Buffer): Promise; + +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function stat(path: string | Buffer): Promise; + +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; + +export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len?: number): Promise; + +/** + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function unlink(path: string | Buffer): Promise; + +export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; +export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; + +export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise<[number, Buffer]>; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise<[number, string]>; + +export function writeFile(filename: string, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; + +/** + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ +export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; +export function mkdtemp(prefix: string): Promise; + +export interface PathEntry { path: string; stats: Stats; } -export interface WalkOptions { - /** - * Control how results are enumerated from `readdir`: - * - 'shift' will return the first element from the array. - * - 'pop' will return the last element from the array. - * - * If not specified, the default behaviour is 'shift' - */ - queueMethod?: 'pop' | 'shift'; - /** - * Provide a function to sort the paths before they are enumerated - */ - pathSorter?: (left: string, right: string) => number; - /** - * An optional object to override the default `fs` APIs for testing purposes - */ - fs?: Object; - /** - * Provide a function to exclude certain file paths. The function should - * return true when the element should be kept, and false otherwise. - */ - filter?: (path: string, index: number, array: Array) => boolean; +export interface PathEntryStream { + read(): PathEntry | null; } -export type PathEntry = { - path: string; - stats: Stats; -} - -export type PathEntryStream = { - read(): PathEntry | null -} - -export interface CopyFilterFunction { - (src: string): boolean -} +export type CopyFilterFunction = (src: string) => boolean; export type CopyFilter = CopyFilterFunction | RegExp; export interface CopyOptions { - clobber?: boolean; dereference?: boolean; overwrite?: boolean; preserveTimestamps?: boolean; @@ -137,28 +268,23 @@ export interface CopyOptions { } export interface MoveOptions { - clobber? : boolean; + overwrite?: boolean; limit?: number; } export interface ReadOptions { throws?: boolean; - fs?: Object; + fs?: object; reviver?: any; encoding?: string; flag?: string; } export interface WriteOptions { - fs?: Object; + fs?: object; replacer?: any; spaces?: number; encoding?: string; flag?: string; mode?: number; } - -export interface MkdirOptions { - fs?: any; - mode?: number; -} diff --git a/types/fs-extra/tsconfig.json b/types/fs-extra/tsconfig.json index 6337361eed..818b38896c 100644 --- a/types/fs-extra/tsconfig.json +++ b/types/fs-extra/tsconfig.json @@ -1,22 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "fs-extra-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-extra-tests.ts" + ] +} diff --git a/types/fs-extra/tslint.json b/types/fs-extra/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fs-extra/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From ebb729c3760cbd837294e9bce4edd061c219cdef Mon Sep 17 00:00:00 2001 From: Josh Gillespie Date: Mon, 1 May 2017 15:56:31 -0500 Subject: [PATCH 016/109] Adding the errors module to request-promise-native (#16216) * Adding the errors module from the request-promise-native * linting --- types/request-promise-native/index.d.ts | 90 ++- .../request-promise-native-tests.ts | 593 +++++++++--------- types/request-promise-native/tslint.json | 3 + 3 files changed, 365 insertions(+), 321 deletions(-) create mode 100644 types/request-promise-native/tslint.json diff --git a/types/request-promise-native/index.d.ts b/types/request-promise-native/index.d.ts index 05eedaab72..ab606fb542 100644 --- a/types/request-promise-native/index.d.ts +++ b/types/request-promise-native/index.d.ts @@ -1,32 +1,76 @@ -// Type definitions for request-promise-native v1.0.3 +// Type definitions for request-promise-native 1.0 // Project: https://github.com/request/request-promise-native // Definitions by: Gustavo Henke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import request = require('request'); -import http = require('http'); +declare module 'request-promise-native' { + import request = require('request'); + import http = require('http'); -declare namespace requestPromise { - interface RequestPromise extends request.Request { - then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; - catch(onrejected?: (reason: any) => any | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; - promise(): Promise; - cancel(): void; + namespace requestPromise { + interface RequestPromise extends request.Request { + then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike | void): Promise; + catch(onrejected?: (reason: any) => any | PromiseLike | void): Promise; + promise(): Promise; + cancel(): void; + } + + interface RequestPromiseOptions extends request.CoreOptions { + simple?: boolean; + transform?(body: any, response: http.IncomingMessage, resolveWithFullResponse?: boolean): any; + resolveWithFullResponse?: boolean; + } + + type FullResponse = request.RequestResponse; + type OptionsWithUri = request.UriOptions & RequestPromiseOptions; + type OptionsWithUrl = request.UrlOptions & RequestPromiseOptions; + type Options = OptionsWithUri | OptionsWithUrl; } - interface RequestPromiseOptions extends request.CoreOptions { - simple?: boolean; - transform?: (body: any, response: http.IncomingMessage, resolveWithFullResponse?: boolean) => any; - resolveWithFullResponse?: boolean; - } - - export type FullResponse = request.RequestResponse; - export type OptionsWithUri = request.UriOptions & RequestPromiseOptions; - export type OptionsWithUrl = request.UrlOptions & RequestPromiseOptions; - export type Options = OptionsWithUri | OptionsWithUrl; + let requestPromise: request.RequestAPI; + export = requestPromise; } -declare var requestPromise: request.RequestAPI; -export = requestPromise; +declare module 'request-promise-native/errors' { + import rp = require('request-promise-native'); + import http = require('http'); + + interface RequestError extends Error { + cause: any; + error: any; + options: rp.Options; + response: http.IncomingMessage; + } + interface RequestErrorConstructor { + new (cause: any, options: rp.Options, response: http.IncomingMessage): RequestError; + (cause: any, options: rp.Options, response: http.IncomingMessage): RequestError; + prototype: RequestError; + } + const RequestError: RequestErrorConstructor; + + interface StatusCodeError extends Error { + statusCode: number; + error: any; + options: rp.Options; + response: http.IncomingMessage; + } + interface StatusCodeErrorConstructor extends Error { + new (statusCode: number, body: any, options: rp.Options, response: http.IncomingMessage): StatusCodeError; + (statusCode: number, body: any, options: rp.Options, response: http.IncomingMessage): StatusCodeError; + prototype: StatusCodeError; + } + const StatusCodeError: StatusCodeErrorConstructor; + + interface TransformError extends Error { + cause: any; + error: any; + options: rp.Options; + response: http.IncomingMessage; + } + interface TransformErrorConstructor extends Error { + new (cause: any, options: rp.Options, response: http.IncomingMessage): TransformError; + (cause: any, options: rp.Options, response: http.IncomingMessage): TransformError; + prototype: TransformError; + } + const TransformError: TransformErrorConstructor; +} diff --git a/types/request-promise-native/request-promise-native-tests.ts b/types/request-promise-native/request-promise-native-tests.ts index 4267351328..b0562acc6e 100644 --- a/types/request-promise-native/request-promise-native-tests.ts +++ b/types/request-promise-native/request-promise-native-tests.ts @@ -1,126 +1,127 @@ -import * as rp from 'request-promise-native'; +import * as rpn from 'request-promise-native'; +import * as path from 'path'; -rp('http://www.google.com') - .then(console.dir) - .catch(console.error); +rpn('http://www.google.com') + .then(console.dir) + .catch(console.error); -var options: rp.Options = { - uri : 'http://posttestserver.com/post.php', - method : 'POST', - json: true, - body: { some: 'payload' } +let options: rpn.Options = { + uri: 'http://posttestserver.com/post.php', + method: 'POST', + json: true, + body: { some: 'payload' } }; -rp(options) - .then(console.dir) - .catch(console.error); +let j = rpn.jar(); -rp('http://google.com').then(() => {}); +rpn(options) + .then(console.dir) + .catch(console.error); + +rpn('http://google.com').then(() => { }); // This works: -rp('http://google.com').then(console.dir); -rp('http://google.com').catch(console.error); -rp('http://google.com').then(console.dir, console.error); +rpn('http://google.com').then(console.dir); +rpn('http://google.com').catch(console.error); +rpn('http://google.com').then(console.dir, console.error); -rp({ uri: 'http://google.com', resolveWithFullResponse: true }).then((response) => {}); -rp({ uri: 'http://google.com', simple: false }).catch((reason) => {}); +rpn({ uri: 'http://google.com', resolveWithFullResponse: true }).then((response) => { }); +rpn({ uri: 'http://google.com', simple: false }).catch((reason) => { }); - -//Defaults tests +// Defaults tests (() => { const githubUrl = 'https://github.com'; - const defaultJarRequest = rp.defaults({ jar: true }); - defaultJarRequest.get(githubUrl).then(() => {}); - //defaultJarRequest(); //this line doesn't compile (and shouldn't) - const defaultUrlRequest = rp.defaults({ url: githubUrl }); - defaultUrlRequest().then(() => {}); - defaultUrlRequest.get().then(() => {}); - const defaultBodyRequest = defaultUrlRequest.defaults({body: '{}', json: true}); - defaultBodyRequest.get().then(() => {}); - defaultBodyRequest.post().then(() => {}); - defaultBodyRequest.put().then(() => {}); + const defaultJarRequest = rpn.defaults({ jar: true }); + defaultJarRequest.get(githubUrl).then(() => { }); + // defaultJarRequest(); //this line doesn't compile (and shouldn't) + const defaultUrlRequest = rpn.defaults({ url: githubUrl }); + defaultUrlRequest().then(() => { }); + defaultUrlRequest.get().then(() => { }); + const defaultBodyRequest = defaultUrlRequest.defaults({ body: '{}', json: true }); + defaultBodyRequest.get().then(() => { }); + defaultBodyRequest.post().then(() => { }); + defaultBodyRequest.put().then(() => { }); })(); // Get full response after DELETE options = { - method: 'DELETE', - uri: 'http://my-server/path/to/resource/1234' + method: 'DELETE', + uri: 'http://my-server/path/to/resource/1234' }; -rp(options) - .then(function (response: http.IncomingMessage) { - console.log("DELETE succeeded with status %d", response.statusCode); - }) - .catch(console.error); +rpn(options) + .then((response: http.IncomingMessage) => { + console.log("DELETE succeeded with status %d", response.statusCode); + }) + .catch(console.error); -//The following examples from https://github.com/request/request +// The following examples from https://github.com/request/request import * as fs from 'fs'; import * as http from 'http'; -var request = rp; -request('http://www.google.com', function (error, response, body) { - if (!error && response.statusCode == 200) { +rpn('http://www.google.com', (error, response, body) => { + if (!error && response.statusCode === 200) { console.log(body); // Show the HTML for the Google homepage. } }); -request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')); +rpn('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')); -fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')); +fs.createReadStream('file.json').pipe(rpn.put('http://mysite.com/obj.json')); -request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')); +rpn.get('http://google.com/img.png').pipe(rpn.put('http://mysite.com/img.png')); -request +rpn .get('http://google.com/img.png') - .on('response', function(response: any) { + .on('response', (response: any) => { console.log(response.statusCode); // 200 console.log(response.headers['content-type']); // 'image/png' }) - .pipe(request.put('http://mysite.com/img.png')); + .pipe(rpn.put('http://mysite.com/img.png')); -request +rpn .get('http://mysite.com/doodle.png') - .on('error', function(err: any) { + .on('error', (err: any) => { console.log(err); }) .pipe(fs.createWriteStream('doodle.png')); -http.createServer(function (req, resp) { +http.createServer((req, resp) => { if (req.url === '/doodle.png') { if (req.method === 'PUT') { - req.pipe(request.put('http://mysite.com/doodle.png')); + req.pipe(rpn.put('http://mysite.com/doodle.png')); } else if (req.method === 'GET' || req.method === 'HEAD') { - request.get('http://mysite.com/doodle.png').pipe(resp); + rpn.get('http://mysite.com/doodle.png').pipe(resp); } } }); -http.createServer(function (req, resp) { +http.createServer((req, resp) => { if (req.url === '/doodle.png') { - var x = request('http://mysite.com/doodle.png'); + let x = rpn('http://mysite.com/doodle.png'); req.pipe(x); x.pipe(resp); } }); -var resp: http.ServerResponse; -var req: rp.RequestPromise; -req.pipe(request('http://mysite.com/doodle.png')).pipe(resp); +let resp: http.ServerResponse; +let req: rpn.RequestPromise; +req.pipe(rpn('http://mysite.com/doodle.png')).pipe(resp); -var r = request; -http.createServer(function (req, resp) { +let r = rpn; +http.createServer((req, resp) => { if (req.url === '/doodle.png') { r.get('http://google.com/doodle.png').pipe(resp); } }); -request.post('http://service.com/upload', {form:{key:'value'}}); +rpn.post('http://service.com/upload', { form: { key: 'value' } }); // or -request.post('http://service.com/upload').form({key:'value'}); +rpn.post('http://service.com/upload').form({ key: 'value' }); // or -request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }); +rpn.post({ url: 'http://service.com/upload', form: { key: 'value' } }, (err, httpResponse, body) => { /* ... */ }); -var data = { +let data = { // Pass a simple key-value pair my_field: 'my_value', // Pass data via Buffers @@ -136,93 +137,93 @@ var data = { // Use case: for some types of streams, you'll need to provide "file"-related information manually. // See the `form-data` README for more information about options: https://github.com/felixge/node-form-data custom_file: { - value: fs.createReadStream('/dev/urandom'), + value: fs.createReadStream('/dev/urandom'), options: { filename: 'topsecret.jpg', contentType: 'image/jpg' } } }; -request.post({url:'http://service.com/upload', formData: data}, function optionalCallback(err, httpResponse, body) { +rpn.post({ url: 'http://service.com/upload', formData: data }, function optionalCallback(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); -var requestMultipart = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {}); -var form = requestMultipart.form(); +let requestMultipart = rpn.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) { }); +let form = requestMultipart.form(); form.append('my_field', 'my_value'); form.append('my_buffer', new Buffer([1, 2, 3])); -form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'}); +form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), { filename: 'unicycle.jpg' }); -request({ - method: 'PUT', - preambleCRLF: true, - postambleCRLF: true, - uri: 'http://service.com/upload', - multipart: { - chunked: false, - data: [ - { - 'content-type': 'application/json', - body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) - }, - { body: 'I am an attachment' } - ] - } - }, - function (error, response, body) { - if (error) { - return console.error('upload failed:', error); - } - console.log('Upload successful! Server responded with:', body); - }); -request({ - method: 'PUT', - preambleCRLF: true, - postambleCRLF: true, - uri: 'http://service.com/upload', - multipart: [ +rpn({ + method: 'PUT', + preambleCRLF: true, + postambleCRLF: true, + uri: 'http://service.com/upload', + multipart: { + chunked: false, + data: [ { 'content-type': 'application/json', - body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + body: JSON.stringify({ foo: 'bar', _attachments: { 'message.txt': { follows: true, length: 18, content_type: 'text/plain' } } }) }, - { body: 'I am an attachment' }, - { body: fs.createReadStream('image.png') } + { body: 'I am an attachment' } ] - }, - function (error, response, body) { + } +}, + (error, response, body) => { + if (error) { + return console.error('upload failed:', error); + } + console.log('Upload successful! Server responded with:', body); + }); +rpn({ + method: 'PUT', + preambleCRLF: true, + postambleCRLF: true, + uri: 'http://service.com/upload', + multipart: [ + { + 'content-type': 'application/json', + body: JSON.stringify({ foo: 'bar', _attachments: { 'message.txt': { follows: true, length: 18, content_type: 'text/plain' } } }) + }, + { body: 'I am an attachment' }, + { body: fs.createReadStream('image.png') } + ] +}, + (error, response, body) => { if (error) { return console.error('upload failed:', error); } console.log('Upload successful! Server responded with:', body); }); -request.get('http://some.server.com/').auth('username', 'password', false); +rpn.get('http://some.server.com/').auth('username', 'password', false); // or -request.get('http://some.server.com/', { - 'auth': { - 'user': 'username', - 'pass': 'password', - 'sendImmediately': false +rpn.get('http://some.server.com/', { + auth: { + user: 'username', + pass: 'password', + sendImmediately: false } }); // or -request.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); +rpn.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); // or -request.get('http://some.server.com/', { - 'auth': { - 'bearer': 'bearerToken' +rpn.get('http://some.server.com/', { + auth: { + bearer: 'bearerToken' } }); -var username = 'username', - password = 'password', - url = 'http://' + username + ':' + password + '@some.server.com'; +let username = 'username'; +let password = 'password'; +let url = 'http://' + username + ':' + password + '@some.server.com'; -request({url: url}, function (error, response, body) { - // Do more stuff with 'body' here +rpn({ url }, (error, response, body) => { + // Do more stuff with 'body' here }); options = { @@ -233,253 +234,249 @@ options = { }; function callback(error: any, response: http.IncomingMessage, body: string) { - if (!error && response.statusCode == 200) { - var info = JSON.parse(body); + if (!error && response.statusCode === 200) { + let info = JSON.parse(body); console.log(info.stargazers_count + " Stars"); console.log(info.forks_count + " Forks"); } } -request(options, callback); +rpn(options, callback); // OAuth1.0 - 3-legged server side flow (Twitter example) // step 1 import * as qs from 'querystring'; const CONSUMER_KEY = 'key'; const CONSUMER_SECRET = 'secret'; -var oauth = - { callback: 'http://mysite.com/callback/' - , consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - } - , url = 'https://api.twitter.com/oauth/request_token' - ; -request.post({url:url, oauth:oauth}, function (e, r, body) { +let oauth = { + callback: 'http://mysite.com/callback/' + , consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET +}; + +url = 'https://api.twitter.com/oauth/request_token'; + +rpn.post({ url, oauth }, (e, r, body) => { // Ideally, you would take the body in the response // and construct a URL that a user clicks on (like a sign in button). // The verifier is only available in the response after a user has // verified with twitter that they are authorizing your app. // step 2 - var req_data = qs.parse(body); - var uri = 'https://api.twitter.com/oauth/authenticate' - + '?' + qs.stringify({oauth_token: req_data.oauth_token}); + let req_data = qs.parse(body); + let uri = 'https://api.twitter.com/oauth/authenticate' + + '?' + qs.stringify({ oauth_token: req_data.oauth_token }); // redirect the user to the authorize uri // step 3 // after the user is redirected back to your server - var auth_data: any = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: auth_data.oauth_token - , token_secret: req_data.oauth_token_secret - , verifier: auth_data.oauth_verifier - } - , url = 'https://api.twitter.com/oauth/access_token' - ; - request.post({url:url, oauth:oauth}, function (e, r, body) { + let auth_data: any = qs.parse(body); + let oauth = { + consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + , token: auth_data.oauth_token + , token_secret: req_data.oauth_token_secret + , verifier: auth_data.oauth_verifier + }; + url = 'https://api.twitter.com/oauth/access_token'; + + rpn.post({ url, oauth }, (e, r, body) => { // ready to make signed requests on behalf of the user - var perm_data: any = qs.parse(body); - var oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: perm_data.oauth_token - , token_secret: perm_data.oauth_token_secret - }; - var url = 'https://api.twitter.com/1.1/users/show.json'; - var query = { + let perm_data: any = qs.parse(body); + let oauth = { + consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + , token: perm_data.oauth_token + , token_secret: perm_data.oauth_token_secret + }; + + url = 'https://api.twitter.com/1.1/users/show.json'; + let query = { screen_name: perm_data.screen_name, user_id: perm_data.user_id }; - request.get({url:url, oauth:oauth, qs:query, json:true}, function (e, r, user) { + rpn.get({ url, oauth, qs: query, json: true }, (e, r, user) => { console.log(user); }); }); }); -var path = require('path') - , certFile = path.resolve(__dirname, 'ssl/client.crt') - , keyFile = path.resolve(__dirname, 'ssl/client.key') - , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem'); +let certFile = path.resolve(__dirname, 'ssl/client.crt'); +let keyFile = path.resolve(__dirname, 'ssl/client.key'); +let caFile = path.resolve(__dirname, 'ssl/ca.cert.pem'); options = { - url: 'https://api.some-server.com/', + url: 'https://api.some-server.com/', + cert: fs.readFileSync(certFile), + key: fs.readFileSync(keyFile), + passphrase: 'password', + ca: fs.readFileSync(caFile) +}; + +rpn.get(options); + +options = { + url: 'https://api.some-server.com/', + agentOptions: { cert: fs.readFileSync(certFile), key: fs.readFileSync(keyFile), + // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format: + // pfx: fs.readFileSync(pfxFilePath), passphrase: 'password', - ca: fs.readFileSync(caFile) + securityOptions: 'SSL_OP_NO_SSLv3' + } }; -request.get(options); +rpn.get(options); -var path = require('path') - , certFile = path.resolve(__dirname, 'ssl/client.crt') - , keyFile = path.resolve(__dirname, 'ssl/client.key'); - -options = { - url: 'https://api.some-server.com/', - agentOptions: { - cert: fs.readFileSync(certFile), - key: fs.readFileSync(keyFile), - // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format: - // pfx: fs.readFileSync(pfxFilePath), - passphrase: 'password', - securityOptions: 'SSL_OP_NO_SSLv3' - } -}; - -request.get(options); - -request.get({ - url: 'https://api.some-server.com/', - agentOptions: { - secureProtocol: 'SSLv3_method' - } +rpn.get({ + url: 'https://api.some-server.com/', + agentOptions: { + secureProtocol: 'SSLv3_method' + } }); -request.get({ - url: 'https://api.some-server.com/', - agentOptions: { - ca: fs.readFileSync('ca.cert.pem') - } +rpn.get({ + url: 'https://api.some-server.com/', + agentOptions: { + ca: fs.readFileSync('ca.cert.pem') + } }); +rpn({ + // will be ignored + method: 'GET', + uri: 'http://www.google.com', -request({ - // will be ignored - method: 'GET', - uri: 'http://www.google.com', - - // HTTP Archive Request Object - har: { - url: 'http://www.mockbin.com/har', - method: 'POST', - headers: [ - { - name: 'content-type', - value: 'application/x-www-form-urlencoded' - } - ], - postData: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - { - name: 'foo', - value: 'bar' - }, - { - name: 'hello', - value: 'world' - } - ] + // HTTP Archive Request Object + har: { + url: 'http://www.mockbin.com/har', + method: 'POST', + headers: [ + { + name: 'content-type', + value: 'application/x-www-form-urlencoded' } - } - }); - -//requests using baseRequest() will set the 'x-token' header -var baseRequest = request.defaults({ - headers: {'x-token': 'my-token'} -}); - -//requests using specialRequest() will include the 'x-token' header set in -//baseRequest and will also include the 'special' header -var specialRequest = baseRequest.defaults({ - headers: {special: 'special value'} -}); - -request.put(url); -request.patch(url); -request.post(url); -request.head(url); -request.del(url); -request.get(url); -request.cookie('key1=value1'); -request.jar(); -request.debug = true; - -request.get('http://10.255.255.1', {timeout: 1500}, function(err) { - console.log(err.code === 'ETIMEDOUT'); - // Set to `true` if the timeout was a connection timeout, `false` or - // `undefined` otherwise. - console.log(err.connect === true); - process.exit(0); -}); - -var rand = Math.floor(Math.random()*100000000).toString(); - request( - { method: 'PUT' - , uri: 'http://mikeal.iriscouch.com/testjs/' + rand - , multipart: - [ { 'content-type': 'application/json' - , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + ], + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { + name: 'foo', + value: 'bar' + }, + { + name: 'hello', + value: 'world' } - , { body: 'I am an attachment' } ] } - , function (error, response, body) { - if(response.statusCode == 201){ - console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) - } else { - console.log('error: '+ response.statusCode) - console.log(body) - } - } - ); + } +}); -request( - { method: 'GET' +// requests using baseRequest() will set the 'x-token' header +let baseRequest = rpn.defaults({ + headers: { 'x-token': 'my-token' } +}); + +// requests using specialRequest() will include the 'x-token' header set in +// baseRequest and will also include the 'special' header +let specialRequest = baseRequest.defaults({ + headers: { special: 'special value' } +}); + +rpn.put(url); +rpn.patch(url); +rpn.post(url); +rpn.head(url); +rpn.del(url); +rpn.get(url); +rpn.cookie('key1=value1'); +rpn.jar(); +console.log(rpn.debug); + +rpn.get('http://10.255.255.1', { timeout: 1500 }, (err) => { + console.log(err.code === 'ETIMEDOUT'); + // Set to `true` if the timeout was a connection timeout, `false` or + // `undefined` otherwise. + console.log(err.connect === true); + process.exit(0); +}); + +let rand = Math.floor(Math.random() * 100000000).toString(); +rpn( + { + method: 'PUT' + , uri: 'http://mikeal.iriscouch.com/testjs/' + rand + , multipart: + [{ + 'content-type': 'application/json' + , body: JSON.stringify({ foo: 'bar', _attachments: { 'message.txt': { follows: true, length: 18, content_type: 'text/plain' } } }) + } + , { body: 'I am an attachment' } + ] + } + , (error, response, body) => { + if (response.statusCode === 201) { + console.log('document saved as: http://mikeal.iriscouch.com/testjs/' + rand); + } else { + console.log('error: ' + response.statusCode); + console.log(body); + } + } +); + +rpn( + { + method: 'GET' , uri: 'http://www.google.com' , gzip: true - } - , function (error, response, body) { - // body is the decompressed response body - console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')) - console.log('the decoded data is: ' + body) - } - ).on('data', function(data: any) { - // decompressed data as it is received - console.log('decoded chunk: ' + data) - }) - .on('response', function(response: http.IncomingMessage) { + } + , (error, response, body) => { + // body is the decompressed response body + console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')); + console.log('the decoded data is: ' + body); + } +).on('data', (data: any) => { + // decompressed data as it is received + console.log('decoded chunk: ' + data); +}) + .on('response', (response: http.IncomingMessage) => { // unmodified http.IncomingMessage object - response.on('data', function(data: any[]) { + response.on('data', (data: any[]) => { // compressed data as it is received - console.log('received ' + data.length + ' bytes of compressed data') - }) + console.log('received ' + data.length + ' bytes of compressed data'); + }); }); -var requestWithJar = request.defaults({jar: true}) -requestWithJar('http://www.google.com', function () { +let requestWithJar = rpn.defaults({ jar: true }); +requestWithJar('http://www.google.com', () => { requestWithJar('http://images.google.com'); }); -var j = request.jar() -requestWithJar = request.defaults({jar:j}) -requestWithJar('http://www.google.com', function () { +requestWithJar = rpn.defaults({ jar: j }); +requestWithJar('http://www.google.com', () => { requestWithJar('http://images.google.com'); }); -var j = request.jar(); -var cookie = request.cookie('key1=value1'); -var url = 'http://www.google.com'; +let cookie = rpn.cookie('key1=value1'); +url = 'http://www.google.com'; j.setCookie(cookie, url); -request({url: url, jar: j}, function () { - request('http://images.google.com'); +rpn({ url, jar: j }, () => { + rpn('http://images.google.com'); }); -//TODO: add definitions for tough-cookie-filestore -//var FileCookieStore = require('tough-cookie-filestore'); +// TODO: add definitions for tough-cookie-filestore +// let FileCookieStore = require('tough-cookie-filestore'); // NOTE - currently the 'cookies.json' file must already exist! -//var j = request.jar(new FileCookieStore('cookies.json')); -requestWithJar = request.defaults({ jar : j }) -request('http://www.google.com', function() { - request('http://images.google.com'); +// let j = request.jar(new FileCookieStore('cookies.json')); +requestWithJar = rpn.defaults({ jar: j }); +rpn('http://www.google.com', () => { + rpn('http://images.google.com'); }); -var j = request.jar() -request({url: 'http://www.google.com', jar: j}, function () { - var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." - var cookies = j.getCookies(url); +rpn({ url: 'http://www.google.com', jar: j }, () => { + let cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." + let cookies = j.getCookies(url); // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] }); diff --git a/types/request-promise-native/tslint.json b/types/request-promise-native/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/request-promise-native/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 418bdd3a4971282c4dd3a5c0fa88a0bf9dc0906e Mon Sep 17 00:00:00 2001 From: lobo87 Date: Mon, 1 May 2017 23:02:04 +0200 Subject: [PATCH 017/109] added new types for npm package cordova-plugin-native-keyboard (#16152) * added cordova-plugin-native-keyboard * updated to conform linting checks --- .../cordova-plugin-native-keyboard-tests.ts | 43 +++ .../cordova-plugin-native-keyboard/index.d.ts | 303 ++++++++++++++++++ .../tsconfig.json | 22 ++ .../tslint.json | 1 + 4 files changed, 369 insertions(+) create mode 100644 types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts create mode 100644 types/cordova-plugin-native-keyboard/index.d.ts create mode 100644 types/cordova-plugin-native-keyboard/tsconfig.json create mode 100644 types/cordova-plugin-native-keyboard/tslint.json diff --git a/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts b/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts new file mode 100644 index 0000000000..4597e2c39a --- /dev/null +++ b/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts @@ -0,0 +1,43 @@ +/** + * Display Messenger + */ +NativeKeyboard.showMessenger({ + onSubmit: (text) => {}, + onKeyboardDidHide: () => {}, + onKeyboardDidShow: () => {}, + onKeyboardWillShow: () => {}, + onTextChanged: (text) => {}, + onKeyboardWillHide: () => {}, +}); + +/** + * Display Messenger Keyboard + */ +NativeKeyboard.showMessengerKeyboard( + () => {}, + () => {}); + +/** + * Hide Messenger + */ +NativeKeyboard.hideMessenger( + { animated: true}, + () => {}, + () => {}); + +NativeKeyboard.hideMessenger(); + +/** + * Hide Messenger Keyboard + */ +NativeKeyboard.hideMessengerKeyboard( + () => {}, + () => {}); + +/** + * Update Messenger Keyboard + */ +NativeKeyboard.updateMessenger( + {text: 'FooBar'}, + () => {}, + () => {}); diff --git a/types/cordova-plugin-native-keyboard/index.d.ts b/types/cordova-plugin-native-keyboard/index.d.ts new file mode 100644 index 0000000000..0f64199bd1 --- /dev/null +++ b/types/cordova-plugin-native-keyboard/index.d.ts @@ -0,0 +1,303 @@ +// Type definitions for cordova-plugin-native-keyboard 1.3 +// Project: https://github.com/EddyVerbruggen/cordova-plugin-native-keyboard#readme +// Definitions by: Daniel Brolli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface NativeKeyboard { + /** + * Show the messenger, the bare minimum which has to be passed to the function is + * the onSubmit callback + * @param options + */ + showMessenger( + options: NativeKeyboardShowOptions + ): void; + + /** + * It's likely your app only has 1 one page where you want to show the messenger, + * so you want to hide it when the user navigates away. You can choose to do this + * either animated (a quick slide down animation) or not. + * + * @param options + * @param onSuccess + * @param onError + */ + hideMessenger( + options?: NativeKeyboardHideOptions, + onSuccess?: () => void, + onError?: (err: any) => void + ): void; + + /** + * Show a previously hidden keyboard + * + * @param onSuccess + * @param onError + */ + showMessengerKeyboard( + onSuccess?: () => void, + onError?: (err: any) => void, + ): void; + + /** + * Hide the keyboard, but not the messenger bar + * + * @param onSuccess + * @param onError + */ + hideMessengerKeyboard( + onSuccess?: () => void, + onError?: (err: any) => void, + ): void; + + /** + * Manipulate the messenger while it's open. For instance if you want to + * update the text programmatically based on what the user typed (by responding to + * onTextChanged events). + * + * @param options + * @param onSuccess + * @param onError + */ + updateMessenger( + options: NativeKeyboardUpdateOptions, + onSuccess?: () => void, + onError?: (err: any) => void + ): void; +} + +interface NativeKeyboardUpdateOptions { + /** + * Replace the messenger's text by this. The current text remains if omitted. + */ + text?: string; + + /** + * Position the cursor anywhere in the text range. Defaults to the end of the text. + */ + caretIndex?: number; + + /** + * If false or omitted no changes to the keyboard state are made. + */ + showKeyboard?: boolean; +} + +interface NativeKeyboardHideOptions { + /** + * A boolean flag inidicating if the keyboard should be shown/hidden with an animation + */ + animated?: boolean; +} + +interface NativeKeyboardShowOptions { + /** + * Callback function, which is being called as soon as the user submits + * @param text + */ + onSubmit(text: string): void; + + /** + * Callback function which is being executed as soon as the keyboard will show + */ + onKeyboardWillShow?(): void; + + /** + * Callback function which is being executed as soon as the keyboard did show + */ + onKeyboardDidShow?(): void; + + /** + * Callback function which is being executed as soon as the keyboard will hide + */ + onKeyboardWillHide?(): void; + + /** + * Callback function which is being executed as soon as the keyboard did hide + */ + onKeyboardDidHide?(): void; + + /** + * Callback function which is being executed as soon as the entered text changes. Will + * return the new text + * + * @param text + */ + onTextChanged?(text: string): void; + + /** + * DOM element, which should be scrolled automatically + */ + autoscrollElement?: any; + + /** + * Boolean value indicating if the content should be scrolled to the end after the messenger is + * shown + */ + scrollToBottomAfterMessengerShows?: boolean; + + /** + * Boolean value indicating if the keyboard should be kept open after submitting the entered + * text + * + * Default: false + */ + keepOpenAfterSubmit?: boolean; + + /** + * Makes the messenger bar slide in from the bottom. + * + * Default: false + */ + animated?: boolean; + + /** + * Open the keyboard when showing the messenger. + * + * Default: false + */ + showKeyboard?: boolean; + + /** + * A text which will be in the messenger bar, when opening + */ + text?: string; + + /** + * The color of the typed text in HEX. + * + * Default: #444 + */ + textColor?: string; + + /** + * A placeholder which will be in the messenger bar, when opening and the input field is + * empty + */ + placeholder?: string; + + /** + * The color of the placeholder. + * + * Default: #ccc + */ + placeholderColor?: string; + + /** + * The background color of the messenger bar. + * + * Default: #F6F6F6 + */ + backgroundColor?: string; + + /** + * The background color of the textview. Looks nicest on Android + * if it's the same color as the backgroundColor property. + * + * Default: #F6F6F6 + */ + textViewBackgroundColor?: string; + + /** + * The border color of the textview. + * + * Default: #666666 + */ + textViewBorderColor?: string; + + /** + * Maximum amount of chars that can be entered + */ + maxChars?: number; + + /** + * Options are: "none", "split", "countdown", "countdownreversed". + * Note that if maxChars is set, "none" will still show a counter. + * + * Default: "none" + */ + counterStyle?: string; + + /** + * Options are: "default", "decimalpad", "phonepad", "numberpad", "namephonepad", + * "number", "email", "twitter", "url", "alphabet", "search", "ascii" + * + * Default: "default" + */ + type?: string; + + /** + * Options are: "light", "dark". + * + * Default: "default" + */ + appearance?: string; + + /** + * Disables things like the Emoji keyboard and the Predicive text entry bar + * + * Default: false + */ + secure?: boolean; + + /** + * The left button of the messenger bar + */ + leftButton?: LeftButtonOptions; + + /** + * The right button of the messenger bar + */ + rightButton?: ButtonOptions; +} + +interface ButtonOptions { + /** + * The type of the button. + * Either "text", "fontawesome" or "ionicon". + * + * Default: "text" + */ + type?: string; + + /** + * The value of the button. On "text" the string is used as label + * On fonatawesome or ionicon the icon name is used (e.g. fa-rocket) + * + * Default: "Send" + */ + value?: string; + + /** + * If type is "text" you can set this to either "normal", "bold" or "italic". + * + * Default: "normal" + */ + textStyle?: string; + + /** + * The color of the button in HEX + * + * Default: #000 + */ + color: string; + + /** + * A callback being executed as soon as the button is clicked + */ + onPress(): void; +} + +interface LeftButtonOptions extends ButtonOptions { + /** + * Set to true to disable the button once text has been entered. + * + * Default: false + */ + disabledWhenTextEntered?: boolean; +} + +/** NativeKeyboard instance */ +declare var NativeKeyboard: NativeKeyboard; +interface Window { + NativeKeyboard: NativeKeyboard; +} diff --git a/types/cordova-plugin-native-keyboard/tsconfig.json b/types/cordova-plugin-native-keyboard/tsconfig.json new file mode 100644 index 0000000000..4309b2406b --- /dev/null +++ b/types/cordova-plugin-native-keyboard/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-native-keyboard-tests.ts" + ] +} diff --git a/types/cordova-plugin-native-keyboard/tslint.json b/types/cordova-plugin-native-keyboard/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cordova-plugin-native-keyboard/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 7bd8b5865ca82475458ee6cb34f6656fc5727db0 Mon Sep 17 00:00:00 2001 From: Guo Yunhe Date: Tue, 2 May 2017 00:03:00 +0300 Subject: [PATCH 018/109] js-search: add definition (#16102) * js-search: add definition * js-search: fix project url * js-search: use module instead of namespace declare * js-search: change strictNullChecks to true * js-search: add tslint.json --- types/js-search/index.d.ts | 143 +++++++++++++++++++++++++++++ types/js-search/js-search-tests.ts | 58 ++++++++++++ types/js-search/tsconfig.json | 22 +++++ types/js-search/tslint.json | 1 + 4 files changed, 224 insertions(+) create mode 100644 types/js-search/index.d.ts create mode 100644 types/js-search/js-search-tests.ts create mode 100644 types/js-search/tsconfig.json create mode 100644 types/js-search/tslint.json diff --git a/types/js-search/index.d.ts b/types/js-search/index.d.ts new file mode 100644 index 0000000000..49c10251eb --- /dev/null +++ b/types/js-search/index.d.ts @@ -0,0 +1,143 @@ +// Type definitions for js-search v1.4.0 +// Project: https://github.com/bvaughn/js-search +// Definitions by: Guo Yunhe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "js-search" { + + class Search { + + constructor( + uidFieldName: string | Array + ); + + public indexStrategy: IIndexStrategy; + public sanitizer: ISanitizer; + public searchIndex: ISearchIndex; + public tokenizer: ITokenizer; + + public addDocument(document: Object): void; + public addDocuments(documents: Array): void; + + public addIndex(field: string | Array): void; + + public search(query: string): Array; + + } + + interface IIndexStrategy { + expandToken(token: string): Array; + } + + class AllSubstringsIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + class ExactWordIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + class PrefixIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + interface ISanitizer { + sanitize(text: string): string; + } + + class CaseSensitiveSanitizer implements ISanitizer { + sanitize(text: string): string; + } + + class LowerCaseSanitizer implements ISanitizer { + sanitize(text: string): string; + } + + interface ISearchIndex { + indexDocument( + token: string, + uid: string, + document: Object + ): void; + + search( + tokens: Array, + corpus: Array + ): Array; + } + + type ITfIdfTokenMap = { + [token: string]: ITfIdfTokenMetadata; + }; + + type ITfIdfUidMap = { + [uid: string]: ITfIdfUidMetadata; + }; + + type ITfIdfTokenMetadata = { + $numDocumentOccurrences: number; + $totalNumOccurrences: number; + $uidMap: ITfIdfUidMap; + }; + + type ITfIdfUidMetadata = { + $document: Object; + $numTokenOccurrences: number; + }; + + class TfIdfSearchIndex implements ISearchIndex { + constructor(uidFieldName: string | Array); + + indexDocument(token: string, uid: string, doc: Object): void; + + search(tokens: Array, corpus: Array): Array; + } + + class UnorderedSearchIndex implements ISearchIndex { + constructor(); + + indexDocument(token: string, uid: string, doc: Object): void; + + search(tokens: Array, corpus: Array): Array; + } + + interface ITokenizer { + tokenize(text: string): Array; + } + + class SimpleTokenizer implements ITokenizer { + tokenize(text: string): Array; + } + + type StemmingFunction = (text: string) => string; + + class StemmingTokenizer implements ITokenizer { + constructor( + stemmingFunction: StemmingFunction, + decoratedTokenizer: ITokenizer + ); + + tokenize(text: string): Array; + } + + class StopWordsTokenizer implements ITokenizer { + constructor(decoratedTokenizer: ITokenizer); + + tokenize(text: string): Array; + } + + var StopWordsMap: any; + + class TokenHighlighter { + + constructor( + opt_indexStrategy: IIndexStrategy, + opt_sanitizer: ISanitizer, + opt_wrapperTagName: string + ); + + public highlight(text: string, tokens: Array): string; + + } + +} diff --git a/types/js-search/js-search-tests.ts b/types/js-search/js-search-tests.ts new file mode 100644 index 0000000000..b852e000cc --- /dev/null +++ b/types/js-search/js-search-tests.ts @@ -0,0 +1,58 @@ +import { Search, ITokenizer, StopWordsMap, StopWordsTokenizer, StemmingTokenizer, SimpleTokenizer, UnorderedSearchIndex } from "js-search"; + +var theGreatGatsby = { + isbn: '9781597226769', + title: 'The Great Gatsby', + author: { + name: 'F. Scott Fitzgerald' + }, + tags: ['book', 'inspirational'] +}; +var theDaVinciCode = { + isbn: '0307474275', + title: 'The DaVinci Code', + author: { + name: 'Dan Brown' + }, + tags: ['book', 'mystery'] +}; +var angelsAndDemons = { + isbn: '074349346X', + title: 'Angels & Demons', + author: { + name: 'Dan Brown', + }, + tags: ['book', 'mystery'] +}; + +var search = new Search('isbn'); +search.addIndex('title'); +search.addIndex(['author', 'name']); +search.addIndex('tags') + +search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]); + +search.search('The'); // [theGreatGatsby, theDaVinciCode] +search.search('scott'); // [theGreatGatsby] +search.search('dan'); // [angelsAndDemons, theDaVinciCode] +search.search('mystery') // [angelsAndDemons, theDaVinciCode] + +search.tokenizer = { + tokenize(text: any) { + // Convert text to an Array of strings and return the Array + } +}; + + +// Function should accept a string param and return a string +var stemmer = function () { return 'foobar' }; + +search.tokenizer = new StemmingTokenizer(stemmer, new SimpleTokenizer()); + + +search.tokenizer = new StopWordsTokenizer(new SimpleTokenizer()); + +StopWordsMap.the = false; // Do not treat "the" as a stop word +StopWordsMap.bob = true; // Treat "bob" as a stop word + +search.searchIndex = new UnorderedSearchIndex(); diff --git a/types/js-search/tsconfig.json b/types/js-search/tsconfig.json new file mode 100644 index 0000000000..83ce87381c --- /dev/null +++ b/types/js-search/tsconfig.json @@ -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", + "js-search-tests.ts" + ] +} diff --git a/types/js-search/tslint.json b/types/js-search/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-search/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3d2aeae3119bbca70f3a68454570e456d25374c0 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 1 May 2017 14:03:24 -0700 Subject: [PATCH 019/109] Remove `promise` package (#16030) --- types/promise/index.d.ts | 28 ---------------------------- types/promise/promise-tests.ts | 25 ------------------------- types/promise/tsconfig.json | 22 ---------------------- 3 files changed, 75 deletions(-) delete mode 100644 types/promise/index.d.ts delete mode 100644 types/promise/promise-tests.ts delete mode 100644 types/promise/tsconfig.json diff --git a/types/promise/index.d.ts b/types/promise/index.d.ts deleted file mode 100644 index d51e11de3d..0000000000 --- a/types/promise/index.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Type definitions for promise v7.1.1 -// Project: https://www.promisejs.org/ -// Definitions by: Manuel Rueda -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export as namespace Promise; - -export = Promise; -declare var Promise: Promise.IPromise; - -declare namespace Promise { - export interface IPromise { - new (resolver: (resolve: (value: T) => void, reject: (reason: any) => void) => void): IThenable; - - resolve: (value: T) => IThenable; - reject: (value: T) => IThenable; - all: (array: Array>) => IThenable>; - denodeify: (fn: Function) => (...args: any[]) => IThenable; - nodeify: (fn: Function) => Function; - } - - export interface IThenable { - then(onFulfilled?: (value: T) => IThenable|R, onRejected?: (error: any) => IThenable|R): IThenable; - catch(onRejected?: (error: any) => IThenable|R): IThenable; - done(onFulfilled?: (value: T) => IThenable|R, onRejected?: (error: any) => IThenable|R): IThenable; - nodeify(callback: Function): IThenable; - } -} diff --git a/types/promise/promise-tests.ts b/types/promise/promise-tests.ts deleted file mode 100644 index c90cf4bf5e..0000000000 --- a/types/promise/promise-tests.ts +++ /dev/null @@ -1,25 +0,0 @@ -var prom = new Promise((resolve, reject) => { - resolve(true); -}); - -var prom2 = new Promise((resolve, reject) => { - resolve(true); -}); - -prom.then((val) => { - const b: boolean = val; -}).catch(() => { - -}); - -var prom3 = Promise.all([prom, prom2]); - -prom3.then((resolve: Array) => { - -}); - -function withCallback(arg: any, cb: (e: Error, result: any) => void): void { - cb(null, arg); -} -var prom4 = Promise.denodeify(withCallback); -prom4('test').then(result => result); diff --git a/types/promise/tsconfig.json b/types/promise/tsconfig.json deleted file mode 100644 index 5fc066d3e9..0000000000 --- a/types/promise/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es5" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "promise-tests.ts" - ] -} \ No newline at end of file From 93f85817e11b3c6f803189d6936a2d9c44e4efad Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 1 May 2017 14:04:18 -0700 Subject: [PATCH 020/109] leaflet-markercluster: Rename to "leaflet.markercluster" and convert to module (#16027) --- .../index.d.ts | 12 +++++++----- .../leaflet.markercluster-tests.ts} | 2 ++ .../tsconfig.json | 2 +- .../tslint.json | 0 4 files changed, 10 insertions(+), 6 deletions(-) rename types/{leaflet-markercluster => leaflet.markercluster}/index.d.ts (96%) rename types/{leaflet-markercluster/leaflet-markercluster-tests.ts => leaflet.markercluster/leaflet.markercluster-tests.ts} (98%) rename types/{leaflet-markercluster => leaflet.markercluster}/tsconfig.json (91%) rename types/{leaflet-markercluster => leaflet.markercluster}/tslint.json (100%) diff --git a/types/leaflet-markercluster/index.d.ts b/types/leaflet.markercluster/index.d.ts similarity index 96% rename from types/leaflet-markercluster/index.d.ts rename to types/leaflet.markercluster/index.d.ts index f2323f4573..b6780ec357 100644 --- a/types/leaflet-markercluster/index.d.ts +++ b/types/leaflet.markercluster/index.d.ts @@ -3,10 +3,12 @@ // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as Leaflet from "leaflet"; -declare namespace L { - interface MarkerCluster extends L.Marker { +export = Leaflet; + +declare global { namespace L { + interface MarkerCluster extends Marker { /* * Recursively retrieve all child markers of this cluster. */ @@ -103,7 +105,7 @@ declare namespace L { /* * Function used to create the cluster icon */ - iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon | L.DivIcon); + iconCreateFunction?: ((cluster: MarkerCluster) => Icon | DivIcon); /* * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. @@ -164,4 +166,4 @@ declare namespace L { * Create a marker cluster group, optionally given marker cluster group options. */ function markerClusterGroup(options?: MarkerClusterGroupOptions): MarkerClusterGroup; -} +} } diff --git a/types/leaflet-markercluster/leaflet-markercluster-tests.ts b/types/leaflet.markercluster/leaflet.markercluster-tests.ts similarity index 98% rename from types/leaflet-markercluster/leaflet-markercluster-tests.ts rename to types/leaflet.markercluster/leaflet.markercluster-tests.ts index 73b98586e9..2a2a4969e1 100644 --- a/types/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/types/leaflet.markercluster/leaflet.markercluster-tests.ts @@ -1,3 +1,5 @@ +import L = require("leaflet.markercluster"); + const polylineOptions: L.PolylineOptions = {}; const icon: L.Icon = L.icon({ iconUrl: 'foo' }); diff --git a/types/leaflet-markercluster/tsconfig.json b/types/leaflet.markercluster/tsconfig.json similarity index 91% rename from types/leaflet-markercluster/tsconfig.json rename to types/leaflet.markercluster/tsconfig.json index d5e7d33df8..6cc587aa00 100644 --- a/types/leaflet-markercluster/tsconfig.json +++ b/types/leaflet.markercluster/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "leaflet-markercluster-tests.ts" + "leaflet.markercluster-tests.ts" ] } \ No newline at end of file diff --git a/types/leaflet-markercluster/tslint.json b/types/leaflet.markercluster/tslint.json similarity index 100% rename from types/leaflet-markercluster/tslint.json rename to types/leaflet.markercluster/tslint.json From 774e70493563a14dd39dc327460ac2fd63a43112 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 1 May 2017 14:04:37 -0700 Subject: [PATCH 021/109] selenium-webdriver: Fix Promise errors (#15989) --- types/selenium-webdriver/test/index.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/types/selenium-webdriver/test/index.ts b/types/selenium-webdriver/test/index.ts index c7bae6700c..f325fe6604 100644 --- a/types/selenium-webdriver/test/index.ts +++ b/types/selenium-webdriver/test/index.ts @@ -822,8 +822,8 @@ function TestPromiseModule() { stringPromise = webdriver.promise.createFlow((newFlow: webdriver.promise.ControlFlow) => 'ABC'); let deferred: webdriver.promise.Deferred; - deferred = webdriver.promise.defer(); - deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); stringPromise = deferred.promise; @@ -835,12 +835,12 @@ function TestPromiseModule() { voidPromise = webdriver.promise.fulfilled(); stringPromise = webdriver.promise.fulfilled('abc'); - stringPromise = webdriver.promise.fullyResolved('abc'); + stringPromise = webdriver.promise.fullyResolved('abc'); let bool: boolean = webdriver.promise.isGenerator(() => {}); let isPromise: boolean = webdriver.promise.isPromise('ABC'); - stringPromise = webdriver.promise.rejected('{a: 123}'); + stringPromise = webdriver.promise.rejected('{a: 123}'); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); @@ -935,11 +935,13 @@ function TestDeferred() { function TestPromiseClass() { let controlFlow: webdriver.promise.ControlFlow; let promise: webdriver.promise.Promise; - promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}); - promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); - promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}, controlFlow); + promise = new webdriver.promise.Promise((resolve, reject) => { + resolve(""); + resolve(Promise.resolve("")); + reject(new Error()); + }, controlFlow); - promise = promise.then(); + promise = promise.then(); promise = promise.then((a: string) => 'cde'); promise = promise.then((a: string) => 'cde', (e: any) => {}); promise = promise.then((a: string) => 'cde', (e: any) => 123); From 441bef5f52b71c559df8df67f48dd179191b374e Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 1 May 2017 14:04:53 -0700 Subject: [PATCH 022/109] cucumber: Fix new `--noImplicitAny` error (#15983) --- types/cucumber/cucumber-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 379922d1a7..53ca726230 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -7,7 +7,7 @@ function StepSample() { type HookScenarioResult = cucumber.HookScenarioResult; cucumber.defineSupportCode(function ({setWorldConstructor, defineParameterType, After, Around, Before, registerHandler, Given, When, Then}) { - setWorldConstructor(function ({attach, parameters}) { + setWorldConstructor(function ({attach, parameters}: any) { this.attach = attach; this.parameters = parameters; this.visit = function (url: string, callback: Callback) { @@ -19,7 +19,7 @@ function StepSample() { console.log(scenarioResult.status === "failed"); callback(); }); - + Before({ timeout: 1000 }, function (scenarioResult: HookScenarioResult, callback: Callback) { console.log(scenarioResult.status === "failed"); callback(); @@ -35,7 +35,7 @@ function StepSample() { console.log("After"); callback(); }); - + After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback?: Callback) => { console.log("After"); callback(); @@ -48,7 +48,7 @@ function StepSample() { Given(/^a variable set to (\d+)$/, (x: string) => { console.log("the number is: " + x); }); - + Given(/^a variable set to (\d+)$/, (x: number) => { console.log(typeof x); }); From 3a5fa639424011eba69ae5a407c4af00174e4bd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iker=20P=C3=A9rez=20Brunelli?= Date: Mon, 1 May 2017 23:46:38 +0200 Subject: [PATCH 023/109] Add snekfetch type definitions (#16214) * Add snekfetch typings * Fix linting errors * Remove unsused import * Make interfaces and types available to import --- types/snekfetch/index.d.ts | 126 +++++++++++++++++++++++++++++ types/snekfetch/snekfetch-tests.ts | 12 +++ types/snekfetch/tsconfig.json | 22 +++++ types/snekfetch/tslint.json | 3 + 4 files changed, 163 insertions(+) create mode 100644 types/snekfetch/index.d.ts create mode 100644 types/snekfetch/snekfetch-tests.ts create mode 100644 types/snekfetch/tsconfig.json create mode 100644 types/snekfetch/tslint.json diff --git a/types/snekfetch/index.d.ts b/types/snekfetch/index.d.ts new file mode 100644 index 0000000000..71ef08d9a1 --- /dev/null +++ b/types/snekfetch/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for snekfetch 3.1 +// Project: https://github.com/GusCaplan/snekfetch +// Definitions by: Iker Pérez Brunelli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { ClientRequest } from 'http'; +import { Readable } from 'stream'; + +declare namespace Snekfetch { + interface SnekfetchOptions { + headers?: { [key: string]: any }; + data?: any; + } + + interface Result { + request: ClientRequest; + body: Buffer; + text: string; + ok: boolean; + headers: { [key: string]: any }; + status: number; + statusText: string; + } + + type methods = 'ACL' + | 'BIND' + | 'CHECKOUT' + | 'CONNECT' + | 'COPY' + | 'DELETE' + | 'GET' + | 'HEAD' + | 'LINK' + | 'LOCK' + | 'M-SEARCH' + | 'MERGE' + | 'MKACTIVITY' + | 'MKCALENDAR' + | 'MKCOL' + | 'MOVE' + | 'NOTIFY' + | 'OPTIONS' + | 'PATCH' + | 'POST' + | 'PROPFIND' + | 'PROPPATCH' + | 'PURGE' + | 'PUT' + | 'REBIND' + | 'REPORT' + | 'SEARCH' + | 'SUBSCRIBE' + | 'TRACE' + | 'UNBIND' + | 'UNLINK' + | 'UNLOCK' + | 'UNSUBSCRIBE' + | 'BREW'; +} + +declare class Snekfetch extends Readable { + static METHODS: Snekfetch.methods[]; + static version: string; + + data: any; + request: ClientRequest; + readonly response: Snekfetch.Result | null; + + constructor(method: Snekfetch.methods, url: string, opts?: Snekfetch.SnekfetchOptions); + + static acl(url: string): Snekfetch; + static bind(url: string): Snekfetch; + static checkout(url: string): Snekfetch; + static connect(url: string): Snekfetch; + static copy(url: string): Snekfetch; + static delete(url: string): Snekfetch; + static get(url: string): Snekfetch; + static head(url: string): Snekfetch; + static link(url: string): Snekfetch; + static lock(url: string): Snekfetch; + static msearch(url: string): Snekfetch; + static merge(url: string): Snekfetch; + static mkactivity(url: string): Snekfetch; + static mkcalendar(url: string): Snekfetch; + static mkcol(url: string): Snekfetch; + static move(url: string): Snekfetch; + static notify(url: string): Snekfetch; + static options(url: string): Snekfetch; + static patch(url: string): Snekfetch; + static post(url: string): Snekfetch; + static propfind(url: string): Snekfetch; + static proppatch(url: string): Snekfetch; + static purge(url: string): Snekfetch; + static put(url: string): Snekfetch; + static rebind(url: string): Snekfetch; + static report(url: string): Snekfetch; + static search(url: string): Snekfetch; + static subscribe(url: string): Snekfetch; + static trace(url: string): Snekfetch; + static unbind(url: string): Snekfetch; + static unlink(url: string): Snekfetch; + static unlock(url: string): Snekfetch; + static unsubscribe(url: string): Snekfetch; + static brew(url: string): Snekfetch; + + query(name: string, value: string): Snekfetch; + + set(name: string | { [key: string]: string | string[] }, value?: string | string[]): Snekfetch; + + attach(name: string, data: string | object | Buffer, filename?: string): Snekfetch; + + send(data?: any): Snekfetch; + + then(): Promise; + then(resolver: (res: Snekfetch.Result) => T, rejector?: (err: Error) => any): Promise; + + catch(rejector: (err: Error) => any): Promise; + + end(): Promise; + end(cb: (err: Error | null, res: Snekfetch.Result | Error | null) => T): Promise; +} + +export = Snekfetch; diff --git a/types/snekfetch/snekfetch-tests.ts b/types/snekfetch/snekfetch-tests.ts new file mode 100644 index 0000000000..b05c02628a --- /dev/null +++ b/types/snekfetch/snekfetch-tests.ts @@ -0,0 +1,12 @@ +import * as fs from 'fs'; +import * as snekfetch from 'snekfetch'; + +snekfetch.get('https://s.gus.host/o-SNAKES-80.jpg') + .then(r => fs.writeFile('download.jpg', r.body)); + +snekfetch.get('https://s.gus.host/o-SNAKES-80.jpg') + .pipe(fs.createWriteStream('download.jpg')); + +snekfetch.post('https://httpbin.org/post') + .send({ meme: 'dream' }) + .then(r => console.log(r.body)); diff --git a/types/snekfetch/tsconfig.json b/types/snekfetch/tsconfig.json new file mode 100644 index 0000000000..f07bbc8b66 --- /dev/null +++ b/types/snekfetch/tsconfig.json @@ -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", + "snekfetch-tests.ts" + ] +} diff --git a/types/snekfetch/tslint.json b/types/snekfetch/tslint.json new file mode 100644 index 0000000000..40ebe59923 --- /dev/null +++ b/types/snekfetch/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From ea345679fb124e9a31572ff022be85b2b0e9cb9c Mon Sep 17 00:00:00 2001 From: Mikal Madsen Date: Tue, 2 May 2017 00:19:16 +0200 Subject: [PATCH 024/109] Add Recase typings (#15744) * Add Recase typings * Add relaxed-json type definitions * Update Recase and Relaxed-JSON types as per PR review * Update Recase and Relaxed-JSON types --- types/recase/index.d.ts | 14 +++++++ types/recase/recase-tests.ts | 33 ++++++++++++++++ types/recase/tsconfig.json | 22 +++++++++++ types/recase/tslint.json | 1 + types/relaxed-json/index.d.ts | 16 ++++++++ types/relaxed-json/relaxed-json-tests.ts | 49 ++++++++++++++++++++++++ types/relaxed-json/tsconfig.json | 22 +++++++++++ types/relaxed-json/tslint.json | 1 + 8 files changed, 158 insertions(+) create mode 100644 types/recase/index.d.ts create mode 100644 types/recase/recase-tests.ts create mode 100644 types/recase/tsconfig.json create mode 100644 types/recase/tslint.json create mode 100644 types/relaxed-json/index.d.ts create mode 100644 types/relaxed-json/relaxed-json-tests.ts create mode 100644 types/relaxed-json/tsconfig.json create mode 100644 types/relaxed-json/tslint.json diff --git a/types/recase/index.d.ts b/types/recase/index.d.ts new file mode 100644 index 0000000000..29808f6130 --- /dev/null +++ b/types/recase/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for Recase 1.0 +// Project: https://www.npmjs.com/package/recase +// Definitions by: Mikal Madsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Recase { + camelCopy(orig: any): any; + snakeCopy(orig: any): any; +} +export function create(opts: { + exceptions?: { + [origKey: string]: string; + }; +}): Recase; diff --git a/types/recase/recase-tests.ts b/types/recase/recase-tests.ts new file mode 100644 index 0000000000..fe554ecb4b --- /dev/null +++ b/types/recase/recase-tests.ts @@ -0,0 +1,33 @@ +import * as Recase from 'recase'; +const recase = Recase.create({exceptions: {FOO: 'foo'}}); + +const snake = recase.snakeCopy( + { + FOO: 1, // Exception + abcXyz: { // Normal + _abcXyz: [ // private + {__abcXyz: 1}, // very private + {___abcXyz: 1}, // very very private + ], + }, + }, +); + +const camel = recase.camelCopy( + { + foo: 1, // Exception + abc_xyz: { // Normal + _abc_xyz: [ // private + {__abc_xyz: 1}, // very private + {___abc_xyz: 1}, // very very private + ], + }, + }, +); + +recase.snakeCopy(1); +recase.camelCopy(2); +recase.snakeCopy('a'); +recase.camelCopy('b'); +recase.snakeCopy(['c', '1']); +recase.snakeCopy(['d', '1']); diff --git a/types/recase/tsconfig.json b/types/recase/tsconfig.json new file mode 100644 index 0000000000..fe94c39f52 --- /dev/null +++ b/types/recase/tsconfig.json @@ -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", + "recase-tests.ts" + ] +} diff --git a/types/recase/tslint.json b/types/recase/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/recase/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/relaxed-json/index.d.ts b/types/relaxed-json/index.d.ts new file mode 100644 index 0000000000..7b081d9acf --- /dev/null +++ b/types/relaxed-json/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for relaxed-json 1.0 +// Project: https://github.com/phadej/relaxed-json +// Definitions by: Mikal Madsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Reviver = (this: {}, key: string, value: any) => any; +export function transform(text: string): string; +export function parse(text: string, reviver: Reviver): {}; +export function parse(text: string, opts?: { + reviver?: Reviver, + relaxed?: boolean, + warnings?: boolean, + tolerant?: boolean, + duplicate?: boolean, +}): {}; +export function stringify(obj: any): string; diff --git a/types/relaxed-json/relaxed-json-tests.ts b/types/relaxed-json/relaxed-json-tests.ts new file mode 100644 index 0000000000..dc07398f9f --- /dev/null +++ b/types/relaxed-json/relaxed-json-tests.ts @@ -0,0 +1,49 @@ +import * as RJSON from 'relaxed-json'; + +const relaxedString = ` + { // comment + foo: "bar", // identifier + "arr": [1,2,3,], // trailing comma in array + "single-quoted": 'string', + 'trailing': 4, + }, +`; + +RJSON.transform(relaxedString); + +function revive(key: string, value: any): any { + return typeof value === 'number' + ? value * 2 // return value * 2 for numbers + : value; // return everything else unchanged +} + +RJSON.parse(relaxedString, revive); + +RJSON.parse(relaxedString, { + reviver: revive, + relaxed: true, + warnings: true, + tolerant: true, + duplicate: true, +}); + +RJSON.parse(relaxedString, { + tolerant: false, + duplicate: true, +}); + +RJSON.parse(relaxedString, { + reviver: revive, +}); + +RJSON.parse(relaxedString, {}); + +const parsed = RJSON.parse(relaxedString); +RJSON.stringify(parsed); + +RJSON.stringify({ + foo: 'bar', +}); +RJSON.stringify([1, 2, 3]); +RJSON.stringify(3); +RJSON.stringify('a'); diff --git a/types/relaxed-json/tsconfig.json b/types/relaxed-json/tsconfig.json new file mode 100644 index 0000000000..235aa056fa --- /dev/null +++ b/types/relaxed-json/tsconfig.json @@ -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", + "relaxed-json-tests.ts" + ] +} diff --git a/types/relaxed-json/tslint.json b/types/relaxed-json/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/relaxed-json/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b0a313322970e0107b3899f7ff432413dd8fc0e6 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Mon, 1 May 2017 18:43:32 -0400 Subject: [PATCH 025/109] Ember: Missing optional parameter for `Ember.Helper.helper` function (#16250) Currently, the second `hash` parameter to the closure is not supported, even though it's used in the Ember Documentation for the method: https://github.com/emberjs/ember.js/blob/v2.12.0/packages/ember-glimmer/lib/helper.js#L110-L114 I confirmed in the latest version of Ember.js that this `hash` parameter works, so I believe the types should be updated to support it. --- types/ember/ember-tests.ts | 11 +++++++++++ types/ember/index.d.ts | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/types/ember/ember-tests.ts b/types/ember/ember-tests.ts index 99f00aae6f..4119e1d7ec 100644 --- a/types/ember/ember-tests.ts +++ b/types/ember/ember-tests.ts @@ -105,6 +105,17 @@ App.userController = Em.Object.create({ }) }); +Ember.Helper.helper((params) => { + let cents = params[0]; + return `${cents * 0.01}`; +}); + +Ember.Helper.helper((params, hash) => { + let cents = params[0]; + let currency = hash.currency; + return `${currency}${cents * 0.01}`; +}); + Handlebars.registerHelper('highlight', (property: string, options: any) => new Handlebars.SafeString('' + "some value" + '')); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index f7aedcb7c1..1a8d5455c5 100644 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1137,7 +1137,7 @@ declare namespace Ember { service(name?: string): Service; }; class Helper extends Object { - static helper( h: (a: any) => any): Helper; + static helper( h: (params: any, hash?: any) => any): Helper; compute(params: any[], hash: any): any; recompute(params: any[], hash: any): any; } From 7a49d23bc5ab2f1c3132f3996fd4f77468d200f5 Mon Sep 17 00:00:00 2001 From: Matthias Dailey Date: Mon, 1 May 2017 18:53:28 -0400 Subject: [PATCH 026/109] Add openlayers version 3.x (3.20) (#15923) --- types/openlayers/v3/index.d.ts | 13931 ++++++++++++++++++++++ types/openlayers/v3/openlayers-tests.ts | 765 ++ types/openlayers/v3/tsconfig.json | 28 + 3 files changed, 14724 insertions(+) create mode 100644 types/openlayers/v3/index.d.ts create mode 100644 types/openlayers/v3/openlayers-tests.ts create mode 100644 types/openlayers/v3/tsconfig.json diff --git a/types/openlayers/v3/index.d.ts b/types/openlayers/v3/index.d.ts new file mode 100644 index 0000000000..c9791bc109 --- /dev/null +++ b/types/openlayers/v3/index.d.ts @@ -0,0 +1,13931 @@ +// Type definitions for OpenLayers v3.20.0 +// Project: http://openlayers.org/ +// Definitions by: Olivier Sechet , Matthias Dailey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) + +declare type GlobalObject = Object; + +/** + * @namespace ol + */ +declare module ol { + /** + * The animation static methods are designed to be used with the + * {@link ol.Map#beforeRender} method. For example: + * + * var map = new ol.Map({ ... }); + * var zoom = ol.animation.zoom({ + * resolution: map.getView().getResolution() + * }); + * map.beforeRender(zoom); + * map.getView().setResolution(map.getView().getResolution() * 2); + * + * @namespace ol.animation + */ + module animation { + /** + * Generate an animated transition that will "bounce" the resolution as it + * approaches the final value. + * @param {olx.animation.BounceOptions} options Bounce options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param {olx.animation.PanOptions} options Pan options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param {olx.animation.RotateOptions} options Rotate options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param {olx.animation.ZoomOptions} options Zoom options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + + } + + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + class AssertionError extends Error { + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + constructor(code: number); + + /** + * Error code. The meaning of the code can be found on + * {@link http://openlayers.org/en/latest/errors.html} (replace `latest` with + * the version found in the OpenLayers script's header comment if a version + * other than the latest is used). + * @type {number} + * @api + */ + code: number; + + } + + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + class Attribution { + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @return {string} The attribution HTML. + * @api stable + */ + getHTML(): string; + + } + + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + class Collection extends ol.Object { + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + constructor(opt_array?: T[]); + + /** + * Remove all elements from the collection. + * @api stable + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array.} arr Array. + * @return {ol.Collection.} This collection. + * @api stable + */ + extend(arr: T[]): ol.Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param {function(this: S, T, number, Array.): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @param {S=} opt_this The object to use as `this` in `f`. + * @template S + * @api stable + */ + forEach(f: ((item: T, index: number, array: T[]) => any), opt_this?: S): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array.} Array. + * @api stable + */ + getArray(): T[]; + + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api stable + */ + item(index: number): T; + + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api stable + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + insertAt(index: number, elem: T): void; + + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api stable + */ + pop(): (T); + + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} Length. + * @api stable + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api stable + */ + remove(elem: T): (T); + + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api stable + */ + removeAt(index: number): (T); + + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + setAt(index: number, elem: T): void; + + } + + module Collection { + + type EventType = string; + + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + constructor(type: ol.Collection.EventType, opt_element?: any); + + /** + * The element that is added to or removed from the collection. + * @type {*} + * @api stable + */ + element: any; + + } + } + + /** + * Colors can be defined as a {@link ol.Color} array, or as strings in + * `rgb(r,g,b)` or `rgba(r,g,b,a)` format, or in hex `#rrggbb` or `#rgb` format. + * Color names, like 'red', 'blue' or 'green', may also be used with the + * Canvas renderer. + * + * @namespace ol.color + */ + module color { + /** + * Return the color as an array. This function maintains a cache of calculated + * arrays which means the result should not be modified. + * @param {ol.Color|string} color Color. + * @return {ol.Color} Color. + * @api + */ + function asArray(color: (ol.Color | string)): ol.Color; + + /** + * Return the color as an rgba string. + * @param {ol.Color|string} color Color. + * @return {string} Rgba string. + * @api + */ + function asString(color: (ol.Color | string)): string; + + } + + /** + * An {@link ol.ColorLike} can be a color, gradient or pattern accepted by + * [CanvasRenderingContext2D.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle). + * @namespace ol.colorlike + */ + module colorlike { + /** + * @param {ol.Color|ol.ColorLike} color Color. + * @return {ol.ColorLike} The color as an ol.ColorLike + * @api + */ + function asColorLike(color: (ol.Color | ol.ColorLike)): ol.ColorLike; + + } + + /** + * @namespace ol.control + */ + module control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + class Attribution extends ol.control.Control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + constructor(opt_options?: olx.control.AttributionOptions); + + /** + * Update the attribution element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Attribution} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the attribution is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the attribution should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the attribution according to the passed parameter. Will + * not do anything if the attribution isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Return `true` when the attribution is currently collapsed or `false` + * otherwise. + * @return {boolean} True if the widget is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + } + + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + class Control extends ol.Object { + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + * @return {ol.Map} Map. + * @api stable + */ + getMap(): ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {ol.Map} map Map. + * @api stable + */ + setMap(map: ol.Map): void; + + /** + * This function is used to set a target element for the control. It has no + * effect if it is called after the control has been added to the map (i.e. + * after `setMap` is called on the control). If no `target` is set in the + * options passed to the control constructor and if `setTarget` is not called + * then the control is added to the map's overlay container. + * @param {Element|string} target Target. + * @api + */ + setTarget(target: (Element | string)): void; + + } + + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + class FullScreen extends ol.control.Control { + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.FullScreenOptions); + + } + + /** + * Set of controls included in maps by default. Unless configured otherwise, + * this returns a collection containing an instance of each of the following + * controls: + * * {@link ol.control.Zoom} + * * {@link ol.control.Rotate} + * * {@link ol.control.Attribution} + * + * @param {olx.control.DefaultsOptions=} opt_options Defaults options. + * @return {ol.Collection.} Controls. + * @api stable + */ + function defaults(opt_options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + class MousePosition extends ol.control.Control { + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + constructor(opt_options?: olx.control.MousePositionOptions); + + /** + * Update the mouseposition element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.MousePosition} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return the coordinate format type used to render the current position or + * undefined. + * @return {ol.CoordinateFormatType|undefined} The format to render the current + * position in. + * @observable + * @api stable + */ + getCoordinateFormat(): (ol.CoordinateFormatType); + + /** + * Return the projection that is used to report the mouse position. + * @return {ol.proj.Projection|undefined} The projection to report mouse + * position in. + * @observable + * @api stable + */ + getProjection(): (ol.proj.Projection); + + /** + * Set the coordinate format type used to render the current position. + * @param {ol.CoordinateFormatType} format The format to render the current + * position in. + * @observable + * @api stable + */ + setCoordinateFormat(format: ol.CoordinateFormatType): void; + + /** + * Set the projection that is used to report the mouse position. + * @param {ol.proj.Projection} projection The projection to report mouse + * position in. + * @observable + * @api stable + */ + setProjection(projection: ol.proj.Projection): void; + + } + + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + class OverviewMap extends ol.control.Control { + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + constructor(opt_options?: olx.control.OverviewMapOptions); + + /** + * Update the overview map element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.OverviewMap} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the overview map is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the overview map should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the overview map according to the passed parameter. Will + * not do anything if the overview map isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Determine if the overview map is collapsed. + * @return {boolean} The overview map is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + /** + * Return the overview map. + * @return {ol.Map} Overview map. + * @api + */ + getOverviewMap(): ol.Map; + + } + + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + class Rotate extends ol.control.Control { + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + constructor(opt_options?: olx.control.RotateOptions); + + /** + * Update the rotate control element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Rotate} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + class ScaleLine extends ol.control.Control { + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + constructor(opt_options?: olx.control.ScaleLineOptions); + + /** + * Return the units to use in the scale line. + * @return {ol.control.ScaleLine.Units|undefined} The units to use in the scale + * line. + * @observable + * @api stable + */ + getUnits(): (ol.control.ScaleLine.Units); + + /** + * Update the scale line element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ScaleLine} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Set the units to use in the scale line. + * @param {ol.control.ScaleLine.Units} units The units to use in the scale line. + * @observable + * @api stable + */ + setUnits(units: ol.control.ScaleLine.Units): void; + } + + module ScaleLine { + /** + * @enum {string} + * @api + */ + type Property = string; + + /** + * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, + * `'nautical'`, `'metric'`, `'us'`. + * @enum {string} + */ + type Units = "degrees" | "imperial" | "nautical" | "metric" | "us"; + } + + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + class Zoom extends ol.control.Control { + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomOptions); + + } + + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + class ZoomSlider extends ol.control.Control { + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomSliderOptions); + + /** + * Update the zoomslider element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ZoomSlider} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + class ZoomToExtent extends ol.control.Control { + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomToExtentOptions); + + } + + } + + /** + * @namespace ol.coordinate + */ + module coordinate { + /** + * Add `delta` to `coordinate`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * ol.coordinate.add(coord, [-2, 4]); + * // coord is now [5.85, 51.983333] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {ol.Coordinate} delta Delta. + * @return {ol.Coordinate} The input coordinate adjusted by the given delta. + * @api stable + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a {@link ol.CoordinateFormatType} function that can be used to format + * a {ol.Coordinate} to a string. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(); + * var out = stringifyFunc(coord); + * // out is now '8, 48' + * + * Example with explicitly specifying 2 fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(2); + * var out = stringifyFunc(coord); + * // out is now '7.85, 47.98' + * + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {ol.CoordinateFormatType} Coordinate format. + * @api stable + */ + function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given {@link ol.Coordinate} to a string using the given string + * template. The strings `{x}` and `{y}` in the template will be replaced with + * the first and second coordinate values respectively. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template); + * // out is now 'Coordinate is (8|48).' + * + * Example explicitly specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template, 2); + * // out is now 'Coordinate is (7.85|47.98).' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {string} template A template string with `{x}` and `{y}` placeholders + * that will be replaced by first and second coordinate values. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Formatted coordinate. + * @api stable + */ + function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; + + /** + * Rotate `coordinate` by `angle`. `coordinate` is modified in place and + * returned by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * var rotateRadians = Math.PI / 2; // 90 degrees + * ol.coordinate.rotate(coord, rotateRadians); + * // coord is now [-47.983333, 7.85] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {number} angle Angle in radian. + * @return {ol.Coordinate} Coordinate. + * @api stable + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and + * seconds. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord); + * // out is now '47° 58′ 60″ N 7° 50′ 60″ E' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord, 1); + * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Hemisphere, degrees, minutes and seconds. + * @api stable + */ + function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + /** + * Format a coordinate as a comma delimited string. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord); + * // out is now '8, 48' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord, 1); + * // out is now '7.8, 48.0' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} XY. + * @api stable + */ + function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + } + + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + class DeviceOrientation extends ol.Object { + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + constructor(opt_options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * standard Z axis. + * @observable + * @api + */ + getAlpha(): (number); + + /** + * Rotation around the device x-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar X axis. + * @observable + * @api + */ + getBeta(): (number); + + /** + * Rotation around the device y-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar Y axis. + * @observable + * @api + */ + getGamma(): (number); + + /** + * The heading of the device relative to north (in radians). + * @return {number|undefined} The heading of the device relative to north, in + * radians, normalizing for different browser behavior. + * @observable + * @api + */ + getHeading(): (number); + + /** + * Determine if orientation is being tracked. + * @return {boolean} Changes in device orientation are being tracked. + * @observable + * @api + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param {boolean} tracking The status of tracking changes to alpha, beta and + * gamma. If true, changes are tracked and reported immediately. + * @observable + * @api + */ + setTracking(tracking: boolean): void; + + } + + /** + * Objects that need to clean up after themselves. + * @constructor + */ + class Disposable { + /** + * Objects that need to clean up after themselves. + * @constructor + */ + constructor(); + + } + + /** + * Easing functions for {@link ol.animation}. + * @namespace ol.easing + */ + module easing { + /** + * Start slow and speed up. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the + * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown + * is delayed. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function upAndDown(t: number): number; + + } + + /** + * Applications do not normally create event instances. They register (and + * unregister) event listener functions, which, when called by the library as + * the result of an event being dispatched, are passed event instances as their + * first argument. Listeners can be registered and unregistered on all objects + * descending from {@link ol.Observable}. All event instances have a `target` + * property, which corresponds to the object on which the event was dispatched. + * By default, `this` within the listener also refers to the target, though + * this can be configured in the listener registration function. + * Some classes have their own event type, which return additional + * properties; see the specific event class page for details. + * + * @namespace ol.events + */ + module events { + /** + * @namespace ol.events.condition + */ + module condition { + /** + * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when + * additionally the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt key is pressed. + * @api stable + */ + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise + * (e.g. when additionally the platform-modifier-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt and shift keys are pressed. + * @api stable + */ + function altShiftKeysOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always true. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True. + * @function + * @api stable + */ + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a `click` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `click` event. + * @api stable + */ + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always false. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} False. + * @function + * @api stable + */ + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the browser event is a `pointermove` event, `false` + * otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the browser event is a `pointermove` event. + * @api + */ + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `singleclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `singleclick` event. + * @api stable + */ + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `dblclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `dblclick` event. + * @api stable + */ + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is + * pressed. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True only if there no modifier keys are pressed. + * @api stable + */ + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the platform-modifier-key (the meta-key on Mac, + * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally + * the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the platform modifier key is pressed. + * @api stable + */ + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when + * additionally the alt-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the shift key is pressed. + * @api stable + */ + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the target element is not editable, i.e. not a ``-, + * `