diff --git a/notNeededPackages.json b/notNeededPackages.json index e076cba36b..48e2c337d0 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -378,6 +378,12 @@ "sourceRepoURL": "https://github.com/elitechance/lambda-phi", "asOfVersion": "1.0.1" }, + { + "libraryName": "left-pad", + "typingsPackageName": "left-pad", + "sourceRepoURL": "https://github.com/stevemao/left-pad", + "asOfVersion": "1.2.0" + }, { "libraryName": "Linq.JS", "typingsPackageName": "linq", @@ -576,6 +582,12 @@ "sourceRepoURL": "https://github.com/gpbl/react-day-picker", "asOfVersion": "5.3.0" }, + { + "libraryName": "react-native-elements", + "typingsPackageName": "react-native-elements", + "sourceRepoURL": "https://github.com/react-native-training/react-native-elements", + "asOfVersion": "0.18.0" + }, { "libraryName": "realm", "typingsPackageName": "realm", diff --git a/types/add-zero/add-zero-tests.ts b/types/add-zero/add-zero-tests.ts new file mode 100644 index 0000000000..ac0509d26d --- /dev/null +++ b/types/add-zero/add-zero-tests.ts @@ -0,0 +1,3 @@ +import addZero from "add-zero"; + +addZero(5, 2); diff --git a/types/add-zero/index.d.ts b/types/add-zero/index.d.ts new file mode 100644 index 0000000000..907364a62d --- /dev/null +++ b/types/add-zero/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for add-zero 1.0 +// Project: https://github.com/rafaelrinaldi/add-zero#readme +// Definitions by: Giles Roadnight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function addZero(value: string | number, digits?: number): string; diff --git a/types/add-zero/tsconfig.json b/types/add-zero/tsconfig.json new file mode 100644 index 0000000000..e71d235cdf --- /dev/null +++ b/types/add-zero/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "add-zero-tests.ts" + ] +} diff --git a/types/left-pad/tslint.json b/types/add-zero/tslint.json similarity index 100% rename from types/left-pad/tslint.json rename to types/add-zero/tslint.json diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index 1786b07af7..0814b0fc03 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -121,12 +121,12 @@ let _algoliaQueryParameters: AlgoliaQueryParameters = { disableTypoToleranceOnAttributes: '', aroundLatLng: '', aroundLatLngViaIP: '', - aroundRadius: '', + aroundRadius: 0, aroundPrecision: 0, minimumAroundRadius: 0, - insideBoundingBox: '', + insideBoundingBox: [[0]], queryType: '', - insidePolygon: '', + insidePolygon: [[0]], removeWordsIfNoResults: '', advancedSyntax: false, optionalWords: [''], diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index f068fc4e22..49e66d2b59 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -49,6 +49,9 @@ declare namespace algoliasearch { */ params: string; } + interface AlgoliaMultiResponse { + results: AlgoliaResponse[]; + } /* Interface for the algolia client object */ @@ -71,8 +74,8 @@ declare namespace algoliasearch { indexName: string; query: string; params: AlgoliaQueryParameters; - }, - cb: (err: Error, res: any) => void + }[], + cb: (err: Error, res: AlgoliaMultiResponse) => void ): void; /** * Query on multiple index @@ -84,7 +87,7 @@ declare namespace algoliasearch { indexName: string; query: string; params: AlgoliaQueryParameters; - }): Promise; + }[]): Promise; /** * clear browser cache * https://github.com/algolia/algoliasearch-client-js#cache @@ -319,8 +322,8 @@ declare namespace algoliasearch { getLogs(options: LogsOptions): Promise; } /** - * Interface for the index algolia object - */ + * Interface for the index algolia object + */ interface AlgoliaIndex { /** * Gets a specific object @@ -783,7 +786,7 @@ declare namespace algoliasearch { * @param err() error callback * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search */ - search(params: AlgoliaQueryParameters): Promise; + search(params: AlgoliaQueryParameters): Promise; /** * Search in an index * @param params query parameter @@ -793,7 +796,7 @@ declare namespace algoliasearch { */ search( params: AlgoliaQueryParameters, - cb: (err: Error, res: any) => void + cb: (err: Error, res: AlgoliaResponse) => void ): void; /** * Search in an index @@ -809,8 +812,7 @@ declare namespace algoliasearch { }: { facetName: string; facetQuery: string; - } & AlgoliaQueryParameters - ): Promise; + } & AlgoliaQueryParameters): Promise; /** * Search in an index * @param params query parameter @@ -1071,8 +1073,8 @@ Interface describing options available for gettings the logs type?: string; } /** - * Describe the action object used for batch operation - */ + * Describe the action object used for batch operation + */ interface AlgoliaAction { /** * Type of the batch action @@ -1098,8 +1100,8 @@ Interface describing options available for gettings the logs body: {}; } /** - * Describes the option used when creating user key - */ + * Describes the option used when creating user key + */ interface AlgoliaApiKeyOptions { /** * Add a validity period. The key will be valid for a specific period of time (in seconds). @@ -1364,8 +1366,8 @@ Interface describing options available for gettings the logs } /** - * Describes the settings available for configure your index - */ + * Describes the settings available for configure your index + */ interface AlgoliaIndexSettings { /** * The list of attributes you want index @@ -1770,7 +1772,7 @@ Interface describing options available for gettings the logs * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area * https://github.com/algolia/algoliasearch-client-js#aroundradius */ - aroundRadius?: any; + aroundRadius?: number | 'all'; /** * Control the precision of a geo search * default: null @@ -1788,7 +1790,7 @@ Interface describing options available for gettings the logs * default: null * https://github.com/algolia/algoliasearch-client-js#insideboundingbox */ - insideBoundingBox?: string; + insideBoundingBox?: number[][]; /** * Selects how the query words are interpreted * default: 'prefixLast' @@ -1803,7 +1805,7 @@ Interface describing options available for gettings the logs * defauly: '' * https://github.com/algolia/algoliasearch-client-js#insidepolygon */ - insidePolygon?: string; + insidePolygon?: number[][]; /** * This option is used to select a strategy in order to avoid having an empty result page * default: 'none' diff --git a/types/amcharts/index.d.ts b/types/amcharts/index.d.ts index 0dae492a76..b8c180d20a 100644 --- a/types/amcharts/index.d.ts +++ b/types/amcharts/index.d.ts @@ -1652,6 +1652,727 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val zoomToIndexes(start: Date, end: Date): void; } + // AmAngularGauge Extension for AmChart to create gauge charts. + class AmAngularGauge extends AmChart { + /** When enabled, chart adds aria-label attributes to columns, bullets or map objects. You can control values of these labels using properties like accessibleLabel of AmGraph. Note, not all screen readers support these tags. We tested this mostly with NVDA Screen reader. WAI-ARIA is now official W3 standard, so in future more readers will handle this well. We will be improving accessibility on our charts, so we would be glad to hear your feedback. + @default true + */ + accessible: boolean; + + /** Description which will be added to node of SVG element. Most of the screen readers will read this description. */ + accessibleDescription: string; + + /** Description which is added to of a SVG element. Some of the screen readers will read this description. */ + accessibleTitle: string; + + /** Specifies, if class names should be added to chart elements. + @default false + */ + addClassNames: boolean; + + /** Uses the whole space of the canvas to draw the gauge. + @default true + */ + adjustSize: boolean; + + /** Array of Labels. Example of label object, with all possible properties: + {"x": 20, "y": 20, "text": "this is label", "align": "left", "size": 12, "color": "#CC0000", "alpha": 1, "rotation": 0, "bold": true, "url": "http://www.amcharts.com"} + @default [] + */ + allLabels: [Label] + + /** Array of arrows. */ + arrows: [GaugeArrow]; + + /** If you set it to true the chart will automatically monitor changes of display style of chart’s container (or any of it’s parents) and will render chart correctly if it is changed from none to block. We recommend setting it to true if you change this style at a run time, as it affects performance a bit. + @default false + */ + autoDisplay: boolean; + + /** Set this to false if you don't want chart to resize itself whenever its parent container size changes. + @default true + */ + autoResize: boolean; + + /** If you set it to true and your chart div (or any of the parent div) has css scale applied, the chart will position mouse at a correct position. Default value is false because this operation consumes some CPU and quite a few people are using css transfroms. + @default false + */ + autoTransform: boolean; + + /** Array of axes. + @default [GaugeAxis] + */ + axes: [GaugeAxis]; + + /** Opacity of background. Set it to >0 value if you want backgroundColor to work. However we recommend changing div's background-color style for changing background color. + @default 0 + */ + backgroundAlpha: number; + + /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. + @default #FFFFFF + */ + backgroundColor: string; + + /** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. + @default AmBalloon + */ + balloon: AmBalloon; + + /** Opacity of chart's border. Value range is 0 - 1. + @default 0 + */ + borderAlpha: number; + + /** Color of chart's border. You should set borderAlpha >0 in order border to be visible. We recommend setting border color directly on a chart's DIV instead of using this property. + @default #000000 + */ + borderColor: string; + + /** This prefix is added to all class names which are added to all visual elements of a chart in case addClassNames is set to true. + @default amcharts + */ + classNamePrefix: string; + + /** In case you use gauge to create a clock, set this to true. + @default false + */ + clockWiseOnly: boolean; + + /** Text color. + @default #000000 + */ + color: string; + + /** Non-commercial version only. Specifies position of link to amCharts site. Allowed values are: top-left, top-right, bottom-left and bottom-right. + @default 'top - left' + */ + creditsPosition: string; + + /** A config object for Data Loader plugin. Please refer to the following page for more information. */ + dataLoader: Object; + + /** Array of data objects, for example: [{country:"US", value:524},{country:"UK", value:624},{country:"Lithuania", value:824}]. You can have any number of fields and use any field names. In case of AmMap, data provider should be MapData object. + + The data set data. + + Important: if you are using date/time-based category axis, the data points needs to come pre-ordered in ascending order. Data with incorrect order might result in visual and functional glitches on the chart. */ + dataProvider: [Object]; + + /** Decimal separator. + @default . + */ + decimalSeparator: string; + + /** Using this property you can add any additional information to SVG, like SVG filters or clip paths. The structure of this object should be identical to XML structure of a object you are adding, only in JSON format. */ + defs: Object; + + /** Export config. Specifies how export to image/data export/print/annotate menu will look and behave. You can find a lot of examples in amcharts/plugins/export folder. More details can be found here. */ + export: ExportSettings; + + /** Gauge face opacity. + @default 0 + */ + faceAlpha: number; + + /** Gauge face border opacity. + @default 0 + */ + faceBorderAlpha: number; + + /** Gauge face border color. + @default #555555 + */ + faceBorderColor: string; + + /** Gauge face border width. + @default 1 + */ + faceBorderWidth: number; + + /** Gauge face color, requires faceAlpha > 0 + @default #FAFAFA + */ + faceColor: string; + + /** Gauge face image-pattern. + Example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4} + fontFamily String Verdana Font family. + fontSize Number 11 Font size. */ + facePattern: Object; + + /** Gauge's horizontal position in pixel, origin is the center. Centered by default. */ + gaugeX: number; + + /** Gauge's vertical position in pixel, origin is the center. Centered by default. */ + gaugeY: number; + + /** If you set this to true, the lines of the chart will be distorted and will produce hand-drawn effect. Try to adjust chart.handDrawScatter and chart.handDrawThickness properties for a more scattered result. + @default false + */ + handDrawn: boolean; + + /** Defines by how many pixels hand-drawn line (when handDrawn is set to true) will fluctuate. + @default 2 + */ + handDrawScatter: number; + + /** Defines by how many pixels line thickness will fluctuate (when handDrawn is set to true). + @default 1 + */ + handDrawThickness: number; + + /** Time, in milliseconds after which balloon is hidden if the user rolls-out of the object. Might be useful for AmMap to avoid balloon flickering while moving mouse over the areas. Note, this is not duration of fade-out. Duration of fade-out is set in AmBalloon class. + @default 150 + */ + hideBalloonTime: number; + + /** Allows changing language easily. Note, you should include language js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de"; Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */ + language: string; + + /** Legend of a chart. */ + legend: AmLegend; + + /** Read-only. Reference to the div of the legend. */ + legendDiv: HTMLElement; + + /** You can add listeners of events using this property. Example: listeners = [{"event":"dataUpdated", "method":handleEvent}]; + @default [Object] + */ + listeners: [Object]; + + /** Bottom spacing between chart and container. + @default 10 + */ + marginBottom: number; + + /** Left-hand spacing between chart and container. + @default 10 + */ + marginLeft: number; + + /** Right-hand spacing between chart and container. + @default 10 + */ + marginRight: number; + + /** Top spacing between chart and container. + @default 10 + */ + marginTop: number; + + /** Minimum radius of a gauge. + @default 10 + */ + minRadius: number; + + /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true, otherwise - false. + @default true + */ + panEventsEnabled: boolean; + + /** Specifies absolute or relative path to amCharts files, i.e."amcharts/". (where all.js files are located) + If relative URLs are used, they will be relative to the current web page, displaying the chart. + You can also set path globally, using global JavaScript variable AmCharts_path.If this variable is set, and "path" is not set in chart config, the chart will assume the path from the global variable.This allows setting amCharts path globally.I.e.: + var AmCharts_path = "/libs/amcharts/"; + "path" parameter will be used by the charts to locate it's files, like images, plugins or patterns. + @default 'amcharts/' + */ + path: string; + + /** Specifies path to the folder where images like resize grips, lens and similar are. + + IMPORTANT: Since V3.14.12, you should use "path" to point to amCharts directory instead. The "pathToImages" will be automatically set and does not need to be in the chart config, unless you keep your images separately from other amCharts files. */ + pathToImages: string; + + /** Precision of percent values. -1 means percent values won't be rounded at all and show as they are. + @default 2 + */ + percentPrecision: number; + + /** Precision of values. -1 means values won't be rounded at all and show as they are. + @default -1 + */ + precision: number; + + /**Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc.Prefixes are used on value axes and in the legend.To enable prefixes, set usePrefixes property to true. + @default [{ "number": 1e+3, "prefix": "k" }, { "number": 1e+6, "prefix": "M" }, { "number": 1e+9, "prefix": "G" }, { "number": 1e+12, "prefix": "T" }, { "number": 1e+15, "prefix": "P" }, { "number": 1e+18, "prefix": "E" }, { "number": 1e+21, "prefix": "Z" }, { "number": 1e+24, "prefix": "Y" }] + */ + prefixesOfBigNumbers: [Object]; + + /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc.Prefixes are used on value axes and in the legend.To enable prefixes, set usePrefixes property to true. + @default [{ "number": 1e-24, "prefix": "y" }, { "number": 1e-21, "prefix": "z" }, { "number": 1e-18, "prefix": "a" }, { "number": 1e-15, "prefix": "f" }, { "number": 1e-12, "prefix": "p" }, { "number": 1e-9, "prefix": "n" }, { "number": 1e-6, "prefix": "μ" }, { "number": 1e-3, "prefix": "m" }] + */ + prefixesOfSmallNumbers: [Object]; + + /** If processTimeout is > 0, 1000 data items will be parsed at a time, then the chart will make pause and continue parsing data until it finishes. + @default 1000 + */ + processCount: number; + + /** If you set it to 1 millisecond or some bigger value, chart will be built in chunks instead of all at once. This is useful if you work with a lot of data and the initial build of the chart takes a lot of time, which freezes the whole web application by not allowing other processes to do their job while the chart is busy. + @default 0 + */ + processTimeout: number; + + /** A config object for Responsive plugin. Please refer to the following page for more information. */ + responsive: Object + + /** Duration of arrow animation. + @default 1 + */ + startDuration: number; + + /** Transition effect of the arrows, possible effects: easeOutSine, easeInSine, elastic, bounce. + @default easeInSine + */ + startEffect: string; + + /** Charts will use SVG icons (some are loaded from images folder and some are drawn inline) if browser supports SVG. his makes icons look good on retina displays on all resolutions. + @default true + */ + svgIcons: boolean; + + /** Charts which require gestures like swipe (charts with scrollbar/cursor) or pinch (maps) used to prevent regular page scrolling and could result page to stick to the same spot if the chart occupied whole screen. Now, in order these gestures to start working user has to touch the chart/maps once. Regular touch events like touching on the bar/slice/map area do not require the first tap and will show balloons and perform other tasks as usual. If you have a map or chart which occupies full screen and your page does not require scrolling, set tapToActivate to false – this will bring old behavior back. + @default true + */ + tapToActivate: boolean; + + /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. + @default none + */ + theme: string; + + /** Thousands separator. + @default , + */ + thousandsSeparator: string; + + /** Array of Title objects. + @default [] + */ + titles: [Title]; + + /** If you set it to 200 (milliseconds) or so, the chart will fire clickGraphItem or clickSlice (AmSlicedChart) or clickMapObject only if user holds his/her finger for 0.2 seconds (200 ms) on the column/bullet/slice/map object. + @default 0 + */ + touchClickDuration: number; + + /** Type of a chart. Required when creating chart using JSON. Possible types are: serial, pie, xy, radar, funnel, gauge, map, gantt, stock. */ + type: string; + + /** If true, prefixes will be used for big and small numbers.You can set arrays of prefixes via prefixesOfSmallNumbers and prefixesOfBigNumbers properties. + @default false + */ + usePrefixes: boolean; + + /** Read-only. Indicates current version of a script. */ + version: string; + + /** Adds arrow to the chart. */ + addArrow(arrow: GaugeArrow): void; + + /** Adds axis to angular gauge. */ + addAxis(axis: GaugeAxis): void; + + /** Adds a label on a chart. You can use it for labeling axes, adding chart title, etc. x and y coordinates can be set in number, percent, or a number with ! in front of it - coordinate will be calculated from right or bottom instead of left or top. */ + addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string): void; + + /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) */ + addLegend(legend: AmLegend, legendDivId?: string): void; + /** Adds a legend to the chart. + By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. + (NOTE: This method will not work on StockPanel.) + @param legend + @param legendDiv - Legend div (optional). + */ + addLegend(legend: AmLegend, legendDiv: HTMLElement): void; + + /** Adds event listener to the object. */ + addListener(type: string, handler: Function): void; + + /** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. */ + addTitle(text: string, size: number, color: string, alpha: number, bold: boolean): void; + + /** Clears the chart area, intervals, etc. */ + clear(): void; + + /** Removes all labels added to the chart. */ + clearLabels(): void; + + /** Use this method to force the chart to resize to it's current container size. */ + invalidateSize(): void; + + /** This method allows to create charts with a single config. */ + makeChart(container: string, config: any, delay: number): AmChart; + + /** Removes arrow from the chart. */ + removeArrow(arrow: GaugeArrow): void; + + /** Removes axis from the chart. */ + removeAxis(axis: GaugeAxis): void; + + /** Removes chart's legend. */ + removeLegend(): void; + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any): void; + + /** This method should be called after data in your data provider changed or a new array was set to dataProvider. After calling this method the chart will parse data and redraw. */ + validateData(): void; + + /** This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called.Both attributes, validateData and skipEvents are optional (false by default). */ + validateNow(): void; + + /** Adds chart to the specified DIV. + @param container DIV object which will hold the chart. */ + write(container: HTMLElement): void; + /** Adds chart to the specified DIV. + @param container Id of a DIV which will hold the chart. */ + write(container: string): void; + } + + class GaugeArrow { + /** Opacity of an arrow. + @default 1 + */ + alpha: number; + + /** Axis of the arrow. You can use reference to the axis or id of the axis. If you don't set any axis, the first axis of a chart will be used. + @default GaugeAxis + */ + axis: GaugeAxis + + /** Opacity of arrow border. + @default 1 + */ + borderAlpha: number; + + /** In case you need the arrow to rotate only clock-wise, set this property to true. + @default false + */ + clockWiseOnly: boolean; + + /** Color of an arrow. + @default #000000 + */ + color: string; + + /** Unique id of an arrow. */ + id: string; + + /** Inner radius of an arrow. + @default 0 + */ + innerRadius: any; + + /** Opacity of a nail, holding the arrow. + @default 1 + */ + nailAlpha: number; + + /** Opacity of nail border. + @default 0 + */ + nailBorderAlpha: number; + + /** Thickness of nail border. + @default 1 + */ + nailBorderThickness: number; + + /** Radius of a nail, holding the arrow. + @default 8 + */ + nailRadius: number; + + /** Radius of an arrow. + @default '90%' + */ + radius: any; + + /** Width of arrow root. + @default 8 + */ + startWidth: number; + + /** Value to which the arrow should point at. */ + value: number; + + /** Sets value for the arrow. Arrow will animate to this value if you do it after chart is written to it's container. */ + setValue(value: number): void; + } + + class GaugeAxis { + /** Axis opacity. + @default 1 + */ + axisAlpha: number; + + /** Axis color. + @default #000000 + */ + axisColor: string; + + /** Thickness of the axis outline. + @default 1 + */ + axisThickness: number; + + /** Opacity of band fills. + @default 1 + */ + bandAlpha: number; + + /** Example: [-0.2, 0, -0.2]. Will make bands to be filled with color gradients. Negative value means the color will be darker than the original, and positive number means the color will be lighter. + @default [] + */ + bandGradientRatio: [number]; + + /** Opacity of band outlines. + @default 0 + */ + bandOutlineAlpha: number; + + /** Color of band outlines. + @default #000000 + */ + bandOutlineColor: string; + + /** Thickness of band outlines. + @default 0 + */ + bandOutlineThickness: number; + + /** Array of bands - GaugeBand objects. Bands are used to draw color fills between specified values. */ + bands: [GaugeBand]; + + /** Text displayed below the axis center. */ + bottomText: string; + + /** Specifies if text should be bold. + @default true + */ + bottomTextBold: boolean; + + /** Bottom text color. */ + bottomTextColor: string; + + /** Font size of bottom text. */ + bottomTextFontSize: number; + + /** Y offset of bottom text. + @default 0 + */ + bottomTextYOffset: number; + + /** X position of the axis, relative to the center of the gauge. + @default '0%' + */ + centerX: any; + + /** Y position of the axis, relative to the center of the gauge. + @default '0%' + */ + centerY: any; + + /** Specifies labels color of the axis. */ + color: string + + /** Axis end angle. Valid values are from - 180 to 180. + @default 120 + */ + endAngle: number; + + /** Axis end (max) value */ + endValue: number; + + /** Font size for axis labels. */ + fontSize: number; + + /** Number of grid lines. Note, GaugeAxis doesn't adjust gridCount, so you should check your values and choose a proper gridCount which would result grids at round numbers. + @default 5 + */ + gridCount: number; + + /** Specifies if grid should be drawn inside or outside the axis. + @default true + */ + gridInside: boolean; + + /** Unique id of an axis. */ + id: any; + + /** Specifies if labels should be placed inside or outside the axis. + @default true + */ + inside: boolean; + + /** Frequency of labels. + @default 1 + */ + labelFrequency: number; + + /** You can use this function to format axis labels. This function is called and value is passed as a attribute: labelFunction(value); */ + labelFunction: Function; + + /** Distance from axis to the labels. + @default 15 + */ + labelOffset: number; + + /** Specifies if labels on the axis should be shown. + @default true + */ + labelsEnabled: boolean; + + /** You can add listeners of events using this property. Example: listeners = [{"event":"clickBand", "method":handleClick}]; */ + listeners: Object[]; + + /** Interval, at which minor ticks should be placed. */ + minorTickInterval: number; + + /** Length of a minor tick. + @default 5 + */ + minorTickLength: number + + /** Axis radius. + @default '95%' + */ + radius: any; + + /** Specifies if the first label should be shown. + @default true + */ + showFirstLabel: boolean; + + /** Specifies if the last label should be shown. + @default true + */ + showLastLabel: boolean; + + /** Axis start angle. Valid values are from - 180 to 180. + @default -120 + */ + startAngle: number; + + /** Axis start (min) value. + @default 0 + */ + startValue: number; + + /** Opacity of axis ticks. + @default 1 + */ + tickAlpha: number; + + /** Color of axis ticks. + @default #555555 + */ + tickColor: string; + + /** Length of a major tick. + @default 10 + */ + tickLength: number; + + /** Tick thickness. + @default 1 + */ + tickThickness: number; + + /** Text displayed above the axis center. */ + topText: string + + /** Specifies if text should be bold. + @default true + */ + topTextBold: boolean; + + /** Color of top text. */ + topTextColor: string + + /** Font size of top text. */ + topTextFontSize: number + + /** Y offset of top text. + @default 0 + */ + topTextYOffset: number; + + /** A string which can be placed next to axis labels. */ + unit: string; + + /** Position of the unit. + @default right + */ + unitPosition: string; + + /** Specifies if small and big numbers should use prefixes to make them more readable. + @default false + */ + usePrefixes: boolean; + + /** Interval, at which ticks with values should be placed. */ + valueInterval: number; + + /** Adds event listener to the object. */ + addListener(type: string, handler: any); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + + /** Sets bottom text. */ + setBottomText(text: string); + + /** Sets top text. */ + setTopText(textstring); + + /** Returns angle of the value. */ + value2angle(value: number); + } + + class GaugeBand { + /** Opacity of band fill. Will use axis.bandAlpha if not set any. */ + alpha: number; + + /** When rolled-over, band will display balloon if you set some text for this property. */ + balloonText: string; + + /** Color of a band. */ + color: string; + + /** End value of a fill. */ + endValue: number + + /** Example: [-0.2, 0, -0.2]. Will make bands to be filled with color gradients. Negative value means the color will be darker than the original, and positive number means the color will be lighter. + @default [] + */ + gradientRatio: [number]; + + /** Unique id of a band. */ + id: string; + + /** Inner radius of a band. If not set any, the band will end with the end of minor ticks. Set 0 if you want the band to be drawn to the axis center. */ + innerRadius: any; + + /** Band radius. If not set any, the band will start with the axis outline. */ + radius: any; + + /** Start value of a fill. */ + startValue: number; + + /** Gauge band can be clickable and can lead to some page. */ + url: string; + + /** Sets end value for the band. */ + setEndValue(value); + + /** Sets start value for the band. */ + setStartValue(value); + } + class PeriodSelector { /** Date format of date input fields. Check [[http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html DD-MM-YYYY */ dateFormat: string; diff --git a/types/appdmg/appdmg-tests.ts b/types/appdmg/appdmg-tests.ts new file mode 100644 index 0000000000..47800d622f --- /dev/null +++ b/types/appdmg/appdmg-tests.ts @@ -0,0 +1,47 @@ +import appdmg = require("appdmg"); +import { Options, Specification, SpecificationOptions } from "appdmg"; + +const proc = appdmg({ + target: "/foo/bar.dmg", + basepath: "/baz", + specification: { + title: "Happy", + icon: "happy.icns", + background: "happy.tiff", + format: "UDBZ", + "icon-size": 98, + contents: [ + { + x: 405, + y: 150, + type: "link", + path: "/Applications" + }, + { + x: 127, + y: 150, + type: "file", + path: "/foo/bar.app" + } + ] + } +}); + +proc.on("progress", info => { + if (info.type === "step-begin") { + process.stdout.write(`${info.title}... `); + } + + if (info.type === "step-end") { + process.stdout.write(`${info.status}\n`); + } +}); + +proc.on("finish", () => { + console.log('Installer was created successfully!'); +}); + +proc.on("error", (err) => { + console.error('Installer could not be created', err); + process.exit(1); +}); diff --git a/types/appdmg/index.d.ts b/types/appdmg/index.d.ts new file mode 100644 index 0000000000..2e23009f44 --- /dev/null +++ b/types/appdmg/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for appdmg 0.5 +// Project: https://github.com/LinusU/node-appdmg#readme +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace appdmg { + interface Progress { + current: number; + total: number; + type: "step-begin" | "step-end"; + title: string; + status: "ok" | "skip" | "fail"; + } + + interface EventEmitter extends NodeJS.EventEmitter { + on(event: "progress", listener: (info: Progress) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "error", listener: (err: any) => void): this; + } + + interface SpecificationOptions { + app: string; + background: string; + icon: string; + iconSize: number; + title: string; + } + + interface SpecificationWindow { + position?: { x: number; y: number }; + size?: { width: number; height: number }; + } + + interface SpecificationContents { + x: number; + y: number; + type: "link" | "file" | "position"; + path: string; + name?: string; + } + + interface SpecificationCodeSign { + "signing-identity": string; + identifier?: string; + } + + interface Specification { + title: string; + icon?: string; + background?: string; + "background-color"?: string; + "icon-size"?: number; + window?: SpecificationWindow; + format: "UDRW" | "UDRO" | "UDCO" | "UDZO" | "UDBZ" | "ULFO"; + contents: SpecificationContents[]; + "code-sign"?: SpecificationCodeSign; + } + + interface Options { + target: string; + basepath: string; + specification: Specification; + } +} + +declare function appdmg(options?: appdmg.Options): appdmg.EventEmitter; + +export = appdmg; diff --git a/types/appdmg/tsconfig.json b/types/appdmg/tsconfig.json new file mode 100644 index 0000000000..f4ca0f95c5 --- /dev/null +++ b/types/appdmg/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "appdmg-tests.ts" + ] +} diff --git a/types/react-native-elements/tslint.json b/types/appdmg/tslint.json similarity index 100% rename from types/react-native-elements/tslint.json rename to types/appdmg/tslint.json diff --git a/types/atom-keymap/index.d.ts b/types/atom-keymap/index.d.ts index 1d67a20ba2..3660fff3f4 100644 --- a/types/atom-keymap/index.d.ts +++ b/types/atom-keymap/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/atom-keymap // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { Disposable } from "event-kit"; diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index e0699463b1..6ea7b9ae1f 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -844,9 +844,12 @@ function testDock() { } // Emitter ==================================================================== +interface TestEmissions { + "test-event": string; +} + function testEmitter() { emitter = new Atom.Emitter(); - emitter.clear(); emitter.dispose(); @@ -858,6 +861,27 @@ function testEmitter() { // Event Emission emitter.emit("test-event"); emitter.emit("test-event", 42); + + // Optional Value Emitter + const optEmitter = new Atom.Emitter<{ "test-event": string }>(); + optEmitter.emit("test-event"); + optEmitter.emit("test-event", "test"); + optEmitter.on("test-event", value => { + str = value ? value : ""; + }); + + // Required Value Emitter + const reqEmitter = new Atom.Emitter<{}, TestEmissions>(); + reqEmitter.on("test-event", value => { + str = value; + }); + reqEmitter.emit("test-event", "test"); + + // Mixed Value Emitter + const mixedEmitter = new Atom.Emitter<{ "t1": "test" }, { "t2": "test" }>(); + mixedEmitter.emit("t1"); + mixedEmitter.emit("t1", "test"); + mixedEmitter.emit("t2", "test"); } // File ======================================================================= @@ -2939,7 +2963,7 @@ function testTooltipManager() { subscription = atom.tooltips.add(element, { class: "test-class" }); subscription = atom.tooltips.add(element, { placement: "top" }); - subscription = atom.tooltips.add(element, { placement: () => "left" }); + subscription = atom.tooltips.add(element, { placement: () => "auto left" }); subscription = atom.tooltips.add(element, { trigger: "click" }); subscription = atom.tooltips.add(element, { delay: { hide: 42, show: 42 }}); diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 2a13373b7d..4adac61dc1 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -717,7 +717,9 @@ export class Disposable implements DisposableLike { * Utility class to be used when implementing event-based APIs that allows * for handlers registered via ::on to be invoked with calls to ::emit. */ -export class Emitter implements DisposableLike { +// tslint:disable-next-line:no-any +export class Emitter + implements DisposableLike { /** Construct an emitter. */ constructor(); @@ -729,27 +731,47 @@ export class Emitter implements DisposableLike { // Event Subscription /** Registers a handler to be invoked whenever the given event is emitted. */ - on(eventName: T, handler: (value?: Emissions[T]) => void): - Disposable; + on(eventName: T, handler: (value?: + OptionalEmissions[T]) => void): Disposable; + /** Registers a handler to be invoked whenever the given event is emitted. */ + on(eventName: T, handler: (value: + RequiredEmissions[T]) => void): Disposable; /** * Register the given handler function to be invoked the next time an event * with the given name is emitted via ::emit. */ - once(eventName: T, handler: (value?: Emissions[T]) => void): - Disposable; + once(eventName: T, handler: (value?: + OptionalEmissions[T]) => void): Disposable; + /** + * Register the given handler function to be invoked the next time an event + * with the given name is emitted via ::emit. + */ + once(eventName: T, handler: (value: + RequiredEmissions[T]) => void): Disposable; /** * Register the given handler function to be invoked before all other * handlers existing at the time of subscription whenever events by the * given name are emitted via ::emit. */ - preempt(eventName: T, handler: (value?: Emissions[T]) => void): - Disposable; + preempt(eventName: T, handler: (value?: + OptionalEmissions[T]) => void): Disposable; + /** + * Register the given handler function to be invoked before all other + * handlers existing at the time of subscription whenever events by the + * given name are emitted via ::emit. + */ + preempt(eventName: T, handler: (value: + RequiredEmissions[T]) => void): Disposable; // Event Emission /** Invoke the handlers registered via ::on for the given event name. */ - emit(eventName: T, value?: Emissions[T]): void; + emit(eventName: T, value?: + OptionalEmissions[T]): void; + /** Invoke the handlers registered via ::on for the given event name. */ + emit(eventName: T, value: + RequiredEmissions[T]): void; } /** @@ -1015,10 +1037,7 @@ export class Point { * Create a Point from an array containing two numbers representing the * row and column. */ - static fromObject(object: [number, number]): Point; - - /** Create a Point from an existing object which implements PointLike. */ - static fromObject(object: PointLike, copy?: boolean): Point; + static fromObject(object: PointCompatible, copy?: boolean): Point; /** Construct a Point object */ constructor(row?: number, column?: number); @@ -1775,7 +1794,8 @@ export class TextEditor { void; /** Add a cursor at the given position in buffer coordinates. */ - addCursorAtBufferPosition(bufferPosition: PointCompatible): Cursor; + addCursorAtBufferPosition(bufferPosition: PointCompatible, options?: + { autoscroll?: boolean }): Cursor; /** Add a cursor at the position in screen coordinates. */ addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor; @@ -2403,27 +2423,25 @@ export interface TextEditorRegistry { observe(callback: (editor: TextEditor) => void): Disposable; } +export type TooltipPlacement = + |"top"|"bottom"|"left"|"right" + |"auto"|"auto top"|"auto bottom"|"auto left"|"auto right"; + /** Associates tooltips with HTML elements or selectors. */ export interface TooltipManager { /** Add a tooltip to the given element. */ add(target: HTMLElement, options: { - title?: string, - html?: boolean, - item?: HTMLElement|{ element: HTMLElement }, - class?: string, - placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), - trigger?: "click"|"hover"|"focus"|"manual", - delay?: { show: number, hide: number }, - keyBindingCommand?: string, - keyBindingTarget?: HTMLElement + item?: object, } | { title?: string|(() => string), html?: boolean, - item?: HTMLElement|{ element: HTMLElement }, - class?: string, - placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), + keyBindingCommand?: string, + keyBindingTarget?: HTMLElement + } & { + class?: string; + placement?: TooltipPlacement|(() => TooltipPlacement), trigger?: "click"|"hover"|"focus"|"manual", - delay?: { show: number, hide: number }, + delay?: { show: number, hide: number } }): Disposable; /** Find the tooltips that have been applied to the given element. */ @@ -5795,16 +5813,6 @@ export interface ConfigValues { [key: string]: any; } -/** - * Allows you to strongly type event emissions across your codebase. Additional - * key:value pairings merged into this interface will result in emissions under - * the value of each key being templated by the type of the associated value. - */ -export interface Emissions { - // tslint:disable-next-line:no-any - [key: string]: any; -} - // Options ==================================================================== // The option objects that the user is expected to fill out and provide to // specific API call. @@ -6094,7 +6102,7 @@ export interface SharedDecorationOptions { * An HTMLElement or a model Object with a corresponding view registered. Only * applicable to the gutter, overlay and block types. */ - item?: HTMLElement; + item?: object; /** * If true, the decoration will only be applied to the head of the DisplayMarker. diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index d425cca21a..d05ee2251e 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -174,6 +174,23 @@ webAuth.login({username: 'bar', password: 'foo'}, (err, data) => {}); webAuth.crossOriginAuthenticationCallback(); +webAuth.checkSession({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback' + }, (err, authResult) => { + // Authentication tokens or error +}); + +webAuth.checkSession({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback', + usePostMessage: true + }, (err, authResult) => { + // Renewed tokens or error +}); + const authentication = new auth0.Authentication({ domain: 'me.auth0.com', clientID: '...', diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 340f14e15b..6110f2fe52 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -268,6 +268,14 @@ export class WebAuth { * @param options: */ passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback): void; + + /** + * Renews an existing session on Auth0's servers using `response_mode=web_message` (i.e. Auth0's hosted login page) + * + * @param options options used in {@link authorize} call + * @param callback: any(err, token_payload) + */ + checkSession(options: CheckSessionOptions, callback: Auth0Callback): void; } export class Redirect { @@ -753,3 +761,10 @@ export interface AuthorizeOptions { scope?: string; audience?: string; } + +export interface CheckSessionOptions extends AuthorizeOptions { + /** + * optional parameter for auth0 to use postMessage to communicate between the silent callback and the SPA. + */ + usePostMessage?: boolean; +} diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 0642453a13..c2107b11e4 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -10,6 +10,17 @@ lock.show(); lock.hide(); lock.logout(() => {}); +lock.checkSession({}, function(error: auth0.Auth0Error, authResult: AuthResult): void { + if (error || !authResult) { + lock.show(); + } else { + // user has an active session, so we can use the accessToken directly. + lock.getUserInfo(authResult.accessToken, function(error, profile) { + console.log(error, profile); + }); + } +}); + // Show supports UI arguments const showOptions : Auth0LockShowOptions = { @@ -37,7 +48,7 @@ lock.show(showOptions); // "on" event-driven example -lock.on("authenticated", function(authResult : any) { +lock.on("authenticated", function(authResult: AuthResult) { lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) { if (error) { // Handle error @@ -49,7 +60,7 @@ lock.on("authenticated", function(authResult : any) { }); }); -lock.on("authenticated", function(authResult : any) { +lock.on("authenticated", function(authResult: AuthResult) { lock.getUserInfo(authResult.accessToken, function(error, profile) { if (error) { // Handle error diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 0a57d988ce..8ed6b50c87 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -154,6 +154,7 @@ interface Auth0LockStatic { // deprecated getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; + checkSession(options: any, callback: (error: auth0.Auth0Error, authResult: AuthResult | undefined) => void): void; // https://github.com/auth0/lock#resumeauthhash-callback resumeAuth(hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void; show(options?: Auth0LockShowOptions): void; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index 08a866e9b1..521738db7e 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -111,3 +111,12 @@ management // Update app metadata using callback management .updateAppMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {}); + + +management.getUsersByEmail('email@address.com', (err, users) => { + console.log(users); +}); + +management.getUsersByEmail('email@address.com').then((users) => { + console.log(users); +}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index d24cb40081..12829b5b67 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -482,6 +482,9 @@ export class ManagementClient { getUser(params: ObjectWithId): Promise; getUser(params: ObjectWithId, cb?: (err: Error, user: User) => void): void; + getUsersByEmail(email: string): Promise; + getUsersByEmail(email: string, cb?: (err: Error, users: User[]) => void): void; + createUser(data: CreateUserData): Promise; createUser(data: CreateUserData, cb: (err: Error, user: User) => void): void; diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index d21f477be0..c50daef248 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -315,6 +315,131 @@ function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) { cb(null, authResponse); } +/* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ +var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { + "Records": [ + { + "cf": { + "config": { + "distributionId": "EDFDVBD6EXAMPLE", + "requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" + }, + "request": { + "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", + "method": "GET", + "uri": "/picture.jpg", + "querystring": "size=large", + "headers": { + "host": [ + { + "key": "Host", + "value": "d111111abcdef8.cloudfront.net" + } + ], + "user-agent": [ + { + "key": "User-Agent", + "value": "curl/7.51.0" + } + ] + }, + "origin": { + "custom": { + "customHeaders": { + "my-origin-custom-header": [ + { + "key": "My-Origin-Custom-Header", + "value": "Test" + } + ] + }, + "domainName": "example.com", + "keepaliveTimeout": 5, + "path": "/custom_path", + "port": 443, + "protocol": "https", + "readTimeout": 5, + "sslProtocols": [ + "TLSv1", + "TLSv1.1" + ] + }, + "s3": { + "authMethod": "origin-access-identity", + "customHeaders": { + "my-origin-custom-header": [ + { + "key": "My-Origin-Custom-Header", + "value": "Test" + } + ] + }, + "domainName": "my-bucket.s3.amazonaws.com", + "path": "/s3_path", + "region": "us-east-1" + } + } + } + } + } + ] +}; + +var CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { + "Records": [ + { + "cf": { + "config": { + "distributionId": "EDFDVBD6EXAMPLE", + "requestId": "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" + }, + "request": { + "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", + "method": "GET", + "uri": "/picture.jpg", + "querystring": "size=large", + "headers": { + "host": [ + { + "key": "Host", + "value": "d111111abcdef8.cloudfront.net" + } + ], + "user-agent": [ + { + "key": "User-Agent", + "value": "curl/7.18.1" + } + ] + } + }, + "response": { + "status": "200", + "statusDescription": "OK", + "headers": { + "server": [ + { + "key": "Server", + "value": "MyCustomOrigin" + } + ], + "set-cookie": [ + { + "key": "Set-Cookie", + "value": "theme=light" + }, + { + "key": "Set-Cookie", + "value": "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT" + } + ] + } + } + } + } + ] +}; + /* Compatibility functions */ context.done(); context.done(error); diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index d6b50ff5e6..29fd267522 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -10,6 +10,7 @@ // Ishaan Malhi // Daniel Cottone // Kostya Misura +// Markus Tacker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -346,6 +347,55 @@ interface AuthResponseContext { [name: string]: string | number | boolean; } +/** + * CloudFront events + * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html + */ +type CloudFrontHeaders = { + [name: string]: { + key: string; + value: string; + }[] +}; + +type CloudFrontResponse = { + status: string; + statusDescription: string; + headers: CloudFrontHeaders; +}; + +type CloudFrontRequest = { + clientIp: string; + method: string; + uri: string; + querystring: string; + headers: CloudFrontHeaders; +}; + +type CloudFrontEvent = { + config: { + distributionId: string; + requestId: string; + } +} + +export type CloudFrontResponseEvent = { + Records: { + cf: CloudFrontEvent & { + request: CloudFrontRequest; + response: CloudFrontResponse; + } + }[] +}; + +export type CloudFrontRequestEvent = { + Records: { + cf: CloudFrontEvent & { + request: CloudFrontRequest; + } + }[] +}; + /** * AWS Lambda handler function. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html diff --git a/types/bindings/bindings-tests.ts b/types/bindings/bindings-tests.ts new file mode 100644 index 0000000000..e66ab51353 --- /dev/null +++ b/types/bindings/bindings-tests.ts @@ -0,0 +1,4 @@ +import bindings = require('bindings'); + +// Use your bindings defined in your C files +const result = bindings('binding.node').your_c_function(); diff --git a/types/bindings/index.d.ts b/types/bindings/index.d.ts new file mode 100644 index 0000000000..9403a7a92b --- /dev/null +++ b/types/bindings/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for bindings 1.3 +// Project: https://github.com/TooTallNate/node-bindings +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * The main `bindings()` function loads the compiled bindings for a given module. + * It uses V8's Error API to determine the parent filename that this function is + * being invoked from, which is then used to find the root directory. + */ +declare function bindings(mod: string): any; + +export = bindings; diff --git a/types/bindings/tsconfig.json b/types/bindings/tsconfig.json new file mode 100644 index 0000000000..fb9350642a --- /dev/null +++ b/types/bindings/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bindings-tests.ts" + ] +} diff --git a/types/bindings/tslint.json b/types/bindings/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bindings/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/braft-editor/braft-editor-tests.tsx b/types/braft-editor/braft-editor-tests.tsx new file mode 100644 index 0000000000..354c4cbb5b --- /dev/null +++ b/types/braft-editor/braft-editor-tests.tsx @@ -0,0 +1,31 @@ +import * as React from "react"; +import * as BraftEditor from "braft-editor"; +import { + RawDraftContentState, +} from 'draft-js'; +class BraftEditorTest extends React.Component { + state = { + content: null + }; + render() { + const editorProps = { + height: 500, + initialContent: this.state.content, + onChange: this.handleChange, + onHTMLChange: this.handleHTMLChange + }; + return ( +
+ +
+ ); + } + private handleChange = (content: RawDraftContentState) => { + console.log(content); + } + private handleHTMLChange = (html: string) => { + console.log(html); + } +} diff --git a/types/braft-editor/index.d.ts b/types/braft-editor/index.d.ts new file mode 100644 index 0000000000..225d32722d --- /dev/null +++ b/types/braft-editor/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for braft-editor 1.1 +// Project: https://github.com/margox/braft#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; +import { RawDraftContentState } from 'draft-js'; +export as namespace BraftEditor; +export = BraftEditor; +declare namespace BraftEditor { + interface fontFamiliesRange { + name: string; + family: string; + } + interface editorProps { + editorState?: any; + contentFormat?: RawDraftContentState; + initialContent?: RawDraftContentState | null; + onChange?: (content: RawDraftContentState) => void; + onRawChange?: (content: RawDraftContentState) => void; + onHTMLChange?: (content: string) => void; + controls?: string[]; + extendControls?: any[]; + height?: number; + language?: string; + placeholder?: string; + viewWrapper?: string; + colors?: string[]; + fontSizes?: number[]; + fontFamilies?: fontFamiliesRange[]; + media?: { [key: string]: any }; + getContent?: (format?: string) => RawDraftContentState; + setContent?: (content: RawDraftContentState, format?: string) => void; + toggleSelectionBlockType?: (blockquote: string) => any; + toggleSelectionInlineStyle?: (style: string, stylesToBeRemoved?: string[]) => any; + insertMedias?: (medias: Array<{ type: string, name: string, url: string }>) => void; + insertText?: (text: string, replace?: boolean) => void; + toggleSelectionLink?: (href: string, target: string) => void; + toggleSelectionAlignment?: (alignment: string) => any; + toggleSelectionColor?: (hexColor: string) => void; + toggleSelectionBackgroundColor?: (hexColor: string) => void; + toggleSelectionFontSize?: (fontSize: number) => void; + toggleSelectionFontFamily?: (fontFamily: string) => void; + selectionCollapsed?: () => boolean; + selectionHasInlineStyle?: () => boolean; + getSelectionBlockType?: () => string; + getEditorState?: () => void; + forceRender?: () => void; + getDraftInstance?: () => any; + getMediaLibraryInstance?: () => any; + getSelectionInlineStyle?: () => any; + undo?: () => any; + redo?: () => any; + focus?: () => void; + blur?: () => void; + } +} +declare class BraftEditor extends React.Component { } diff --git a/types/braft-editor/tsconfig.json b/types/braft-editor/tsconfig.json new file mode 100644 index 0000000000..f04b8febfe --- /dev/null +++ b/types/braft-editor/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "braft-editor-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/braft-editor/tslint.json b/types/braft-editor/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/braft-editor/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bson/index.d.ts b/types/bson/index.d.ts index 6aeeabe3d9..380e6e380c 100644 --- a/types/bson/index.d.ts +++ b/types/bson/index.d.ts @@ -58,6 +58,9 @@ export class Code { } export class DBRef { constructor(namespace: string, oid: ObjectID, db?: string); + namespace: string; + oid: ObjectID; + db?: string; } export class Double { constructor(value: number); diff --git a/types/cancan/cancan-tests.ts b/types/cancan/cancan-tests.ts new file mode 100644 index 0000000000..0d6ab3e9a7 --- /dev/null +++ b/types/cancan/cancan-tests.ts @@ -0,0 +1,32 @@ +import CanCan = require('cancan'); + +const cancan = new CanCan(); + +// $ExpectType void +cancan.allow('admin', 'manage', 'all'); + +// $ExpectType void +cancan.allow('user', 'read', 'post', {public: true}); + +// $ExpectType boolean +cancan.can('user', 'read', 'post'); + +// $ExpectType boolean +cancan.cannot('user', 'delete', 'post'); + +// $ExpectType void +cancan.authorize('user', 'delete', 'post'); + +// $ExpectType boolean +cancan.can('user', 'read', 'post', {fields: ['title']}); + +// $ExpectType boolean +cancan.cannot('user', 'delete', 'post', {fields: ['title']}); + +// $ExpectType void +cancan.authorize('user', 'delete', 'post', {fields: ['title']}); + +const cancanWithOption = new CanCan({ + instanceOf: (_instance, _model) => true, + createError: () => true +}); diff --git a/types/cancan/index.d.ts b/types/cancan/index.d.ts new file mode 100644 index 0000000000..e739af1ef5 --- /dev/null +++ b/types/cancan/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for cancan 3.1 +// Project: https://github.com/vadimdemedes/cancan +// Definitions by: Vincent Pang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace CanCan { + interface Option { + instanceOf?: (instance: any, model: any) => boolean; + createError?: () => any; + } +} + +declare class CanCan { + constructor(options?: CanCan.Option); + + allow(model: any, + actions: string | ReadonlyArray, + targets: T | ReadonlyArray | string | ReadonlyArray, + condition?: object | ((performer: any, target: any, options?: any) => boolean)): void; + + can(performer: any, action: string, target: any, options?: any): boolean; + + cannot(performer: any, action: string, target: any, options?: any): boolean; + + authorize(performer: any, action: string, target: any, options?: any): void; +} + +export = CanCan; diff --git a/types/cancan/tsconfig.json b/types/cancan/tsconfig.json new file mode 100644 index 0000000000..8aace9dd52 --- /dev/null +++ b/types/cancan/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cancan-tests.ts" + ] +} diff --git a/types/cancan/tslint.json b/types/cancan/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cancan/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 984e4103d1..8c19f1f54a 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -26,20 +26,20 @@ declare namespace Chai { version: string; } - interface ExpectStatic extends AssertionStatic { + export interface ExpectStatic extends AssertionStatic { fail(actual?: any, expected?: any, message?: string, operator?: Operator): void; } - interface AssertStatic extends Assert { + export interface AssertStatic extends Assert { } - interface AssertionStatic { + export interface AssertionStatic { (target: any, message?: string): Assertion; } - type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; + export type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; - type OperatorComparable = boolean | null | number | string | undefined | Date; + export type OperatorComparable = boolean | null | number | string | undefined | Date; interface ShouldAssertion { equal(value1: any, value2: any, message?: string): void; @@ -256,7 +256,7 @@ declare namespace Chai { (object: Object, property: string, message?: string): Assertion; } - interface Assert { + export interface Assert { /** * @param expression Expression to test for truthiness. * @param message Message to display on error. @@ -1587,7 +1587,7 @@ declare namespace Chai { doesNotHaveAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; } - interface Config { + export interface Config { /** * Default: false */ @@ -1604,7 +1604,7 @@ declare namespace Chai { truncateThreshold: number; } - class AssertionError { + export class AssertionError { constructor(message: string, _props?: any, ssf?: Function); name: string; message: string; @@ -1615,10 +1615,10 @@ declare namespace Chai { declare const chai: Chai.ChaiStatic; -export = chai; +declare module "chai" { + export = chai; +} -declare global { - interface Object { - should: Chai.Assertion; - } +interface Object { + should: Chai.Assertion; } diff --git a/types/chai/tslint.json b/types/chai/tslint.json index 1a0ebe45c6..f99183c97d 100644 --- a/types/chai/tslint.json +++ b/types/chai/tslint.json @@ -4,8 +4,11 @@ "ban-types": false, "callable-types": false, "new-parens": false, + "no-declare-current-package": false, "no-empty-interface": false, "no-redundant-jsdoc-2": false, - "no-unnecessary-generics": false + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "strict-export-declare-modifiers": false } } diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 7d18eb39a8..614fbe26ef 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -364,7 +364,7 @@ declare namespace Chart { interface TickOptions { autoSkip?: boolean; - autoSkipPadding?: boolean; + autoSkipPadding?: number; callback?(value: any, index: any, values: any): string|number; display?: boolean; fontColor?: ChartColor; diff --git a/types/chokidar/index.d.ts b/types/chokidar/index.d.ts index 229ffb556f..396ad10e0a 100644 --- a/types/chokidar/index.d.ts +++ b/types/chokidar/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chokidar 1.7.1 +// Type definitions for chokidar 1.7 // Project: https://github.com/paulmillr/chokidar // Definitions by: Stefan Steinhart // Felix Becker @@ -19,7 +19,6 @@ export interface WatchedPaths { } export class FSWatcher extends EventEmitter implements fs.FSWatcher { - /** * Constructs a new FSWatcher instance with optional WatchOptions parameter. */ @@ -52,7 +51,6 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher { } export interface WatchOptions { - /** * Indicates whether the process should continue to run as long as files are being watched. If * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, @@ -86,7 +84,7 @@ export interface WatchOptions { * be relative to this. */ cwd?: string; - + /** * If set to true then the strings passed to .watch() and .add() are treated as literal path * names, even if they look like globs. Default: false. @@ -155,7 +153,6 @@ export interface WatchOptions { } export interface AwaitWriteFinishOptions { - /** * Amount of time in milliseconds for a file size to remain constant before emitting its event. */ diff --git a/types/chokidar/tslint.json b/types/chokidar/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/chokidar/tslint.json +++ b/types/chokidar/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/chrome/chrome-app.d.ts b/types/chrome/chrome-app.d.ts index f80b335125..561544c00c 100644 --- a/types/chrome/chrome-app.d.ts +++ b/types/chrome/chrome-app.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan +// Definitions by: Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,12 +21,39 @@ declare namespace chrome.app { // App Runtime //////////////////// declare namespace chrome.app.runtime { + enum LaunchSource { + "untracked" = "untracked", + "app_launcher" = "app_launcher", + "new_tab_page" = "new_tab_page", + "reload" = "reload", + "restart" = "restart", + "load_and_launch" = "load_and_launch", + "command_line" = "command_line", + "file_handler" = "file_handler", + "url_handler" = "url_handler", + "system_tray" = "system_tray", + "about_page" = "about_page", + "keyboard" = "keyboard", + "extensions_page" = "extensions_page", + "management_api" = "management_api", + "ephemeral_app" = "ephemeral_app", + "background" = "background", + "kiosk" = "kiosk", + "chrome_internal" = "chrome_internal", + "test" = "test", + "installed_notification" = "installed_notification", + "context_menu" = "context_menu", + } + interface LaunchData { id?: string; items?: LaunchDataItem[]; url?: string; referrerUrl?: string; isKioskSession?: boolean; + isPublicSession?: boolean; + source?: LaunchSource; + actionData?: {}; } interface LaunchDataItem { diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index bb2b4afcb5..16ed80730f 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -2,7 +2,7 @@ // Project: http://developer.chrome.com/extensions/ // Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// diff --git a/types/clamp-js-main/clamp-js-main-tests.ts b/types/clamp-js-main/clamp-js-main-tests.ts new file mode 100644 index 0000000000..f903b82a06 --- /dev/null +++ b/types/clamp-js-main/clamp-js-main-tests.ts @@ -0,0 +1,22 @@ +import clamp, { ClampOptions, ClampResponse } from 'clamp-js-main'; + +const element: HTMLElement = document.createElement('div'); +element.style.setProperty('width', '5px'); +element.style.setProperty('height', '5px'); +element.style.setProperty('font-size', '12px'); + +const span: HTMLSpanElement = document.createElement('span'); +span.textContent = "Lorem ipsum. Lorem ipsum"; +element.appendChild(span); + +const simpleClamp: ClampResponse = clamp(element); + +const options: ClampOptions = { + clamp: 2, + useNativeClamp: false, + splitOnChars: ['.'], + animate: true, + truncationChar: '--', + truncationHTML: '' +}; +const clampWithOptions: ClampResponse = clamp(element, options); diff --git a/types/clamp-js-main/index.d.ts b/types/clamp-js-main/index.d.ts new file mode 100644 index 0000000000..75286172cb --- /dev/null +++ b/types/clamp-js-main/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for clamp-js-main 0.11 +// Project: https://github.com/jmenglis/clamp-js-main#readme +// Definitions by: Sinziana Nicolae +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ClampOptions { + clamp?: number|string; + useNativeClamp?: boolean; + splitOnChars?: string[]; + animate?: boolean; + truncationChar?: string; + truncationHTML?: string | null; +} + +export interface ClampResponse { + original: string; + clamped: string; +} + +export default function clamp(element: HTMLElement, options?: ClampOptions): ClampResponse; diff --git a/types/clamp-js-main/tsconfig.json b/types/clamp-js-main/tsconfig.json new file mode 100644 index 0000000000..5c05321afc --- /dev/null +++ b/types/clamp-js-main/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clamp-js-main-tests.ts" + ] +} diff --git a/types/clamp-js-main/tslint.json b/types/clamp-js-main/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clamp-js-main/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/coinbase/coinbase-tests.ts b/types/coinbase/coinbase-tests.ts new file mode 100644 index 0000000000..793833355e --- /dev/null +++ b/types/coinbase/coinbase-tests.ts @@ -0,0 +1,108 @@ +import * as coinbase from "coinbase"; + +const client = new coinbase.Client({ apiKey: "key", apiSecret: "secret", version: "2017-10-22" }); + +client.getAccounts({}, (error: Error, result: coinbase.Account[]): void => undefined); + +client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { + account.buy({ amount: "1", commit: false, currency: "BTC", payment_method: "abcdef" }, (error: Error, buy: coinbase.Buy): void => { + buy.commit((error: Error, buy: coinbase.Buy): void => undefined); + }); + + account.createAddress({ name: "foo" }, (error: Error, address: coinbase.Address): void => { + address.getTransactions({}, (error: Error, transactions: coinbase.Transaction[]): void => undefined); + }); + + account.delete((error: Error): void => undefined); + + account.deposit({ amount: "1", commit: false, currency: "USD", payment_method: "abcdef" }, (error: Error, deposit: coinbase.Deposit): void => { + deposit.commit((error: Error, deposit: coinbase.Deposit): void => undefined); + }); + + account.getAddress("abcdef", (error: Error, address: coinbase.Address): void => undefined); + + account.getAddresses((error: Error, address: coinbase.Address[]): void => undefined); + + account.getBuy("abcdef", (error: Error, buy: coinbase.Buy): void => undefined); + + account.getBuys((error: Error, buy: coinbase.Buy[]): void => undefined); + + account.getDeposit("abcdef", (error: Error, deposit: coinbase.Deposit): void => undefined); + + account.getDeposits((error: Error, deposit: coinbase.Deposit[]): void => undefined); + + account.getSell("abcdef", (error: Error, deposit: coinbase.Sell): void => undefined); + + account.getSells((error: Error, deposit: coinbase.Sell[]): void => undefined); + + account.getTransaction("abcdef", (error: Error, deposit: coinbase.Transaction): void => undefined); + + account.getTransactions((error: Error, deposit: coinbase.Transaction[]): void => undefined); + + account.getWithdrawal("abcdef", (error: Error, deposit: coinbase.Withdrawal): void => undefined); + + account.getWithdrawals((error: Error, deposit: coinbase.Withdrawal[]): void => undefined); + + account.requestMoney( + { amount: "1", currency: "EUR", description: "foo", to: "bar", type: "request" }, + (error: Error, result: coinbase.Transaction) => undefined + ); + account.requestMoney({ amount: "1", currency: "EUR", to: "bar", type: "request" }, (error: Error, tx: coinbase.Transaction) => { + tx.cancel((error: Error, tx: coinbase.Transaction): void => undefined); + tx.complete((error: Error, tx: coinbase.Transaction): void => undefined); + tx.resend((error: Error, tx: coinbase.Transaction): void => undefined); + }); + + account.sell( + { agree_btc_amount_varies: true, amount: "1", commit: true, currency: "BTC", payment_method: "abcdef", quote: true}, + (error: Error, sell: coinbase.Sell): void => { + sell.commit((error: Error, sell: coinbase.Sell): void => undefined); + } + ); + account.sell( + { currency: "BTC", payment_method: "abcdef", total: "3"}, + (error: Error, sell: coinbase.Sell): void => { + sell.commit((error: Error, sell: coinbase.Sell): void => undefined); + } + ); + + account.sendMoney( + { amount: "1", currency: "EUR", description: "foo", fee: "2", idem: "bar", to: "baz", type: "send" }, + (error: Error, result: coinbase.Transaction) => undefined + ); + + account.setPrimary((error: Error, result: coinbase.Account): void => undefined); + + account.transferMoney( + { amount: "1", currency: "USD", description: "foo", to: "bar", type: "transfer" }, + (error: Error, tx: coinbase.Transaction): void => undefined + ); + + account.update({ name: "foo" }, (error: Error, result: coinbase.Account): void => undefined); + + account.withdraw({ amount: "1", commit: false, currency: "ETH", payment_method: "abcdef"}, (error: Error, result: coinbase.Withdrawal): void => { + result.commit((error: Error, result: coinbase.Withdrawal): void => undefined); + }); +}); + +client.getBuyPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined); + +client.getCurrencies((error: Error, result: coinbase.Currency[]): void => undefined); + +client.getExchangeRates({currency: "ETC"}, (error: Error, result: coinbase.ExchangeRate): void => undefined); + +client.getPaymentMethod("foo", (error: Error, result: coinbase.PaymentMethod): void => undefined); + +client.getPaymentMethods((error: Error, result: coinbase.PaymentMethod[]): void => undefined); + +client.getSellPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined); + +client.getSpotPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined); +client.getSpotPrice({ currencyPair: "USD-BTC", date: "2017-22-01" }, (error: Error, result: coinbase.MoneyHash): void => undefined); + +client.getTime((error: Error, result: coinbase.Time): void => undefined); + +client.getUser("abcdef", (error: Error, user: coinbase.User): void => { + user.showAuth((error: Error, auth: coinbase.Auth): void => undefined); + user.update({ name: "foo", time_zone: "bar", native_currency: "USD" }, (error: Error, user: coinbase.User): void => undefined); +}); diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts new file mode 100644 index 0000000000..ae1e041203 --- /dev/null +++ b/types/coinbase/index.d.ts @@ -0,0 +1,1333 @@ +// Type definitions for coinbase 2.0 +// Project: https://github.com/coinbase/coinbase-node +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ClientConstructOpts { + /** + * API key (obtain this from the coinbase website) + */ + apiKey?: string; + /** + * API key secret (obtain this from the coinbase website) + */ + apiSecret?: string; + /** + * OAuth2 access token + */ + accessToken?: string; + /** + * API version in 'yyyy-mm-dd' format, see https://developers.coinbase.com/api/v2#changelog + */ + version?: string; +} + +export interface CreateAccountOpts { + /** + * Account name + */ + name?: string; +} + +export interface GetExchangeRateOpts { + /** + * Base currency, default USD + */ + currency?: string; +} + +export interface GetBuyPriceOpts { + /** + * Currency pair, e.g. 'BTC-USD' + */ + currencyPair: string; +} + +export interface GetSellPriceOpts { + /** + * Currency pair, e.g. 'BTC-USD' + */ + currencyPair: string; +} + +export interface GetSpotPriceOpts { + /** + * Currency pair, e.g. 'BTC-USD' + */ + currencyPair: string; + /** + * Specify date for historic spot price in format YYYY-MM-DD (UTC) + */ + date?: string; +} + +export interface UpdateAccountOpts { + /** + * Account name + */ + name?: string; +} + +export interface CreateAddressOpts { + /** + * Address label + */ + name?: string; +} + +export interface SendMoneyOpts { + /** + * Type send is required when sending money + */ + type: "send"; + /** + * A bitcoin address, litecoin address, ethereum address, or an email of the recipient + */ + to: string; + /** + * Amount to be sent + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Notes to be included in the email that the recipient receives + */ + description?: string; + /** + * Don’t send notification emails for small amounts (e.g. tips) + */ + skip_notifications?: boolean; + /** + * Transaction fee in BTC/ETH/LTC if you would like to pay it. Fees can be added as a string, such as 0.0005 + */ + fee?: string; + /** + * *Recommended* A token to ensure idempotence. If a previous transaction with the same idem parameter already exists for this sender, + * that previous transaction will be returned and a new one will not be created. Max length 100 characters + */ + idem?: string; + /** + * Whether this send is to another financial institution or exchange. Required if this send is to an address and is valued at over USD$3000. + */ + to_financial_institution?: boolean; + /** + * The website of the financial institution or exchange. Required if to_financial_institution is true. + */ + financial_institution_website?: string; +} + +export interface TransferMoneyOpts { + /** + * Type transfer is required when transferring bitcoin or ethereum between accounts + */ + type: "transfer"; + /** + * ID of the receiving account + */ + to: string; + /** + * Amount to be transferred + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Notes to be included in the transfer + */ + description?: string; +} + +export interface RequestMoneyOpts { + /** + * Type request is required when sending money + */ + type: "request"; + /** + * An email of the recipient + */ + to: string; + /** + * Amount to be transferred + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Notes to be included in the email that the recipient receives + */ + description?: string; +} + +export interface UpdateUserOpts { + /** + * User’s name + */ + name?: string; + /** + * Time zone + */ + time_zone?: string; + /** + * Local currency used to display amounts converted from BTC + */ + native_currency?: string; +} + +export interface BuyOpts { + /** + * Buy amount without fees (alternative to total) + */ + amount?: string; + /** + * Buy amount with fees (alternative to amount) + */ + total?: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the buy. (todo get payment methods) + */ + payment_method?: string; + /** + * Whether or not you would still like to buy if you have to wait for your money to arrive to lock in a price + */ + agree_btc_amount_varies?: boolean; + /** + * If set to false, this buy will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; + /** + * If set to true, response will return an unsave buy for detailed price quote. Default value: false + */ + quote?: boolean; +} + +export interface SellOpts { + /** + * Sell amount without fees (alternative to total) + */ + amount?: string; + /** + * Sell amount with fees (alternative to amount) + */ + total?: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the sell. + */ + payment_method?: string; + /** + * Whether or not you would still like to sell if you have to wait for your money to arrive to lock in a price + */ + agree_btc_amount_varies?: boolean; + /** + * If set to false, this sell will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; + /** + * If set to true, response will return an unsave sell for detailed price quote. Default value: false + */ + quote?: boolean; +} + +export interface DepositOpts { + /** + * Deposit amount + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the buy. (todo get payment methods) + */ + payment_method?: string; + /** + * If set to false, this deposit will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; +} + +export interface WithdrawOpts { + /** + * Withdrawal amount + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the buy. (todo get payment methods) + */ + payment_method?: string; + /** + * If set to false, this withdrawal will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; +} + +/** + * Combination of an amount and a currency + */ +export interface MoneyHash { + /** + * Amount as floating-point in a string + */ + amount: string; + /** + * Currency e.g. "BTC" (see Client#getCurrencies() for available strings) + */ + currency: string; +} + +export type ResourceType = "account" | "transaction" | "address" | "user" | "buy" | "sell" | "deposit" | "withdrawal" | "payment_method"; + +/** + * Base interface for all resources + */ +export interface Resource { + /** + * Resource type + */ + resource: ResourceType; +} + +export class User implements Resource { + /** + * Resource type, constant "user" + */ + resource: "user"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * User’s name + */ + name?: string; + + /** + * + */ + username?: string; + + /** + * Location for user’s profile + */ + profile_location?: string; + + /** + * Bio for user’s profile + */ + profile_bio?: string; + + /** + * profile location if user has one + */ + profile_url?: string; + + /** + * User’s avatar url + */ + avatar_url: string; + + /** + * Time zone (needs wallet:user:read permission) + */ + time_zone?: string; + + /** + * Native currency (needs wallet:user:read permission) + */ + native_currency?: string; + + /** + * (needs wallet:user:read permission) + */ + bitcoin_unit?: string; + + /** + * (needs wallet:user:read permission) + */ + country?: Country; + + /** + * Email address (needs wallet:user:email permission) + */ + email?: string; + + /** + * Get current user’s authorization information including granted scopes and send limits when using OAuth2 authentication + * No permission required + */ + showAuth(cb: (error: Error, result: Auth) => void): void; + + /** + * Change user properties + * Scope: wallet:user:update + */ + update(opts: UpdateUserOpts, cb: (error: Error, result: User) => void): void; +} + +export interface Auth { + /** + * Authentication method e.g. "oauth" + */ + method: string; + /** + * Permissions for this user e.g. "wallet:user:read" + */ + scopes: string[]; + + oauth_meta?: any; +} + +export interface Country { + /** + * 2-letter country code + */ + code: string; + /** + * Country name + */ + name: string; +} + +/** + * Bitcoin, Litecoin or Ethereum address + */ +export class Address implements Resource { + /** + * Type of resource, constant string "address" + */ + resource: "address"; + + /** + * Bitcoin, Litecoin or Ethereum address + */ + address: string; + + /** + * User defined label for the address + */ + name?: string; + + /** + * List transactions that have been sent to a specific address. + * Scope: wallet:transactions:read + */ + getTransactions(opts: {}, cb: (error: Error, result: Transaction[]) => void): void; +} + +export type AccountType = "wallet" | "fiat" | "multisig" | "vault" | "multisig_vault"; + +/** + * Account resource represents all of a user’s accounts, including bitcoin, litecoin and ethereum wallets, fiat currency accounts, + * and vaults. This is represented in the type field. It’s important to note that new types can be added over time so you want to + * make sure this won’t break your implementation. + * User can only have one primary account and it’s type can only be wallet. + */ +export class Account implements Resource { + /** + * Type of resource, constant string "account" + */ + resource: "account"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * User or system defined name + */ + name: string; + + /** + * Primary account + */ + primary: boolean; + + /** + * Account’s type + */ + type: AccountType; + + /** + * Account’s currency (see Client#getCurrencies() for available strings) + */ + currency: string; + + /** + * Balance + */ + balance: MoneyHash; + + /** + * Promote an account as primary account. + * Scope: wallet:accounts:update + */ + setPrimary(cb: (error: Error, result: Account) => void): void; + + /** + * Modifies user’s account. + * Scope: wallet:accounts:update + */ + update(opts: UpdateAccountOpts, cb: (error: Error, result: Account) => void): void; + + /** + * Removes user’s account. In order to remove an account it can’t be: + * - Primary account + * - Account with non-zero balance + * - Fiat account + * - Vault with a pending withdrawal + * Scope: wallet:accounts:delete + */ + delete(cb: (error: Error) => void): void; + + /** + * Lists addresses for an account. Important: Addresses should be considered one time use only. Create new addresses. + * Scope: wallet:addresses:read + */ + getAddresses(cb: (error: Error, result: Address[]) => void): void; + + /** + * Show an individual address for an account. A regular bitcoin, litecoin or ethereum address can be used in place of `id` but the + * address has to be associated to the correct account. Important: Addresses should be considered one time use only. Create new addresses. + * Scope: wallet:addresses:read + * @param id resource id or a regular bitcoin, litecoin or ethereum address + */ + getAddress(id: string, cb: (error: Error, result: Address) => void): void; + + /** + * Creates a new address for an account. As all the arguments are optinal, it’s possible just to do a empty POST which will create a new + * address. This is handy if you need to create new receive addresses for an account on-demand. + * Addresses can be created for all account types. With fiat accounts, funds will be received with Instant Exchange + * Scope: wallet:addresses:create + * @param opts can be null, optional address name + */ + createAddress(opts: CreateAddressOpts | null, cb: (error: Error, result: Address) => void): void; + + /** + * Lists account’s transactions. + * Scope: wallet:transactions:read + */ + getTransactions(cb: (error: Error, result: Transaction[]) => void): void; + + /** + * Show an individual transaction for an account + * Scope: wallet:transactions:read + * @param id resource id + */ + getTransaction(id: string, cb: (error: Error, result: Transaction) => void): void; + + /** + * Send funds to a bitcoin address, litecoin address, ethereum address, or email address. No transaction fees are required for off + * blockchain bitcoin transactions. + * + * It’s recommended to always supply a unique `idem` field for each transaction. This prevents you from sending the same transaction + * twice if there has been an unexpected network outage or other issue. + * + * When used with OAuth2 authentication, this endpoint requires two factor authentication unless used with + * wallet:transactions:send:bypass-2fa scope. + * + * If the user is able to buy bitcoin, they can send funds from their fiat account using instant exchange feature. + * Buy fees will be included in the created transaction and the recipient will receive the user defined amount. + * To create a multisig transaction, visit Multisig documentation. + * + * Scope: wallet:transactions:send, wallet:transactions:send:bypass-2fa + */ + sendMoney(opts: SendMoneyOpts, cb: (error: Error, result: Transaction) => void): void; + + /** + * Transfer bitcoin, litecoin or ethereum between two of a user’s accounts. Following transfers are allowed: + * - wallet to wallet + * - wallet to vault + * Scope: wallet:transactions:transfer + */ + transferMoney(opts: TransferMoneyOpts, cb: (error: Error, result: Transaction) => void): void; + + /** + * Requests money from an email address. + * Scope: wallet:transactions:request + */ + requestMoney(opts: RequestMoneyOpts, cb: (error: Error, result: Transaction) => void): void; + + /** + * Lists buys for an account. + * Scope: wallet:buys:read + */ + getBuys(cb: (error: Error, result: Buy[]) => void): void; + + /** + * Show an individual buy. + * Scope: wallet:buys:read + * @param id resource id + */ + getBuy(id: string, cb: (error: Error, result: Buy) => void): void; + + /** + * Buys a user-defined amount of bitcoin, litecoin or ethereum. + * There are two ways to define buy amounts–you can use either the amount or the total parameter: + * - When supplying amount, you’ll get the amount of bitcoin, litecoin or ethereum defined. With amount it’s recommended to use BTC or + * ETH as the currency value, but you can always specify a fiat currency and and the amount will be converted to BTC or ETH respectively. + * - When supplying total, your payment method will be debited the total amount and you’ll get the amount in BTC or ETH after fees have + * been reduced from the total. With total it’s recommended to use the currency of the payment method as the currency parameter, + * but you can always specify a different currency and it will be converted. + * Given the price of digital currency depends on the time of the call and on the amount of purchase, it’s recommended to use the + * commit: false parameter to create an uncommitted buy to show the confirmation for the user or get the final quote, and commit that + * with a separate request. + * If you need to query the buy price without locking in the buy, you can use quote: true option. This returns an unsaved buy and + * unlike commit: false, this buy can’t be completed. This option is useful when you need to show the detailed buy price quote + * for the user when they are filling a form or similar situation. + * Scope: wallet:buys:create + * @param opts indicates what to buy + * @param cb receives transaction that you can use to commit the buy + */ + buy(opts: BuyOpts, cb: (error: Error, result: Buy) => void): void; + + /** + * Lists sells for an account. + * Scope: wallet:sells:read + */ + getSells(cb: (error: Error, result: Sell[]) => void): void; + + /** + * Show an individual sell. + * Scope: wallet:sells:read + * @param id resource id + */ + getSell(id: string, cb: (error: Error, result: Sell) => void): void; + + /** + * Sells a user-defined amount of bitcoin, litecoin or ethereum. + * + * There are two ways to define sell amounts–you can use either the amount or the total parameter: + * - When supplying amount, you’ll get the amount of bitcoin, litecoin or ethereum defined. With amount it’s recommended to use BTC or + * ETH as the currency value, but you can always specify a fiat currency and the amount will be converted to BTC or ETH respectively. + * - When supplying total, your payment method will be credited the total amount and you’ll get the amount in BTC or ETH after fees + * have been reduced from the subtotal. With total it’s recommended to use the currency of the payment method as the currency parameter, + * but you can always specify a different currency and it will be converted. + * + * Given the price of digital currency depends on the time of the call and amount of the sell, it’s recommended to use the commit: false + * parameter to create an uncommitted sell to get a quote and then to commit that with a separate request. + * + * If you need to query the sell price without locking in the sell, you can use quote: true option. This returns an unsaved sell and + * unlike commit: false, this sell can’t be completed. This option is useful when you need to show the detailed sell price quote for + * the user when they are filling a form or similar situation. + * Scope: wallet:sells:create + */ + sell(opts: SellOpts, cb: (error: Error, result: Sell) => void): void; + + /** + * Lists deposits for an account. + * Scope: wallet:deposits:read + */ + getDeposits(cb: (error: Error, result: Deposit[]) => void): void; + + /** + * Show an individual deposit. + * Scope: wallet:deposits:read + * @param id resource id + */ + getDeposit(id: string, cb: (error: Error, result: Deposit) => void): void; + + /** + * Deposits user-defined amount of funds to a fiat account. + * Scope: wallet:deposits:create + */ + deposit(opts: DepositOpts, cb: (error: Error, result: Deposit) => void): void; + + /** + * Lists withdrawals for an account. + * Scope: wallet:withdrawals:read + */ + getWithdrawals(cb: (error: Error, result: Withdrawal[]) => void): void; + + /** + * Show an individual withdrawal. + * Scope: wallet:withdrawals:read + * @param id resource id + */ + getWithdrawal(id: string, cb: (error: Error, result: Withdrawal) => void): void; + + /** + * Withdraws user-defined amount of funds from a fiat account. + * Scope: wallet:withdrawals:create + */ + withdraw(opts: WithdrawOpts, cb: (error: Error, result: Withdrawal) => void): void; +} + +/** + * Reference to any resource + */ +export interface ResourceRef { + id: string; + resource: ResourceType; + resource_path: string; +} + +export type TransactionType = "send" | "request" | "transfer" | "buy" | "sell" | "fiat_deposit" | "fiat_withdrawal" | "exchange_deposit" + | "exchange_withdrawal" | "vault_withdrawal"; + +export type TransactionStatus = "pending" | "completed" | "failed" | "expired" | "canceled" | "waiting_for_signature" | "waiting_for_clearing"; + +export class Transaction implements Resource { + /** + * Constant "transaction" + */ + resource: "transaction"; + + /** + * Transaction type + */ + type: TransactionType; + + /** + * Transaction status + */ + status: TransactionStatus; + + /** + * Amount in bitcoin, litecoin or ethereum + */ + amount: MoneyHash; + + /** + * Amount in user's native currency + */ + native_amount: MoneyHash; + + /** + * Account associated with the transaction + */ + account: Account; + + /** + * User defined description + */ + description: string; + + /** + * Indicator if the transaction was instant exchanged (received into a bitcoin address for a fiat account) + */ + instant_exchange: boolean; + + /** + * Detailed information about the transaction + */ + details: any; + + /** + * Information about bitcoin, litecoin or ethereum network including network transaction hash if transaction was on-blockchain. + * Only available for certain types of transactions + */ + network?: any; + + /** + * The receiving party of a debit transaction. Usually another resource but can also be another type like email. + * Only available for certain types of transactions + */ + to?: ResourceRef | string; + + /** + * The originating party of a credit transaction. Usually another resource but can also be another type like bitcoin network. + * Only available for certain types of transactions + */ + from?: ResourceRef | string; + + /** + * Associated bitcoin, litecoin or ethereum address for received payment + */ + address?: Address; + + /** + * Associated OAuth2 application + */ + application?: any; + + /** + * Lets the recipient of a money request complete the request by sending money to the user who requested the money. + * This can only be completed by the user to whom the request was made, not the user who sent the request. + * Scope: wallet:transactions:request + */ + complete(cb: (error: Error, result: Transaction) => void): void; + + /** + * Lets the user resend a money request. This will notify recipient with a new email. + * Scope: wallet:transactions:request + */ + resend(cb: (error: Error, result: Transaction) => void): void; + + /** + * Lets a user cancel a money request. Money requests can be canceled by the sender or the recipient. + * Scope: wallet:transactions:request + */ + cancel(cb: (error: Error, result: Transaction) => void): void; +} + +export type BuyStatus = "created" | "completed" | "canceled"; + +/** + * Buy resource + */ +export class Buy implements Resource { + /** + * Constant "buy" + */ + resource: "buy"; + + /** + * Status + */ + status: BuyStatus; + + /** + * Associated payment method (e.g. a bank, fiat account) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount in bitcoin, litecoin or ethereum + */ + amount: MoneyHash; + + /** + * Fiat amount with fees + */ + total: MoneyHash; + + /** + * Fiat amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this buy + */ + fee: MoneyHash; + + /** + * Has this buy been committed? + */ + committed: boolean; + + /** + * Was this buy executed instantly? + */ + instant: boolean; + + /** + * When a buy isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a buy that is created in commit: false state. + * If the exchange rate has changed since the buy was created, this call will fail with the error “The exchange rate updated while you + * were waiting. The new total is shown below”. The buy’s total will also be updated. You can repeat the `commit` call to accept the new + * values and start the buy at the new rates. + * Scope: wallet:buys:create + */ + commit(cb: (error: Error, transaction: Buy) => void): void; +} + +export type SellStatus = "created" | "completed" | "canceled"; + +/** + * Sell resource + */ +export class Sell implements Resource { + /** + * Constant "sell" + */ + resource: "sell"; + + /** + * Status of the sell. Currently available values: created, completed, canceled + */ + status: BuyStatus; + + /** + * Associated payment method (e.g. a bank, fiat account) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount in bitcoin, litecoin or ethereum + */ + amount: MoneyHash; + + /** + * Fiat amount with fees + */ + total: MoneyHash; + + /** + * Fiat amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this sell + */ + fee: MoneyHash; + + /** + * Has this sell been committed? + */ + committed: boolean; + + /** + * Was this sell executed instantly? + */ + instant: boolean; + + /** + * When a sell isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a sell that is created in commit: false state. + * If the exchange rate has changed since the sell was created, this call will fail with the error “The exchange rate updated while you + * were waiting. The new total is shown below”. The buy’s total will also be updated. You can repeat the `commit` call to accept the new + * values and start the buy at the new rates. + * Scope: wallet:sells:create + */ + commit(cb: (error: Error, transaction: Sell) => void): void; +} + +export type DepositStatus = "created" | "completed" | "canceled"; + +/** + * Deposit resource represents a deposit of funds using a payment method (e.g. a bank). Each committed deposit also has an associated transaction. + * Deposits can be started with commit: false which is useful when displaying the confirmation for a deposit. + * These deposits will never complete and receive an associated transaction unless they are committed separately. + */ +export class Deposit implements Resource { + resource: "deposit"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * Status of the deposit. Currently available values: created, completed, canceled + */ + status: DepositStatus; + + /** + * Associated payment method (e.g. a bank) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount + */ + amount: MoneyHash; + + /** + * Amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this deposit + */ + fee: MoneyHash; + + /** + * Has this deposit been committed? + */ + committed: boolean; + + /** + * When a deposit isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a deposit that is created in commit: false state. + * Scope: wallet:deposits:create + */ + commit(cb: (error: Error, result: Deposit) => void): void; +} + +export type WithdrawalStatus = "created" | "completed" | "canceled"; + +/** + * Withdrawal resource represents a withdrawal of funds using a payment method (e.g. a bank). Each committed withdrawal also has a associated + * transaction. + * Withdrawal can be started with commit: false which is useful when displaying the confirmation for a withdrawal. These withdrawals will + * never complete and receive an associated transaction unless they are committed separately. + */ +export class Withdrawal implements Resource { + resource: "deposit"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * Status of the deposit. Currently available values: created, completed, canceled + */ + status: WithdrawalStatus; + + /** + * Associated payment method (e.g. a bank) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount + */ + amount: MoneyHash; + + /** + * Amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this withdrawal + */ + fee: MoneyHash; + + /** + * Has this withdrawal been committed? + */ + committed: boolean; + + /** + * When a withdrawal isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a withdrawal that is created in commit: false state. + * Scope: wallet:withdrawals:create + */ + commit(cb: (error: Error, result: Withdrawal) => void): void; +} + +export type PaymentMethodType = "ach_bank_account" | "sepa_bank_account" | "ideal_bank_account" | "fiat_account" | "bank_wire" + | "credit_card" | "secure3d_card" | "eft_bank_account" | "interac"; + +/** + * Payment method resource represents the different kinds of payment methods that can be used when buying and selling bitcoin, litecoin or + * ethereum. + * As fiat accounts can be used for buying and selling, they have an associated payment method. This type of a payment method will also have + * a fiat_account reference to the actual account. + * + * Currently available type values: + * - ach_bank_account - Regular US bank account + * - sepa_bank_account - European SEPA bank account + * - ideal_bank_account - iDeal bank account (Europe) + * - fiat_account - Fiat nominated Coinbase account + * - bank_wire - Bank wire (US only) + * - credit_card - Credit card (can’t be used for buying/selling) + * - secure3d_card - Secure3D verified payment card + * - eft_bank_account - Canadian EFT bank account + * - interac - Interac Online for Canadian bank accounts + */ +export interface PaymentMethod extends Resource { + /** + * Resource type, constant "payment_method" + */ + resource: "payment_method"; + + /** + * Payment method type + */ + type: PaymentMethodType; + + /** + * Method name + */ + name: string; + + /** + * Payment method’s native currency (see Client#getCurrencies() for available strings) + */ + currency: string; + + /** + * Is primary buying method? + */ + primary_buy: boolean; + + /** + * Is primary selling method? + */ + primary_sell: boolean; + + /** + * Is buying allowed with this method? + */ + allow_buy: boolean; + + /** + * Is selling allowed with this method? + */ + allow_sell: boolean; + + /** + * Does this method allow for instant buys? + */ + instant_buy: boolean; + + /** + * Does this method allow for instant sells? + */ + instant_sell: boolean; + + /** + * If the user has obtained optional wallet:payment-methods:limits permission, an additional field, limits, will be embedded into payment + * method data. It will contain information about buy, instant buy, sell and deposit limits (there’s no limits for withdrawals at this time). + * As each one of these can have several limits you should always look for the lowest remaining value when performing the relevant action. + */ + limits?: PaymentMethodLimits; +} + +/** + * This contains information about buy, instant buy, sell and deposit limits (there’s no limits for withdrawals at this time). + * As each one of these can have several limits you should always look for the lowest remaining value when performing the relevant action. + */ +export interface PaymentMethodLimits { + buy: PaymentMethodLimit[]; + instant_buy: PaymentMethodLimit[]; + sell: PaymentMethodLimit[]; + deposit: PaymentMethodLimit[]; +} + +export interface PaymentMethodLimit { + period_in_days: number; + total: MoneyHash; + remaining: MoneyHash; +} + +/** + * Information about one supported currency. Currency codes will conform to the ISO 4217 standard where possible. + * Currencies which have or had no representation in ISO 4217 may use a custom code (e.g. BTC). + */ +export interface Currency { + /** + * Abbreviation e.g. "USD" or "BTC" + */ + id: string; + /** + * Full name e.g. "United Arab Emirates Dirham" + */ + name: string; + /** + * Floating-point number in a string + */ + min_size: string; +} + +export interface ExchangeRate { + /** + * Base currency + */ + currency: string; + /** + * Rates as floating points in strings; indexed by currency id + */ + rates: { [index: string]: string }; +} + +export interface Time { + iso: string; + epoch: number; +} + +export class Client { + constructor(opts: ClientConstructOpts); + + /** + * Get any user’s information with their ID. + * Scopes: none + * @param id resource id + */ + getUser(id: string, cb: (error: Error, result: User) => void): void; + + /** + * Get the current user. To get user’s email or private information, use permissions wallet:user:email and wallet:user:read. If current + * request has a wallet:transactions:send scope, then the response will contain a boolean sends_disabled field that indicates + * if the user’s send functionality has been disabled. + */ + getCurrentUser(cb: (error: Error, result: User) => void): void; + + /** + * Returns all accounts for the current user + * Scope: wallet:accounts:read + */ + getAccounts(opts: {}, cb: (error: Error, result: Account[]) => void): void; + + /** + * Get one account by its Resource ID + * Scope: wallet:accounts:read + * @param id resource ID or "primary" + */ + getAccount(id: string, cb: (error: Error, result: Account) => void): void; + + /** + * Creates a new account for user. + * Scopes: wallet:accounts:create + */ + createAccount(opts: CreateAccountOpts, cb: (error: Error, result: Account) => void): void; + + /** + * Lists current user’s payment methods + * Scope: wallet:payment-methods:read + */ + getPaymentMethods(cb: (error: Error, result: PaymentMethod[]) => void): void; + + /** + * Show current user’s payment method. + * Scope: wallet:payment-methods:read + */ + getPaymentMethod(id: string, cb: (error: Error, result: PaymentMethod) => void): void; + + /** + * List known currencies. Currency codes will conform to the ISO 4217 standard where possible. Currencies which have or had no + * representation in ISO 4217 may use a custom code (e.g. BTC). + * Scope: none + */ + getCurrencies(cb: (error: Error, result: Currency[]) => void): void; + + /** + * Get current exchange rates. Default base currency is USD but it can be defined as any supported currency. + * Returned rates will define the exchange rate for one unit of the base currency. + * Scope: none + */ + getExchangeRates(opts: GetExchangeRateOpts, cb: (error: Error, result: ExchangeRate) => void): void; + + /** + * Get the total price to buy one bitcoin or ether. Note that exchange rates fluctuates so the price is only correct for seconds at the time. + * This buy price includes standard Coinbase fee (1%) but excludes any other fees including bank fees. + * If you need more accurate price estimate for a specific payment method or amount, @see Account#buy() and `quote: true` option. + * Scope: none + */ + getBuyPrice(opts: GetBuyPriceOpts, cb: (error: Error, result: MoneyHash) => void): void; + + /** + * Get the total price to sell one bitcoin or ether. Note that exchange rates fluctuates so the price is only correct for seconds at the time. + * This sell price includes standard Coinbase fee (1%) but excludes any other fees including bank fees. If you need more accurate price + * estimate for a specific payment method or amount, see sell bitcoin endpoint and quote: true option. + * Scope: none + */ + getSellPrice(opts: GetSellPriceOpts, cb: (error: Error, result: MoneyHash) => void): void; + + /** + * Get the current market price for bitcoin. This is usually somewhere in between the buy and sell price. + * Note that exchange rates fluctuates so the price is only correct for seconds at the time. + * You can also get historic prices with date parameter. + * Scope: none + */ + getSpotPrice(opts: GetSpotPriceOpts, cb: (error: Error, result: MoneyHash) => void): void; + + /** + * Get the API server time. + */ + getTime(cb: (error: Error, result: Time) => void): void; +} diff --git a/types/coinbase/tsconfig.json b/types/coinbase/tsconfig.json new file mode 100644 index 0000000000..6f8b261d27 --- /dev/null +++ b/types/coinbase/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "coinbase-tests.ts" + ] +} diff --git a/types/coinbase/tslint.json b/types/coinbase/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/coinbase/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/concaveman/concaveman-tests.ts b/types/concaveman/concaveman-tests.ts index 736d616ad9..1d951b5448 100644 --- a/types/concaveman/concaveman-tests.ts +++ b/types/concaveman/concaveman-tests.ts @@ -1,4 +1,4 @@ import * as concaveman from 'concaveman'; var points = [[10, 20], [30, 12.5]]; -var polygon = concaveman(points); \ No newline at end of file +var polygon = concaveman(points); diff --git a/types/concaveman/index.d.ts b/types/concaveman/index.d.ts index a5b55c8fa3..ed5da84fc9 100644 --- a/types/concaveman/index.d.ts +++ b/types/concaveman/index.d.ts @@ -3,10 +3,11 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + declare module "concaveman" { /** * A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set). - * + * * @name concaveman * @param {Array>} points is an array of [x, y] points. * @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes. @@ -15,7 +16,7 @@ declare module "concaveman" { * @example * var points = [[10, 20], [30, 12.5], ...]; * var polygon = concaveman(points); - * + * * //=hull */ function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][]; diff --git a/types/confirmdialog/confirmdialog-tests.ts b/types/confirmdialog/confirmdialog-tests.ts new file mode 100644 index 0000000000..cd2ad0e8ca --- /dev/null +++ b/types/confirmdialog/confirmdialog-tests.ts @@ -0,0 +1,129 @@ +class Confirm { + private title_: string; + private conTent_: string; + constructor(title: string, content: string) { + this.title_ = title; + this.conTent_ = content; + } + + confirm() { + $.confirm({ + title: 'Confirm!', + content: 'Simple confirm!', + buttons: { + confirm: () => { + $.alert('Confirmed!'); + }, + cancel: (cancel: string) => { + $.alert('Canceled! ' + cancel); + }, + somethingElse: { + text: 'Something else', + btnClass: 'btn-blue', + keys: ['enter', 'shift'], + action: () => { + alert('Something else?'); + } + } + } + }); + } + + alert() { + $.alert({ + title: 'Alert!', + content: 'Simple alert!', + }); + } + + globalSettings() { + jconfirm.defaults = { + title: 'Hello', + titleClass: '', + type: 'default', + typeAnimated: true, + draggable: true, + dragWindowGap: 15, + dragWindowBorder: true, + animateFromElement: true, + smoothContent: true, + content: 'Are you sure to continue?', + buttons: {}, + defaultButtons: { + ok: { + action: () => { + } + }, + close: { + action: () => { + } + }, + }, + + icon: '', + lazyOpen: false, + bgOpacity: null, + theme: 'light', + animation: 'scale', + closeAnimation: 'scale', + animationSpeed: 400, + animationBounce: 1, + rtl: false, + container: 'body', + containerFluid: false, + backgroundDismiss: false, + backgroundDismissAnimation: 'shake', + autoClose: false, + closeIcon: null, + closeIconClass: false, + watchInterval: 100, + columnClass: 'col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1', + boxWidth: '50%', + scrollToPreviousElement: true, + scrollToPreviousElementAnimate: true, + useBootstrap: true, + offsetTop: 40, + offsetBottom: 40, + bootstrapClasses: { + container: 'container', + containerFluid: 'container-fluid', + row: 'row', + }, + onContentReady: () => {}, + onOpenBefore: () => {}, + onOpen: () => {}, + onClose: () => {}, + onDestroy: () => {}, + onAction: () => {} +}; + } + + api() { + const jc = $.confirm({ + title: 'awesome', + onContentReady: () => { + jc.setTitle(); + } +}); + } + + confirm_84() { + $.confirm({ + closeIcon: true, + buttons: { + buttonA: { + text: 'button a', + action: (buttonA: string) => { + return false; // prevent the modal from closing + } + }, + resetButton: (resetButton: string) => { + } + } +}); + } +} + +let firstName = 'Pierre'; +let lastName = 'Yotti'; +let type = new Confirm(firstName, lastName); diff --git a/types/confirmdialog/index.d.ts b/types/confirmdialog/index.d.ts new file mode 100644 index 0000000000..9b98ab2389 --- /dev/null +++ b/types/confirmdialog/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for confirmdialog 3.3 +// Project: https://github.com/allipierre/Type-definitions-for-jquery-confirm/tree/master/types/confirmDialog-js +// Definitions by: Alli Pierre Yotti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + + interface JQueryStatic { + /** + * confirm Dialog + * {confirmOptions} pOtions + */ + confirm(pOtions: options.confirmOptions | string, title?: string): any; + + /** + * confirm alert + * {any} pMessage + */ + alert(pMessage?: any, title?: string): any; + + /** + * confirm Dialog + * {any} pMessage + */ + dialog(pOtions: options.confirmOptions | string): any; +} + + interface JQuery { + /** + * confirm Dialog + * {confirmOptions} pOtions + */ + confirm(pOtions: options.confirmOptions | string, title?: string): any; + + /** + * confirm alert + * {any} pMessage + */ + alert(pMessage?: any, title?: string): any; + + /** + * confirm Dialog + * {any} pMessage + */ + dialog(pOtions: options.confirmOptions): any; +} + +interface Window { + setContentAppend: any; +} + +declare namespace options { + interface confirmOptions { + buttons?: any; + title?: string | boolean; + content?: any; + onContentReady?: any; + lazyOpen?: boolean; + closeIcon?: any; + type?: string; + typeAnimated?: boolean; + icon?: string; + closeIconClass?: string; + columnClass?: string; + containerFluid?: boolean; + boxWidth?: string; + useBootstrap?: boolean; + bootstrapClasses?: any; + draggable?: boolean; + dragWindowBorder?: boolean; + dragWindowGap?: number; + contentLoaded?: () => void; + autoClose?: string; + backgroundDismiss?: any; + backgroundDismissAnimation?: string; + escapeKey?: string | boolean; + onOpenBefore?: () => void; + onOpen?: () => void; + onClose?: () => void; + onDestroy?: () => void; + onAction?: () => void; + } + + interface buttonOptionss { + cancel?: () => void; + confirm?: () => void; + } +} + +declare namespace jconfirm { + let defaults: any; +} diff --git a/types/confirmdialog/tsconfig.json b/types/confirmdialog/tsconfig.json new file mode 100644 index 0000000000..95f33eb036 --- /dev/null +++ b/types/confirmdialog/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "target": "es6" + }, + "files": [ + "index.d.ts", + "confirmdialog-tests.ts" + ] +} diff --git a/types/confirmdialog/tslint.json b/types/confirmdialog/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/confirmdialog/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-inappbrowser/index.d.ts b/types/cordova-plugin-inappbrowser/index.d.ts index 1cf2c67642..47c58eadfa 100644 --- a/types/cordova-plugin-inappbrowser/index.d.ts +++ b/types/cordova-plugin-inappbrowser/index.d.ts @@ -39,7 +39,7 @@ interface InAppBrowser extends Window { * @param callback the function that executes when the event fires. The function is * passed an InAppBrowserEvent object as a parameter. */ - addEventListener(type: channel, callback: (event: InAppBrowserEvent) => void): void; + addEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void; // removeEventListener overloads /** * Removes a listener for an event from the InAppBrowser. @@ -51,7 +51,7 @@ interface InAppBrowser extends Window { * @param callback the function that executes when the event fires. The function is * passed an InAppBrowserEvent object as a parameter. */ - removeEventListener(type: channel, callback: (event: InAppBrowserEvent) => void): void; + removeEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void; /** Closes the InAppBrowser window. */ close(): void; /** Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. */ @@ -79,6 +79,14 @@ interface InAppBrowser extends Window { insertCSS(css: { code: string } | { file: string }, callback: () => void): void; } +type InAppBrowserEventListenerOrEventListenerObject = InAppBrowserEventListener | InAppBrowserEventListenerObject; + +type InAppBrowserEventListener = (evt: InAppBrowserEvent) => void; + +interface InAppBrowserEventListenerObject { + handleEvent(evt: InAppBrowserEvent): void; +} + interface InAppBrowserEvent extends Event { /** the eventname, either loadstart, loadstop, loaderror, or exit. */ type: string; diff --git a/types/cordova-plugin-inappbrowser/tsconfig.json b/types/cordova-plugin-inappbrowser/tsconfig.json index ff0151160c..f3d3cb59d3 100644 --- a/types/cordova-plugin-inappbrowser/tsconfig.json +++ b/types/cordova-plugin-inappbrowser/tsconfig.json @@ -5,10 +5,10 @@ "es6", "dom" ], - "noImplicitAny": false, + "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/crypto-js/index.d.ts b/types/crypto-js/index.d.ts index c3dad4637b..c066204df2 100644 --- a/types/crypto-js/index.d.ts +++ b/types/crypto-js/index.d.ts @@ -8,7 +8,7 @@ export as namespace CryptoJS; declare var CryptoJS: CryptoJS.Hashes; declare namespace CryptoJS { - type Hash = (message: string | LibWordArray, key?: string, ...options: any[]) => WordArray; + type Hash = (message: string | LibWordArray, key?: string | WordArray, ...options: any[]) => WordArray; interface Cipher { encrypt(message: string, secretPassphrase: string | WordArray, option?: CipherOption): WordArray; decrypt(encryptedMessage: string | WordArray, secretPassphrase: string | WordArray, option?: CipherOption): DecryptedMessage; diff --git a/types/defer-promise/defer-promise-tests.ts b/types/defer-promise/defer-promise-tests.ts new file mode 100644 index 0000000000..cdf80657f9 --- /dev/null +++ b/types/defer-promise/defer-promise-tests.ts @@ -0,0 +1,23 @@ +import defer = require('defer-promise'); + +// $ExpectType Deferred +const a = defer(); +// $ExpectType void +a.resolve(5); +// $ExpectError +a.resolve('foo'); +// $ExpectError +a.resolve(); + +// $ExpectType Deferred +const b = defer(); +// $ExpectType void +b.resolve(); +// $ExpectError +b.resolve(5); + +const c: DeferPromise.Deferred = defer(); +// $ExpectType void +c.resolve('foo'); +// $ExpectType Promise +c.promise; diff --git a/types/defer-promise/index.d.ts b/types/defer-promise/index.d.ts new file mode 100644 index 0000000000..8516e63b30 --- /dev/null +++ b/types/defer-promise/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for defer-promise 1.0 +// Project: https://github.com/75lb/defer-promise#readme +// Definitions by: Niklas Fiekas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +// tslint:disable-next-line no-unnecessary-generics +declare function defer(): DeferPromise.Deferred; + +export = defer; + +declare global { + namespace DeferPromise { + interface Deferred { + promise: Promise; + resolve(value: T | PromiseLike): void; + resolve(this: Deferred): void; + reject(reason?: any): void; + } + } +} diff --git a/types/defer-promise/tsconfig.json b/types/defer-promise/tsconfig.json new file mode 100644 index 0000000000..1aaa667626 --- /dev/null +++ b/types/defer-promise/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "es2015.Promise" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "defer-promise-tests.ts" + ] +} diff --git a/types/defer-promise/tslint.json b/types/defer-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/defer-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/double-ended-queue/double-ended-queue-tests.ts b/types/double-ended-queue/double-ended-queue-tests.ts new file mode 100644 index 0000000000..d6df205a77 --- /dev/null +++ b/types/double-ended-queue/double-ended-queue-tests.ts @@ -0,0 +1,24 @@ +import * as Deque from 'double-ended-queue'; + +const a = new Deque(); // $ExpectType Deque +const b = new Deque(6); // $ExpectType Deque +const c = new Deque([1, 2, 3]); // $ExpectError +const d = new Deque([1, 2, 3]); // $ExpectType Deque + +a.length; // $ExpectType number +a.push("foo"); // $ExpectError +a.push(4, 5); // $ExpectType number +a.unshift("foo"); // $ExpectError +a.unshift(4, 5); // $ExpectType number +a.pop(); // $ExpectType number | undefined +a.pop(2); // $ExpectError +a.shift(); // $ExpectType number | undefined +a.peekBack(); // $ExpectType number | undefined +a.peekFront(); // $ExpectType number | undefined +a.toArray(); // $ExpectType number[] +a.get(); // $ExpectError +a.get(null); // $ExpectError +a.get(1); // $ExpectType number | undefined +b.get(-1); // $ExpectType string | undefined +b.clear(); // $ExpectType void +b.isEmpty(); // $ExpectType boolean diff --git a/types/double-ended-queue/index.d.ts b/types/double-ended-queue/index.d.ts new file mode 100644 index 0000000000..b9aa30de1a --- /dev/null +++ b/types/double-ended-queue/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for double-ended-queue 2.1 +// Project: https://github.com/petkaantonov/deque +// Definitions by: Dmitry +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Deque { + readonly length: number; + push(...items: T[]): number; + unshift(...items: T[]): number; + pop(): T|undefined; + shift(): T|undefined; + toArray(): T[]; + peekBack(): T|undefined; + peekFront(): T|undefined; + get(index: number): T|undefined; + isEmpty(): boolean; + clear(): void; +} + +declare const Deque: { + prototype: Deque; + new (items?: ReadonlyArray): Deque; + new (capacity: number): Deque; // tslint:disable-line:no-unnecessary-generics +}; + +export = Deque; diff --git a/types/double-ended-queue/tsconfig.json b/types/double-ended-queue/tsconfig.json new file mode 100644 index 0000000000..5477379341 --- /dev/null +++ b/types/double-ended-queue/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "double-ended-queue-tests.ts" + ] +} diff --git a/types/double-ended-queue/tslint.json b/types/double-ended-queue/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/double-ended-queue/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 3eaa05aa30..7913e81d55 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -746,7 +746,7 @@ declare namespace Draft { } class ContentState extends Record { - static createFromBlockArray(blocks: Array, entityMap: any): ContentState; + static createFromBlockArray(blocks: Array, entityMap?: any): ContentState; static createFromText(text: string, delimiter?: string): ContentState; createEntity(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): ContentState; @@ -797,7 +797,7 @@ declare namespace Draft { class CharacterMetadata { static applyStyle(record: CharacterMetadata, style: string): CharacterMetadata; static removeStyle(record: CharacterMetadata, style: string): CharacterMetadata; - static applyEntity(record: CharacterMetadata, entityKey: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata, entityKey: string | null): CharacterMetadata; static applyEntity(record: CharacterMetadata): CharacterMetadata; /** * Use this function instead of the `CharacterMetadata` constructor. @@ -894,7 +894,7 @@ declare namespace Draft { static setBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; static mergeBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; - static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string): ContentState; + static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string | null): ContentState; } class RichTextEditorUtil { diff --git a/types/dvtng-jss/dvtng-jss-tests.ts b/types/dvtng-jss/dvtng-jss-tests.ts new file mode 100644 index 0000000000..2863bbfb66 --- /dev/null +++ b/types/dvtng-jss/dvtng-jss-tests.ts @@ -0,0 +1,16 @@ + + +jss.set('.demo', { + 'font-size': '15px', + 'color': 'red' +}); + +jss.get('.demo'); + +jss.get(); + +jss.getAll('.demo'); + +jss.remove('.demo'); + +jss.remove(); diff --git a/types/dvtng-jss/index.d.ts b/types/dvtng-jss/index.d.ts new file mode 100644 index 0000000000..18278d80d1 --- /dev/null +++ b/types/dvtng-jss/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for jss v0.6 +// Project: https://github.com/Box9/jss +// Definitions by: Valentin Robert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Properties { + [name: string]: string; +} + +interface Selectors { + [selector: string]: Properties; +} + +interface JSS { + /** + * Retrieve all rules added via JSS, organized by selectors + */ + get(): Selectors; + + /** + * Retrieve rules added via JSS for a given selector + * @param s CSS selector + */ + get(s: string): Properties; + + /** + * Retrieve all rules specified for a given selector (not necessarily added via JSS) + * @param s CSS selector + */ + getAll(s: string): Properties; + + /** + * Remove all rules added via JSS + */ + remove(): void; + + /** + * Remove all rules added via JSS for the given selector + */ + remove(s: string): void; + + /** + * Add or extend an existing rule + * @param s CSS selector + * @param p CSS properties + */ + set(s: string, p: Properties): void; +} + +declare var jss: JSS; diff --git a/types/dvtng-jss/tsconfig.json b/types/dvtng-jss/tsconfig.json new file mode 100644 index 0000000000..3d47f98d9f --- /dev/null +++ b/types/dvtng-jss/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dvtng-jss-tests.ts" + ] +} diff --git a/types/jquery.tooltipster/tslint.json b/types/dvtng-jss/tslint.json similarity index 100% rename from types/jquery.tooltipster/tslint.json rename to types/dvtng-jss/tslint.json diff --git a/types/ejs/ejs-tests.ts b/types/ejs/ejs-tests.ts index b5b46f03b5..a7b7b66944 100644 --- a/types/ejs/ejs-tests.ts +++ b/types/ejs/ejs-tests.ts @@ -1,3 +1,61 @@ +/// + import ejs = require("ejs"); -var people = ['geddy', 'neil', 'alex']; -var html = ejs.render('<%= people.join(", "); %>', { people: people }); +import { readFileSync as read } from 'fs'; +import LRU = require("lru-cache"); +import { TemplateFunction, Options } from "ejs"; + +const fileName = 'test.ejs'; +const people = ['geddy', 'neil', 'alex']; +const data = { people }; +const template = '<%= people.join(", "); %>'; +const options = { filename: fileName }; +let result: string; +let ejsFunction: TemplateFunction; + +const SimpleCallback = (err: any, html?: string) => { + if (err) { + return null; + } + return html; +}; + +result = ejs.render(template); +result = ejs.render(template, data); +result = ejs.render(template, data, options); + +result = ejs.renderFile(fileName, SimpleCallback); +result = ejs.renderFile(fileName, data, SimpleCallback); +result = ejs.renderFile(fileName, data, options, SimpleCallback); + +ejsFunction = ejs.compile(''); +ejsFunction = ejs.compile(read(fileName, "utf8")); +ejsFunction = ejs.compile(template); +ejsFunction = ejs.compile(template, options); +ejsFunction = ejs.compile(template, { cache: true, filename: fileName }); +ejsFunction = ejs.compile(template, { cache: true, filename: fileName, root: "./" }); +ejsFunction = ejs.compile(template, { context: { foo: 'FOO' } }); +ejsFunction = ejs.compile(template, { compileDebug: false }); +ejsFunction = ejs.compile(template, { client: true }); +ejsFunction = ejs.compile('<$= people.join(", "); $>', { delimiter: '$' }); +ejsFunction = ejs.compile('<%= locals.people.join(", "); %>', { _with: false }); +ejsFunction = ejs.compile('<%= locals.people.join(", "); %>', { strict: true }); +ejsFunction = ejs.compile('<%= it.people.join(", "); %>', { _with: false, localsName: "it" }); +ejsFunction = ejs.compile(template, { rmWhitespace: true }); +const customEscape = (str: string) => !str ? '' : str.toUpperCase(); +ejsFunction = ejs.compile(template, { escape: customEscape }); + +result = ejsFunction(); +result = ejsFunction({}); +result = ejsFunction(data); + +/** @see https://github.com/mde/ejs/tree/v2.5.7#custom-fileloader */ +ejs.fileLoader = (path: string) => ""; + +/** @see https://github.com/mde/ejs/tree/v2.5.7#caching */ +ejs.clearCache(); +ejs.cache = LRU(100); + +/** @see https://github.com/mde/ejs/tree/v2.5.7#custom-delimiters */ +ejs.delimiter = "%"; +delete ejs.delimiter; diff --git a/types/ejs/index.d.ts b/types/ejs/index.d.ts index a5bfb23ee9..e785f2c6ae 100644 --- a/types/ejs/index.d.ts +++ b/types/ejs/index.d.ts @@ -1,90 +1,124 @@ -// Type definitions for ejs.js v2.3.3 +// Type definitions for ejs.js 2.5 // Project: http://ejs.co/ -// Definitions by: Ben Liddicott +// Definitions by: Ben Liddicott // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -declare namespace Ejs { - type Data = { [name: string]: any }; - type Dependencies = string[]; - var cache: Cache; - var localsName: string; - function resolveInclude(name: string, filename: string): string; - function compile(template: string, opts?: Options): (TemplateFunction); - function render(template: string, data?: Data, opts?: Options): string; +export interface Data { + [name: string]: any; +} +/** + * EJS template function cache. This can be a LRU object from lru-cache NPM + * module. By default, it is {@link module:utils.cache}, a simple in-process + * cache that grows continuously. + */ +export let cache: Cache; +/** + * Name of the object containing the locals. + * + * This variable is overridden by {@link Options}`.localsName` if it is not + * `undefined`. + */ +export let localsName: string; +/** + * Get the path to the included file from the parent file path and the + * specified path. + */ +export function resolveInclude(name: string, filename: string, isDir: boolean): string; +/** + * Compile the given `str` of ejs into a template function. + */ +export function compile(template: string, opts?: Options): (TemplateFunction); +/** + * Render the given `template` of ejs. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + */ +export function render(template: string, data?: Data, opts?: Options): string; - type RenderFileCallback = (err: Error, str?: string) => T; - function renderFile(path: string, cb: RenderFileCallback): T; - function renderFile(path: string, data: Data, cb: RenderFileCallback): T; - function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; +export type RenderFileCallback = (err: Error, str?: string) => T; - function clearCache(): any; +/** + * Render an EJS file at the given `path` and callback `cb(err, str)`. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + */ +export function renderFile(path: string, cb: RenderFileCallback): T; +export function renderFile(path: string, data: Data, cb: RenderFileCallback): T; +export function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; - interface TemplateFunction { - (data: Data): any; - } - interface Options { - cache?: any; - filename?: string; - context?: any; - compileDebug?: boolean; - client?: boolean; - delimiter?: string; - debug?: any; - _with?: boolean; - } - class Template { - constructor(text: string, opts: Options); - opts: Options; - templateText: string; - mode: string; - truncate: boolean; - currentLine: number; - source: string; - dependencies: Dependencies; - createRegex(): RegExp; - compile(): TemplateFunction; - generateSource(): any; - parseTemplateText(): string[]; - scanLine(line: string): any; +/** + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. + */ +export function clearCache(): void; - } - namespace Template { - interface MODES { - EVAL: string; - ESCAPED: string; - RAW: string; - COMMENT: string; - LITERAL: string; - } - } - function escapeRegexChars(s: string): string; - function escapeXML(markup: string): string; - function shallowCopy(to: T1, fro: any): T1; - interface Cache { - _data: { [name: string]: any }; - set(key: string, val: any): any; - get(key: string): any; - } - function resolve(from1: string, to: string): string; - function resolve(from1: string, from2: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, from9: string, to: string): string; - function resolve(...args: string[]): string; - function normalize(path: string): string; - function isAbsolute(path: string): boolean; - function join(...args: string[]): string; - function relative(from: string, to: string): string; - var sep: string; - var delimiter: string; - function dirname(path: string): string; - function basename(path: string): string; - function extname(path: string): string; - function filter(xs: any, f: any): any; // TODO WHUT? +export type TemplateFunction = (data?: Data) => string; +export interface Options { + /** Compiled functions are cached, requires `filename` */ + cache?: boolean; + /** + * The name of the file being rendered. Not required if you are using `renderFile()`. + * Used by `cache` to key caches, and for includes. + */ + filename?: string; + /** Set project root for includes with an absolute path (/file.ejs). */ + root?: string; + /** Function execution context */ + context?: any; + /** When `false` no debug instrumentation is compiled */ + compileDebug?: boolean; + /** When `true`, compiles a function that can be rendered in the browser without needing to load the EJS Runtime (ejs.min.js). */ + client?: boolean; + /** Character to use with angle brackets for open/close */ + delimiter?: string; + /** Output generated function body */ + debug?: boolean; + /** When set to `true`, generated function is in strict mode */ + strict?: boolean; + /** + * Whether or not to use `with() {}` constructs. + * If `false` then the locals will be stored in the `locals` object. Set to `false` in strict mode. + */ + _with?: boolean; + /** Name to use for the object storing local variables when not using `with` Defaults to `locals` */ + localsName?: string; + /** + * Remove all safe-to-remove whitespace, including leading and trailing whitespace. + * It also enables a safer version of `-%>` line slurping for all scriptlet tags (it does not strip new lines of tags in the middle of a line). + */ + rmWhitespace?: boolean; + /** + * The escaping function used with `<%=` construct. + * It is used in rendering and is `.toString()`ed in the generation of client functions. + * (By default escapes XML). + */ + escape?(str: string): string; } -export = Ejs; +export function escapeRegexChars(s: string): string; +/** + * Escape characters reserved in XML. + * + * This is simply an export of {@link module:utils.escapeXML}. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + */ +export function escapeXML(markup: string): string; +export interface Cache { + set(key: string, val: TemplateFunction): void; + get(key: string): TemplateFunction; +} +export let delimiter: string; + +/** + * Custom file loader. Useful for template preprocessing or restricting access + * to a certain part of the filesystem. + */ +export function fileLoader(filePath: string): string; + +/** + * Name for detection of EJS. + */ +export const name = "ejs"; diff --git a/types/ejs/tslint.json b/types/ejs/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/ejs/tslint.json +++ b/types/ejs/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 1b45a237e5..dbf836c6ae 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -137,6 +137,7 @@ export interface ShardsResponse { total: number; successful: number; failed: number; + skipped: number; } /** @@ -638,6 +639,7 @@ export interface SearchResponse { fields?: any; highlight?: any; inner_hits?: any; + sort?: string[]; }>; }; aggregations?: any; diff --git a/types/electron-spellchecker/electron-spellchecker-tests.ts b/types/electron-spellchecker/electron-spellchecker-tests.ts new file mode 100644 index 0000000000..c62b3939c9 --- /dev/null +++ b/types/electron-spellchecker/electron-spellchecker-tests.ts @@ -0,0 +1,15 @@ +import { + SpellCheckHandler, + ContextMenuListener, + ContextMenuBuilder +} from "electron-spellchecker"; + +const spellCheckHandler = new SpellCheckHandler(); +spellCheckHandler.attachToInput(); + +spellCheckHandler.switchLanguage("en-US"); + +const contextMenuBuilder = new ContextMenuBuilder(spellCheckHandler); +const contextMenuListener = new ContextMenuListener(info => { + contextMenuBuilder.showPopupMenu(info); +}); diff --git a/types/electron-spellchecker/index.d.ts b/types/electron-spellchecker/index.d.ts new file mode 100644 index 0000000000..8c02cc8794 --- /dev/null +++ b/types/electron-spellchecker/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for electron-spellchecker 1.1 +// Project: https://github.com/paulcbetts/electron-spellchecker +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export type ContextMenuFormatter = (options: { word: string }) => string; + +export class SpellCheckHandler { + currentSpellchecker: this; + + attachToInput(): void; + autoUnloadDictionariesOnBlur(): void; + provideHintText(inputText: string): void; + switchLanguage(language: string): void; + getCorrectionsForMisspelling(misspelledWord: string): Promise; + addToDictionary(text: string): void; + + unsubscribe(): void; +} + +export class ContextMenuBuilder { + constructor( + spellCheckHandler?: SpellCheckHandler, + target?: Electron.BrowserWindow | Electron.WebviewTag | null, + debugMode?: boolean, + processMenu?: (menu: Electron.Menu) => Electron.Menu + ); + + setAlternateStringFormatter(formatter: { + [key: string]: ContextMenuFormatter; + }): void; + + showPopupMenu: (info: Electron.ContextMenuParams) => void; +} + +export class ContextMenuListener { + constructor( + handler: (info: Electron.ContextMenuParams) => void, + target?: Electron.BrowserWindow | Electron.WebviewTag | null + ); + + unsubscribe(): void; +} diff --git a/types/electron-spellchecker/package.json b/types/electron-spellchecker/package.json new file mode 100644 index 0000000000..eefa07e77a --- /dev/null +++ b/types/electron-spellchecker/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "electron": ">=1.6.10" + } +} diff --git a/types/electron-spellchecker/tsconfig.json b/types/electron-spellchecker/tsconfig.json new file mode 100644 index 0000000000..539cc30156 --- /dev/null +++ b/types/electron-spellchecker/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "electron-spellchecker-tests.ts" + ] +} diff --git a/types/electron-spellchecker/tslint.json b/types/electron-spellchecker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/electron-spellchecker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ember-mocha/ember-mocha-tests.ts b/types/ember-mocha/ember-mocha-tests.ts new file mode 100644 index 0000000000..a4c055c91b --- /dev/null +++ b/types/ember-mocha/ember-mocha-tests.ts @@ -0,0 +1,187 @@ +import { + describeComponent, describeModel, describeModule, + setResolver, setupAcceptanceTest, setupComponentTest, + setupModelTest, setupTest +} from 'ember-mocha'; +import { describe, it, beforeEach, afterEach, before, after } from 'mocha'; +import chai = require('chai'); +import Ember from "ember"; +import hbs from 'htmlbars-inline-precompile'; + +describeModule('name', function() { + beforeEach(function() { + }); + + it('test', function() { + }); +}); + +describeModule('name', 'description', function() { + it('test', function() { + }); +}); + +describeModule( + 'name', + 'description', + { + needs: ['service:notifications'] + }, + function() { + } +); + +describeModule('component:x-foo', 'TestModule callbacks', { + needs: [], + + beforeSetup() { + }, + setup() { + }, + teardown() { + }, + afterTeardown() { + } +}, function() { +}); + +describeComponent('x-foo', { + integration: true +}, function() { +}); + +describeComponent('x-foo', { + unit: true, + needs: ['helper:pluralize-string'] +}, function() { +}); + +describeComponent.skip( + 'block-slot', + 'Integration: BlockSlotComponent', + { + integration: true + }, + function() { + } +); + +describeModel('user', { + needs: ['model:child'] +}, function() { +}); + +describeModule('component:x-foo', 'TestModule callbacks', function() { + before(function() { + class I18n extends Ember.Object {} + + this.skip(); + this.timeout(1000); + this.registry.register('helper:i18n', I18n); + this.registry.register('helper:i18n', I18n, { singleton: true }); + this.register('service:i18n', {}); + this.inject.service('i18n'); + this.inject.service('i18n', { as: 'i18n' }); + this.factory('object:user').create(); + }); + + after(function() { + }); + + beforeEach(function() { + }); + + afterEach(function() { + }); +}); + +describe('setupTest', function() { + setupTest(); + + setupTest('service:ajax'); + + setupTest('service:ajax', { + unit: true + }); + + setupTest('controller:sidebar', { + // Specify the other units that are required for this test. + // needs: ['controller:foo'] + }); + + setupComponentTest('gravatar-image', { + // specify the other units that are required for this test + // needs: ['component:foo', 'helper:bar'] + }); + + setupModelTest('contact', { + // Specify the other units that are required for this test. + needs: [] + }); + + const Application = Ember.Application.extend(); + + setupAcceptanceTest({ Application }); + + it('test', function() { + }); +}); + +// if you don't have a custom resolver, do it like this: +setResolver(Ember.DefaultResolver.create()); + +it('renders', function() { + // setup the outer context + this.set('value', 'cat'); + this.on('action', function(result) { + chai.expect(result).to.equal('bar', 'The correct result was returned'); + chai.expect(this.get('value')).to.equal('cat'); + }); + + // render the component + this.render(hbs` + {{ x-foo value=value action="result" }} + `); + this.render('{{ x-foo value=value action="result" }}'); + this.render([ + '{{ x-foo value=value action="result" }}' + ]); + + chai.expect(this.$('div>.value').text()).to.equal('cat', 'The component shows the correct value'); + + this.$('button').click(); +}); + +it('renders', function() { + // creates the component instance + const subject = this.subject(); + + const subject2 = this.subject({ + item: 42 + }); + + const { inputFormat } = this.setProperties({ + inputFormat: 'M/D/YY', + outputFormat: 'MMMM D, YYYY', + date: '5/3/10' + }); + + const { inputFormat: if2, outputFormat } = this.getProperties('inputFormat', 'outputFormat'); + + const inputFormat2 = this.get('inputFormat'); + + // render the component on the page + this.render(); + chai.expect(this.$('.foo').text()).to.equal('bar'); +}); + +it('can calculate the result', function(assert) { + const subject = this.subject(); + + subject.set('value', 'foo'); + chai.assert.equal(subject.get('result'), 'bar'); +}); + +it.skip('disabled test'); + +it.skip('disabled test', function() { }); diff --git a/types/ember-mocha/index.d.ts b/types/ember-mocha/index.d.ts new file mode 100644 index 0000000000..6a16c54fde --- /dev/null +++ b/types/ember-mocha/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for ember-mocha 0.12 +// Project: https://github.com/emberjs/ember-mocha#readme +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { TestContext, ModuleCallbacks } from "ember-test-helpers"; +import Ember from 'ember'; +import { it as mochaIt, ISuiteCallbackContext } from 'mocha'; + +// these globals are re-exported as named exports by ember-mocha +type mochaBefore = typeof before; +type mochaAfter = typeof after; +type mochaBeforeEach = typeof beforeEach; +type mochaAfterEach = typeof afterEach; +type mochaSetup = typeof setup; +type mochaTeardown = typeof teardown; +type mochaSuiteSetup = typeof suiteSetup; +type mochaSuiteTeardown = typeof suiteTeardown; + +declare module 'ember-mocha' { + interface ContextDefinitionFunction { + (name: string, description: string, callbacks: ModuleCallbacks, tests: (this: ISuiteCallbackContext) => void): void; + (name: string, description: string, tests: (this: ISuiteCallbackContext) => void): void; + (name: string, callbacks: ModuleCallbacks, tests: (this: ISuiteCallbackContext) => void): void; + (name: string, tests: (this: ISuiteCallbackContext) => void): void; + } + + interface ContextDefinition extends ContextDefinitionFunction { + only: ContextDefinitionFunction; + skip: ContextDefinitionFunction; + } + + interface SetupTest { + (name?: string, callbacks?: ModuleCallbacks): void; + (callbacks: ModuleCallbacks): void; + } + + /** @deprecated Use setupTest instead */ + export const describeModule: ContextDefinition; + + /** @deprecated Use setupComponentTest instead */ + export const describeComponent: ContextDefinition; + + /** @deprecated Use setupModelTest instead */ + export const describeModel: ContextDefinition; + + export const setupTest: SetupTest; + export const setupAcceptanceTest: SetupTest; + export const setupComponentTest: SetupTest; + export const setupModelTest: SetupTest; + + export const it: typeof mochaIt; + + /** + * Sets a Resolver globally which will be used to look up objects from each test's container. + */ + export function setResolver(resolver: Ember.Resolver): void; +} + +declare module 'mocha' { + // augment test callback context + interface ITestCallbackContext extends TestContext {} + interface IHookCallbackContext extends TestContext {} + + // re-export mocha globals as named exports + export const describe: Mocha.IContextDefinition; + export const it: Mocha.ITestDefinition; + export const setup: mochaSetup; + export const teardown: mochaTeardown; + export const suiteSetup: mochaSuiteSetup; + export const suiteTeardown: mochaSuiteTeardown; + export const before: mochaBefore; + export const after: mochaAfter; + export const beforeEach: mochaBeforeEach; + export const afterEach: mochaAfterEach; +} diff --git a/types/ember-mocha/tsconfig.json b/types/ember-mocha/tsconfig.json new file mode 100644 index 0000000000..e9fdedfe7f --- /dev/null +++ b/types/ember-mocha/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-mocha-tests.ts" + ] +} diff --git a/types/ember-mocha/tslint.json b/types/ember-mocha/tslint.json new file mode 100644 index 0000000000..aed9a80a73 --- /dev/null +++ b/types/ember-mocha/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "only-arrow-functions": false, + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "unified-signatures": false, + "no-declare-current-package": false, + + // ERROR: An interface declaring no members is equivalent to its supertype. + // -- Not true when augmenting an interface + "no-empty-interface": false, + + // ERROR: interface name must not have an "I" prefix + // -- Augmenting @types/mocha which uses "I" prefix + "interface-name": false + } +} diff --git a/types/ember-qunit/ember-qunit-tests.ts b/types/ember-qunit/ember-qunit-tests.ts new file mode 100644 index 0000000000..de22ab3d94 --- /dev/null +++ b/types/ember-qunit/ember-qunit-tests.ts @@ -0,0 +1,107 @@ +import Ember from 'ember'; +import hbs from 'htmlbars-inline-precompile'; +import { test, skip, moduleFor, moduleForModel, moduleForComponent, setResolver } from 'ember-qunit'; + +moduleForComponent('x-foo', { + integration: true +}); + +moduleForComponent('x-foo', { + unit: true, + needs: ['helper:pluralize-string'] +}); + +moduleForModel('user', { + needs: ['model:child'] +}); + +moduleFor('controller:home'); + +moduleFor('component:x-foo', 'Some description'); + +moduleFor('component:x-foo', 'TestModule callbacks', { + beforeSetup() { + }, + + beforeEach(assert) { + this.registry.register('helper:i18n', {}); + this.register('service:i18n', {}); + this.inject.service('i18n'); + this.inject.service('i18n', { as: 'i18n' }); + this.factory('object:user').create(); + assert.ok(true); + }, + + afterEach(assert) { + assert.ok(true); + }, + + afterTeardown(assert) { + assert.ok(true); + } +}); + +// if you don't have a custom resolver, do it like this: +setResolver(Ember.DefaultResolver.create()); + +test('it renders', function(assert) { + assert.expect(2); + + // setup the outer context + this.set('value', 'cat'); + this.on('action', function(result) { + assert.equal(result, 'bar', 'The correct result was returned'); + assert.equal(this.get('value'), 'cat'); + }); + + // render the component + this.render(hbs` + {{ x-foo value=value action="result" }} + `); + this.render('{{ x-foo value=value action="result" }}'); + this.render([ + '{{ x-foo value=value action="result" }}' + ]); + + assert.equal(this.$('div>.value').text(), 'cat', 'The component shows the correct value'); + + this.$('button').click(); +}); + +test('it renders', function(assert) { + assert.expect(1); + + // creates the component instance + const subject = this.subject(); + + const subject2 = this.subject({ + item: 42 + }); + + const { inputFormat } = this.setProperties({ + inputFormat: 'M/D/YY', + outputFormat: 'MMMM D, YYYY', + date: '5/3/10' + }); + + const { inputFormat: if2, outputFormat } = this.getProperties('inputFormat', 'outputFormat'); + + const inputFormat2 = this.get('inputFormat'); + + // render the component on the page + this.render(); + assert.equal(this.$('.foo').text(), 'bar'); +}); + +test('It can calculate the result', function(assert) { + assert.expect(1); + + const subject = this.subject(); + + subject.set('value', 'foo'); + assert.equal(subject.get('result'), 'bar'); +}); + +skip('disabled test'); + +skip('disabled test', function(assert) { }); diff --git a/types/ember-qunit/index.d.ts b/types/ember-qunit/index.d.ts new file mode 100644 index 0000000000..0edc5c837f --- /dev/null +++ b/types/ember-qunit/index.d.ts @@ -0,0 +1,118 @@ +// Type definitions for ember-qunit 2.2 +// Project: https://github.com/emberjs/ember-qunit#readme +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +declare module 'ember-qunit' { + import Ember from 'ember'; + import { ModuleCallbacks } from "ember-test-helpers"; + + interface QUnitModuleCallbacks extends ModuleCallbacks, Hooks { + beforeSetup?(assert: Assert): void; + setup?(assert: Assert): void; + teardown?(assert: Assert): void; + afterTeardown?(assert: Assert): void; + } + + /** + * @param fullName The full name of the unit, ie controller:application, route:index. + * @param description The description of the module + */ + export function moduleFor(fullName: string, description: string, callbacks?: QUnitModuleCallbacks): void; + export function moduleFor(fullName: string, callbacks?: QUnitModuleCallbacks): void; + + /** + * @param fullName the short name of the component that you'd use in a template, ie x-foo, ic-tabs, etc. + * @param description The description of the module + */ + export function moduleForComponent(fullName: string, description: string, callbacks?: QUnitModuleCallbacks): void; + export function moduleForComponent(fullName: string, callbacks?: QUnitModuleCallbacks): void; + + /** + * @param fullName the short name of the model you'd use in store operations ie user, assignmentGroup, etc. + * @param description The description of the module + */ + export function moduleForModel(fullName: string, description: string, callbacks?: QUnitModuleCallbacks): void; + export function moduleForModel(fullName: string, callbacks?: QUnitModuleCallbacks): void; + + /** + * Sets a Resolver globally which will be used to look up objects from each test's container. + */ + export function setResolver(resolver: Ember.Resolver): void; + + export class QUnitAdapter extends Ember.Test.Adapter {} + + export { module, test, skip, only, todo } from 'qunit'; +} + +declare module 'qunit' { + import { TestContext } from "ember-test-helpers"; + + export const module: typeof QUnit.module; + + /** + * Add a test to run. + * + * Add a test to run using `QUnit.test()`. + * + * The `assert` argument to the callback contains all of QUnit's assertion + * methods. Use this argument to call your test assertions. + * + * `QUnit.test()` can automatically handle the asynchronous resolution of a + * Promise on your behalf if you return a thenable Promise as the result of + * your callback function. + * + * @param name Title of unit being tested + * @param callback Function to close over assertions + */ + export function test(name: string, callback: (this: TestContext, assert: Assert) => void): void; + + /** + * Adds a test to exclusively run, preventing all other tests from running. + * + * Use this method to focus your test suite on a specific test. QUnit.only + * will cause any other tests in your suite to be ignored. + * + * Note, that if more than one QUnit.only is present only the first instance + * will run. + * + * This is an alternative to filtering tests to run in the HTML reporter. It + * is especially useful when you use a console reporter or in a codebase + * with a large set of long running tests. + * + * @param name Title of unit being tested + * @param callback Function to close over assertions + */ + export function only(name: string, callback: (this: TestContext, assert: Assert) => void): void; + + /** + * Use this method to test a unit of code which is still under development (in a “todo” state). + * The test will pass as long as one failing assertion is present. + * + * If all assertions pass, then the test will fail signaling that `QUnit.todo` should + * be replaced by `QUnit.test`. + * + * @param name Title of unit being tested + * @param callback Function to close over assertions + */ + export function todo(name: string, callback: (this: TestContext, assert: Assert) => void): void; + + /** + * Adds a test like object to be skipped. + * + * Use this method to replace QUnit.test() instead of commenting out entire + * tests. + * + * This test's prototype will be listed on the suite as a skipped test, + * ignoring the callback argument and the respective global and module's + * hooks. + * + * @param Title of unit being tested + */ + export const skip: typeof QUnit.skip; + + export default QUnit; +} diff --git a/types/ember-qunit/tsconfig.json b/types/ember-qunit/tsconfig.json new file mode 100644 index 0000000000..845f5b1023 --- /dev/null +++ b/types/ember-qunit/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-qunit-tests.ts" + ] +} diff --git a/types/ember-qunit/tslint.json b/types/ember-qunit/tslint.json new file mode 100644 index 0000000000..5070b08af9 --- /dev/null +++ b/types/ember-qunit/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "only-arrow-functions": false, + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "no-declare-current-package": false + } +} diff --git a/types/ember-test-helpers/ember-test-helpers-tests.ts b/types/ember-test-helpers/ember-test-helpers-tests.ts new file mode 100644 index 0000000000..f21d554cfa --- /dev/null +++ b/types/ember-test-helpers/ember-test-helpers-tests.ts @@ -0,0 +1,25 @@ +/// +import { ModuleCallbacks, TestModule } from "ember-test-helpers"; +import wait from 'ember-test-helpers/wait'; +import hasEmberVersion from 'ember-test-helpers/has-ember-version'; + +function moduleFor(name: string, description: string, callbacks: ModuleCallbacks) { + const module = new TestModule(name, description, callbacks); + + QUnit.module(module.name, { + beforeEach() { + module.setup(); + }, + afterEach() { + module.teardown(); + } + }); +} + +async function testWait() { + await wait(); +} + +if (hasEmberVersion(2, 10)) { + // ... +} diff --git a/types/ember-test-helpers/index.d.ts b/types/ember-test-helpers/index.d.ts new file mode 100644 index 0000000000..26591d7d23 --- /dev/null +++ b/types/ember-test-helpers/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for ember-test-helpers 0.6 +// Project: https://github.com/emberjs/ember-test-helpers#readme +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +declare module 'ember-test-helpers' { + import Ember from 'ember'; + import DS from 'ember-data'; + import { TemplateFactory } from 'htmlbars-inline-precompile'; + import RSVP from "rsvp"; + + interface ModuleCallbacks { + integration?: boolean; + unit?: boolean; + needs?: string[]; + + beforeSetup?(assert?: any): void; + setup?(assert?: any): void; + teardown?(assert?: any): void; + afterTeardown?(assert?: any): void; + + [key: string]: any; + } + + interface TestContext { + get(key: string): any; + getProperties(...keys: K[]): Pick; + set(key: string, value: V): V; + setProperties

(hash: P): P; + on(actionName: string, handler: (this: TestContext, ...args: any[]) => any): void; + send(actionName: string): void; + $: JQueryStatic; + subject(options?: {}): any; + render(template?: string | string[] | TemplateFactory): void; + clearRender(): void; + registry: Ember.Registry; + container: Ember.Container; + dispatcher: Ember.EventDispatcher; + application: Ember.Application; + store: DS.Store; + register(fullName: string, factory: any): void; + factory(fullName: string): any; + inject: { + controller(name: string, options?: { as: string }): any; + service(name: string, options?: { as: string }): any; + }; + } + + class TestModule { + constructor(name: string, callbacks?: ModuleCallbacks); + constructor(name: string, description?: string, callbacks?: ModuleCallbacks); + + name: string; + subjectName: string; + description: string; + isIntegration: boolean; + callbacks: ModuleCallbacks; + context: TestContext; + resolver: Ember.Resolver; + + setup(assert?: any): RSVP.Promise; + teardown(assert?: any): RSVP.Promise; + getContext(): TestContext; + setContext(context: TestContext): void; + } + + class TestModuleForAcceptance extends TestModule {} + class TestModuleForIntegration extends TestModule {} + class TestModuleForComponent extends TestModule {} + class TestModuleForModel extends TestModule {} + + function getContext(): TestContext | undefined; + function setContext(context: TestContext): void; + function unsetContext(): void; + function setResolver(resolver: Ember.Resolver): void; +} + +declare module 'ember-test-helpers/wait' { + import RSVP from "rsvp"; + + interface WaitOptions { + waitForTimers?: boolean; + waitForAJAX?: boolean; + waitForWaiters?: boolean; + } + + export default function wait(options?: WaitOptions): RSVP.Promise; +} + +declare module 'ember-test-helpers/has-ember-version' { + export default function hasEmberVersion(major: number, minor: number): boolean; +} diff --git a/types/ember-test-helpers/tsconfig.json b/types/ember-test-helpers/tsconfig.json new file mode 100644 index 0000000000..dc9c583d1c --- /dev/null +++ b/types/ember-test-helpers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-test-helpers-tests.ts" + ] +} diff --git a/types/ember-test-helpers/tslint.json b/types/ember-test-helpers/tslint.json new file mode 100644 index 0000000000..659431c9ea --- /dev/null +++ b/types/ember-test-helpers/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "no-declare-current-package": false + } +} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index adef4e70c2..7839a3021c 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -300,7 +300,7 @@ declare module 'ember' { /** * Given a fullName return a corresponding instance. */ - lookup(fullName: string, options: {}): any; + lookup(fullName: string, options?: {}): any; } const _ContainerProxyMixin: Mixin<_ContainerProxyMixin>; @@ -2097,7 +2097,15 @@ declare module 'ember' { options?: { path?: string; resetNamespace?: boolean }, callback?: (this: RouterDSL) => void ): void; - mount(name: string): void; + mount( + name: string, + options?: { + as?: string, + path?: string, + resetNamespace?: boolean, + engineInfo?: any + } + ): void; } class Service extends Object {} /** diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index a4aa89af1a..9ec79ce281 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -20,4 +20,5 @@ AppRouter.map(function() { }); this.route('not-found', { path: '/*path' }); this.mount('my-engine'); + this.mount('my-engine', { as: 'some-other-engine', path: '/some-other-engine'}); }); diff --git a/types/event-kit/index.d.ts b/types/event-kit/index.d.ts index 01b68e8f26..2208ffaae3 100644 --- a/types/event-kit/index.d.ts +++ b/types/event-kit/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/event-kit // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export interface DisposableLike { dispose(): void; @@ -64,21 +64,12 @@ export class CompositeDisposable implements DisposableLike { clear(): void; } -/** - * Allows you to strongly type event emissions across your codebase. Additional - * key:value pairings merged into this interface will result in emissions under - * the value of each key being templated by the type of the associated value. - */ -export interface Emissions { - // tslint:disable-next-line:no-any - [key: string]: any; -} - /** * Utility class to be used when implementing event-based APIs that allows * for handlers registered via ::on to be invoked with calls to ::emit. */ -export class Emitter implements DisposableLike { +// tslint:disable-next-line:no-any +export class Emitter implements DisposableLike { disposed: boolean; /** Construct an emitter. */ diff --git a/types/firefox-webext-browser/firefox-webext-browser-tests.ts b/types/firefox-webext-browser/firefox-webext-browser-tests.ts new file mode 100644 index 0000000000..01d9cf9f3d --- /dev/null +++ b/types/firefox-webext-browser/firefox-webext-browser-tests.ts @@ -0,0 +1,10 @@ +browser.nonexistentNS; // $ExpectError +browser.nonexistentNS.unknownMethod(); // $ExpectError + +// Test that out overwritten things at least worked +browser.runtime.getManifest(); // $ExpectType WebExtensionManifest +browser.test; // $ExpectError +browser.manifest; // $ExpectError +browser._manifest; // $ExpectType typeof _manifest +browser._manifest.WebExtensionLangpackManifest; // $ExpectError +browser._manifest.NativeManifest; // $ExpectError diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts new file mode 100644 index 0000000000..326346be82 --- /dev/null +++ b/types/firefox-webext-browser/index.d.ts @@ -0,0 +1,3148 @@ +// Type definitions for WebExtension Development in FireFox 58.0 +// Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions +// Definitions by: Jacob Bom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 +// Generated using script at github.com/bomjacob/definitelytyped-firefox-webext-browser + +interface WebExtEventListener any> { + addListener: (callback: T) => void; + removeListener: (listener: T) => void; + hasListener: (listener: T) => boolean; +} + +interface Window { + browser: typeof browser; +} + +declare namespace browser.alarms { + /* alarms types */ + interface Alarm { + name: string; + scheduledTime: number; + periodInMinutes?: number; + } + + /* alarms functions */ + function create(alarmInfo: { + when?: number; + delayInMinutes?: number; + periodInMinutes?: number; + }): void; + function create(name: string, alarmInfo: { + when?: number; + delayInMinutes?: number; + periodInMinutes?: number; + }): void; + + function get(name?: string): Promise; + + function getAll(): Promise; + + function clear(name?: string): Promise; + + function clearAll(): Promise; + + /* alarms events */ + const onAlarm: WebExtEventListener<(name: Alarm) => void>; +} + +declare namespace browser._manifest { + /* _manifest types */ + type OptionalPermission = _OptionalPermission; + + type Permission = string | OptionalPermission | _Permission; + + interface ProtocolHandler { + name: string; + protocol: string | _ProtocolHandlerProtocol; + uriTemplate: ExtensionURL | HttpURL; + } + + interface WebExtensionManifest { + protocol_handlers?: ProtocolHandler[]; + default_locale?: string; + manifest_version: number; + minimum_chrome_version?: string; + minimum_opera_version?: string; + applications?: { + gecko?: FirefoxSpecificProperties; + }; + browser_specific_settings?: { + gecko?: FirefoxSpecificProperties; + }; + name: string; + short_name?: string; + description?: string; + author?: string; + version: string; + homepage_url?: string; + icons?: { + [key: number]: string; + }; + incognito?: _WebExtensionManifestIncognito; + background?: { + page: ExtensionURL; + persistent?: PersistentBackgroundProperty; + } | { + scripts: ExtensionURL[]; + persistent?: PersistentBackgroundProperty; + }; + options_ui?: { + page: ExtensionURL; + browser_style?: boolean; + chrome_style?: boolean; + open_in_tab?: boolean; + }; + content_scripts?: ContentScript[]; + content_security_policy?: string; + permissions?: PermissionOrOrigin[]; + optional_permissions?: OptionalPermissionOrOrigin[]; + web_accessible_resources?: string[]; + developer?: { + name?: string; + url?: string; + }; + theme?: ThemeType; + browser_action?: { + default_title?: string; + default_icon?: IconPath; + theme_icons?: ThemeIcons[]; + default_popup?: string; + browser_style?: boolean; + default_area?: _WebExtensionManifestBrowserActionDefaultArea; + }; + chrome_settings_overrides?: { + homepage?: string; + search_provider?: { + name: string; + keyword?: string; + search_url: string; + favicon_url?: string; + suggest_url?: string; + instant_url?: string; + image_url?: string; + search_url_post_params?: string; + instant_url_post_params?: string; + image_url_post_params?: string; + alternate_urls?: string[]; + prepopulated_id?: number; + is_default?: boolean; + }; + }; + commands?: { + suggested_key?: { + default?: KeyName; + mac?: KeyName; + linux?: KeyName; + windows?: KeyName; + chromeos?: string; + android?: string; + ios?: string; + additionalProperties?: string; + }; + description?: string; + }; + devtools_page?: ExtensionURL; + omnibox?: { + keyword: string; + }; + page_action?: { + default_title?: string; + default_icon?: IconPath; + default_popup?: string; + browser_style?: boolean; + }; + sidebar_action?: { + default_title?: string; + default_icon?: IconPath; + browser_style?: boolean; + default_panel: string; + }; + chrome_url_overrides?: { + newtab?: ExtensionURL; + bookmarks?: ExtensionURL; + history?: ExtensionURL; + }; + } + + interface ThemeIcons { + light: ExtensionURL; + dark: ExtensionURL; + size: number; + } + + type OptionalPermissionOrOrigin = OptionalPermission | MatchPattern; + + type PermissionOrOrigin = Permission | MatchPattern; + + type HttpURL = string; + + type ExtensionURL = string; + + type ImageDataOrExtensionURL = string; + + type ExtensionID = string; + + interface FirefoxSpecificProperties { + id?: ExtensionID; + update_url?: string; + strict_min_version?: string; + strict_max_version?: string; + } + + type MatchPattern = string | _MatchPattern; + + type MatchPatternInternal = string | _MatchPatternInternal; + + interface ContentScript { + matches: MatchPattern[]; + exclude_matches?: MatchPattern[]; + include_globs?: string[]; + exclude_globs?: string[]; + css?: ExtensionURL[]; + js?: ExtensionURL[]; + all_frames?: boolean; + match_about_blank?: boolean; + run_at?: extensionTypes.RunAt; + } + + type IconPath = { + [key: number]: ExtensionURL; + } | ExtensionURL; + + type IconImageData = { + [key: number]: ImageData; + } | ImageData; + + type ImageData = any; + + type UnrecognizedProperty = any; + + type PersistentBackgroundProperty = boolean; + + interface ThemeType { + images?: { + additional_backgrounds?: ImageDataOrExtensionURL[]; + headerURL?: ImageDataOrExtensionURL; + theme_frame?: ImageDataOrExtensionURL; + }; + colors?: { + accentcolor?: string; + frame?: number[]; + tab_text?: number[]; + textcolor?: string; + toolbar?: string; + toolbar_text?: string; + bookmark_text?: string; + toolbar_field?: string; + toolbar_field_text?: string; + toolbar_top_separator?: string; + toolbar_bottom_separator?: string; + toolbar_vertical_separator?: string; + }; + icons?: { + back?: ExtensionURL; + forward?: ExtensionURL; + reload?: ExtensionURL; + stop?: ExtensionURL; + bookmark_star?: ExtensionURL; + bookmark_menu?: ExtensionURL; + downloads?: ExtensionURL; + home?: ExtensionURL; + app_menu?: ExtensionURL; + cut?: ExtensionURL; + copy?: ExtensionURL; + paste?: ExtensionURL; + new_window?: ExtensionURL; + new_private_window?: ExtensionURL; + save_page?: ExtensionURL; + print?: ExtensionURL; + history?: ExtensionURL; + full_screen?: ExtensionURL; + find?: ExtensionURL; + options?: ExtensionURL; + addons?: ExtensionURL; + developer?: ExtensionURL; + synced_tabs?: ExtensionURL; + open_file?: ExtensionURL; + sidebars?: ExtensionURL; + subscribe?: ExtensionURL; + text_encoding?: ExtensionURL; + email_link?: ExtensionURL; + forget?: ExtensionURL; + pocket?: ExtensionURL; + getmsg?: ExtensionURL; + newmsg?: ExtensionURL; + address?: ExtensionURL; + reply?: ExtensionURL; + replyall?: ExtensionURL; + replylist?: ExtensionURL; + forwarding?: ExtensionURL; + delete?: ExtensionURL; + junk?: ExtensionURL; + file?: ExtensionURL; + nextUnread?: ExtensionURL; + prevUnread?: ExtensionURL; + mark?: ExtensionURL; + tag?: ExtensionURL; + compact?: ExtensionURL; + archive?: ExtensionURL; + chat?: ExtensionURL; + nextMsg?: ExtensionURL; + prevMsg?: ExtensionURL; + QFB?: ExtensionURL; + conversation?: ExtensionURL; + newcard?: ExtensionURL; + newlist?: ExtensionURL; + editcard?: ExtensionURL; + newim?: ExtensionURL; + send?: ExtensionURL; + spelling?: ExtensionURL; + attach?: ExtensionURL; + security?: ExtensionURL; + save?: ExtensionURL; + quote?: ExtensionURL; + buddy?: ExtensionURL; + join_chat?: ExtensionURL; + chat_accounts?: ExtensionURL; + calendar?: ExtensionURL; + tasks?: ExtensionURL; + synchronize?: ExtensionURL; + newevent?: ExtensionURL; + newtask?: ExtensionURL; + editevent?: ExtensionURL; + today?: ExtensionURL; + category?: ExtensionURL; + complete?: ExtensionURL; + priority?: ExtensionURL; + saveandclose?: ExtensionURL; + attendees?: ExtensionURL; + privacy?: ExtensionURL; + status?: ExtensionURL; + freebusy?: ExtensionURL; + timezones?: ExtensionURL; + }; + properties?: { + additional_backgrounds_alignment?: _ThemeTypeAdditionalBackgroundsAlignment[]; + additional_backgrounds_tiling?: _ThemeTypeAdditionalBackgroundsTiling[]; + }; + } + + type KeyName = string; + + enum _OptionalPermission { + browserSettings = "browserSettings", + cookies = "cookies", + clipboardRead = "clipboardRead", + clipboardWrite = "clipboardWrite", + geolocation = "geolocation", + idle = "idle", + notifications = "notifications", + topSites = "topSites", + webNavigation = "webNavigation", + webRequest = "webRequest", + webRequestBlocking = "webRequestBlocking", + bookmarks = "bookmarks", + find = "find", + history = "history", + activeTab = "activeTab", + tabs = "tabs" + } + + enum _Permission { + contextualIdentities = "contextualIdentities", + downloads = "downloads", + downloadsopen = "downloads.open", + identity = "identity", + management = "management", + alarms = "alarms", + mozillaAddons = "mozillaAddons", + storage = "storage", + unlimitedStorage = "unlimitedStorage", + privacy = "privacy", + proxy = "proxy", + nativeMessaging = "nativeMessaging", + theme = "theme", + browsingData = "browsingData", + devtools = "devtools", + geckoProfiler = "geckoProfiler", + menus = "menus", + contextMenus = "contextMenus", + pkcs11 = "pkcs11", + sessions = "sessions" + } + + enum _ProtocolHandlerProtocol { + bitcoin = "bitcoin", + geo = "geo", + gopher = "gopher", + im = "im", + irc = "irc", + ircs = "ircs", + magnet = "magnet", + mailto = "mailto", + mms = "mms", + news = "news", + nntp = "nntp", + sip = "sip", + sms = "sms", + smsto = "smsto", + ssh = "ssh", + tel = "tel", + urn = "urn", + webcal = "webcal", + wtai = "wtai", + xmpp = "xmpp" + } + + enum _WebExtensionManifestIncognito { + spanning = "spanning" + } + + enum _WebExtensionManifestBrowserActionDefaultArea { + navbar = "navbar", + menupanel = "menupanel", + tabstrip = "tabstrip", + personaltoolbar = "personaltoolbar" + } + + enum _MatchPattern { + all_urls = "" + } + + enum _MatchPatternInternal { + all_urls = "" + } + + enum _ThemeTypeAdditionalBackgroundsAlignment { + bottom = "bottom", + center = "center", + left = "left", + right = "right", + top = "top", + centerbottom = "center bottom", + centercenter = "center center", + centertop = "center top", + leftbottom = "left bottom", + leftcenter = "left center", + lefttop = "left top", + rightbottom = "right bottom", + rightcenter = "right center", + righttop = "right top" + } + + enum _ThemeTypeAdditionalBackgroundsTiling { + norepeat = "no-repeat", + repeat = "repeat", + repeatx = "repeat-x", + repeaty = "repeat-y" + } +} + +declare namespace browser.browserSettings { + /* browserSettings types */ + enum ImageAnimationBehavior { + normal = "normal", + none = "none", + once = "once" + } + + /* browserSettings properties */ + const allowPopupsForUserEvents: types.Setting; + + const cacheEnabled: types.Setting; + + const homepageOverride: types.Setting; + + const imageAnimationBehavior: types.Setting; + + const newTabPageOverride: types.Setting; + + const webNotificationsDisabled: types.Setting; +} + +declare namespace browser.clipboard { + type ArrayBuffer = any; + + enum _SetImageData { + jpeg = "jpeg", + png = "png" + } + + /* clipboard functions */ + function setImageData(imageData: ArrayBuffer, imageType: _SetImageData): void; +} + +declare namespace browser.contextualIdentities { + /* contextualIdentities types */ + interface ContextualIdentity { + name: string; + icon: string; + iconUrl: string; + color: string; + colorCode: string; + cookieStoreId: string; + } + + /* contextualIdentities functions */ + function get(cookieStoreId: string): void; + + function query(details: { + name?: string; + }): void; + + function create(details: { + name: string; + color: string; + icon: string; + }): void; + + function update(cookieStoreId: string, details: { + name?: string; + color?: string; + icon?: string; + }): void; + + function remove(cookieStoreId: string): void; + + /* contextualIdentities events */ + const onUpdated: WebExtEventListener<(changeInfo: { + contextualIdentity: ContextualIdentity; + }) => void>; + + const onCreated: WebExtEventListener<(changeInfo: { + contextualIdentity: ContextualIdentity; + }) => void>; + + const onRemoved: WebExtEventListener<(changeInfo: { + contextualIdentity: ContextualIdentity; + }) => void>; +} + +declare namespace browser.cookies { + /* cookies types */ + interface Cookie { + name: string; + value: string; + domain: string; + hostOnly: boolean; + path: string; + secure: boolean; + httpOnly: boolean; + session: boolean; + expirationDate?: number; + storeId: string; + } + + interface CookieStore { + id: string; + tabIds: number[]; + incognito: boolean; + } + + enum OnChangedCause { + evicted = "evicted", + expired = "expired", + explicit = "explicit", + expired_overwrite = "expired_overwrite", + overwrite = "overwrite" + } + + /* cookies functions */ + function get(details: { + url: string; + name: string; + storeId?: string; + }): Promise; + + function getAll(details: { + url?: string; + name?: string; + domain?: string; + path?: string; + secure?: boolean; + session?: boolean; + storeId?: string; + }): Promise; + + function set(details: { + url: string; + name?: string; + value?: string; + domain?: string; + path?: string; + secure?: boolean; + httpOnly?: boolean; + expirationDate?: number; + storeId?: string; + }): Promise; + + function remove(details: { + url: string; + name: string; + storeId?: string; + }): Promise<{ + url: string; + name: string; + storeId: string; + }>; + + function getAllCookieStores(): Promise; + + /* cookies events */ + const onChanged: WebExtEventListener<(changeInfo: { + removed: boolean; + cookie: Cookie; + cause: OnChangedCause; + }) => void>; +} + +declare namespace browser.downloads { + /* downloads types */ + enum FilenameConflictAction { + uniquify = "uniquify", + overwrite = "overwrite", + prompt = "prompt" + } + + enum InterruptReason { + FILE_FAILED = "FILE_FAILED", + FILE_ACCESS_DENIED = "FILE_ACCESS_DENIED", + FILE_NO_SPACE = "FILE_NO_SPACE", + FILE_NAME_TOO_LONG = "FILE_NAME_TOO_LONG", + FILE_TOO_LARGE = "FILE_TOO_LARGE", + FILE_VIRUS_INFECTED = "FILE_VIRUS_INFECTED", + FILE_TRANSIENT_ERROR = "FILE_TRANSIENT_ERROR", + FILE_BLOCKED = "FILE_BLOCKED", + FILE_SECURITY_CHECK_FAILED = "FILE_SECURITY_CHECK_FAILED", + FILE_TOO_SHORT = "FILE_TOO_SHORT", + NETWORK_FAILED = "NETWORK_FAILED", + NETWORK_TIMEOUT = "NETWORK_TIMEOUT", + NETWORK_DISCONNECTED = "NETWORK_DISCONNECTED", + NETWORK_SERVER_DOWN = "NETWORK_SERVER_DOWN", + NETWORK_INVALID_REQUEST = "NETWORK_INVALID_REQUEST", + SERVER_FAILED = "SERVER_FAILED", + SERVER_NO_RANGE = "SERVER_NO_RANGE", + SERVER_BAD_CONTENT = "SERVER_BAD_CONTENT", + SERVER_UNAUTHORIZED = "SERVER_UNAUTHORIZED", + SERVER_CERT_PROBLEM = "SERVER_CERT_PROBLEM", + SERVER_FORBIDDEN = "SERVER_FORBIDDEN", + USER_CANCELED = "USER_CANCELED", + USER_SHUTDOWN = "USER_SHUTDOWN", + CRASH = "CRASH" + } + + enum DangerType { + file = "file", + url = "url", + content = "content", + uncommon = "uncommon", + host = "host", + unwanted = "unwanted", + safe = "safe", + accepted = "accepted" + } + + enum State { + in_progress = "in_progress", + interrupted = "interrupted", + complete = "complete" + } + + interface DownloadItem { + id: number; + url: string; + referrer?: string; + filename: string; + incognito: boolean; + danger: DangerType; + mime: string; + startTime: string; + endTime?: string; + estimatedEndTime?: string; + state: State; + paused: boolean; + canResume: boolean; + error?: InterruptReason; + bytesReceived: number; + totalBytes: number; + fileSize: number; + exists: boolean; + byExtensionId?: string; + byExtensionName?: string; + } + + interface StringDelta { + current?: string; + previous?: string; + } + + interface DoubleDelta { + current?: number; + previous?: number; + } + + interface BooleanDelta { + current?: boolean; + previous?: boolean; + } + + type DownloadTime = string | extensionTypes.Date; + + interface DownloadQuery { + query?: string[]; + startedBefore?: DownloadTime; + startedAfter?: DownloadTime; + endedBefore?: DownloadTime; + endedAfter?: DownloadTime; + totalBytesGreater?: number; + totalBytesLess?: number; + filenameRegex?: string; + urlRegex?: string; + limit?: number; + orderBy?: string[]; + id?: number; + url?: string; + filename?: string; + danger?: DangerType; + mime?: string; + startTime?: string; + endTime?: string; + state?: State; + paused?: boolean; + error?: InterruptReason; + bytesReceived?: number; + totalBytes?: number; + fileSize?: number; + exists?: boolean; + } + + enum _DownloadMethod { + GET = "GET", + POST = "POST" + } + + /* downloads functions */ + function download(options: { + url: string; + filename?: string; + incognito?: boolean; + conflictAction?: FilenameConflictAction; + saveAs?: boolean; + method?: _DownloadMethod; + headers?: Array<{ + name: string; + value: string; + }>; + body?: string; + }): Promise; + + function search(query: DownloadQuery): Promise; + + function pause(downloadId: number): Promise; + + function resume(downloadId: number): Promise; + + function cancel(downloadId: number): Promise; + + function getFileIcon(downloadId: number, options?: { + size?: number; + }): Promise; + + function open(downloadId: number): Promise; + + function show(downloadId: number): Promise; + + function showDefaultFolder(): void; + + function erase(query: DownloadQuery): Promise; + + function removeFile(downloadId: number): Promise; + + const acceptDanger: ((downloadId: number) => void) | undefined; + + const drag: ((downloadId: number) => void) | undefined; + + const setShelfEnabled: ((enabled: boolean) => void) | undefined; + + /* downloads events */ + const onCreated: WebExtEventListener<(downloadItem: DownloadItem) => void>; + + const onErased: WebExtEventListener<(downloadId: number) => void>; + + const onChanged: WebExtEventListener<(downloadDelta: { + id: number; + url?: StringDelta; + filename?: StringDelta; + danger?: StringDelta; + mime?: StringDelta; + startTime?: StringDelta; + endTime?: StringDelta; + state?: StringDelta; + canResume?: BooleanDelta; + paused?: BooleanDelta; + error?: StringDelta; + totalBytes?: DoubleDelta; + fileSize?: DoubleDelta; + exists?: BooleanDelta; + }) => void>; +} + +declare namespace browser.events { + /* events types */ + interface Rule { + id?: string; + tags?: string[]; + conditions: any[]; + actions: any[]; + priority?: number; + } + + class Event { + addListener(): void; + + removeListener(): void; + + hasListener(): boolean; + + hasListeners(): boolean; + + addRules?(eventName: string, webViewInstanceId: number, rules: Rule[]): void; + + getRules?(eventName: string, webViewInstanceId: number, ruleIdentifiers?: string[]): void; + + removeRules?(eventName: string, webViewInstanceId: number, ruleIdentifiers?: string[]): void; + } + + interface UrlFilter { + hostContains?: string; + hostEquals?: string; + hostPrefix?: string; + hostSuffix?: string; + pathContains?: string; + pathEquals?: string; + pathPrefix?: string; + pathSuffix?: string; + queryContains?: string; + queryEquals?: string; + queryPrefix?: string; + querySuffix?: string; + urlContains?: string; + urlEquals?: string; + urlMatches?: string; + originAndPathMatches?: string; + urlPrefix?: string; + urlSuffix?: string; + schemes?: string[]; + ports?: Array; + } +} + +declare namespace browser.extension { + /* extension types */ + enum ViewType { + tab = "tab", + popup = "popup", + sidebar = "sidebar" + } + + /* extension properties */ + const lastError: { + message: string; + } | undefined; + + const inIncognitoContext: boolean | undefined; + + /* extension functions */ + function getURL(path: string): string; + + function getViews(fetchProperties?: { + type?: ViewType; + windowId?: number; + tabId?: number; + }): Window[]; + + function getBackgroundPage(): Window; + + function isAllowedIncognitoAccess(): Promise; + + function isAllowedFileSchemeAccess(): Promise; + + const setUpdateUrlData: ((data: string) => void) | undefined; + + /* extension events */ + const onRequest: WebExtEventListener<(request: any, sender: runtime.MessageSender, sendResponse: () => void) => void> + | WebExtEventListener<(sender: runtime.MessageSender, sendResponse: () => void) => void> | undefined; + + const onRequestExternal: WebExtEventListener<(request: any, sender: runtime.MessageSender, sendResponse: () => void) => void> + | WebExtEventListener<(sender: runtime.MessageSender, sendResponse: () => void) => void> | undefined; +} + +declare namespace browser.extensionTypes { + /* extensionTypes types */ + enum ImageFormat { + jpeg = "jpeg", + png = "png" + } + + interface ImageDetails { + format?: ImageFormat; + quality?: number; + } + + enum RunAt { + document_start = "document_start", + document_end = "document_end", + document_idle = "document_idle" + } + + enum CSSOrigin { + user = "user", + author = "author" + } + + interface InjectDetails { + code?: string; + file?: string; + allFrames?: boolean; + matchAboutBlank?: boolean; + frameId?: number; + runAt?: RunAt; + cssOrigin?: CSSOrigin; + } + + type Date = string | number | object/*Date*/; +} + +declare namespace browser.i18n { + /* i18n types */ + type LanguageCode = string; + + /* i18n functions */ + function getAcceptLanguages(): Promise; + + function getMessage(messageName: string, substitutions?: any): string; + + function getUILanguage(): string; + + function detectLanguage(text: string): Promise<{ + isReliable: boolean; + languages: Array<{ + language: LanguageCode; + percentage: number; + }>; + }>; +} + +declare namespace browser.identity { + /* identity types */ + interface AccountInfo { + id: string; + } + + /* identity functions */ + const getAccounts: (() => Promise) | undefined; + + const getAuthToken: ((details?: { + interactive?: boolean; + account?: AccountInfo; + scopes?: string[]; + }) => Promise) | undefined; + + const getProfileUserInfo: (() => Promise<{ + email: string; + id: string; + }>) | undefined; + + const removeCachedAuthToken: ((details: { + token: string; + }) => Promise<{ + email: string; + id: string; + }>) | undefined; + + function launchWebAuthFlow(details: { + url: string; + interactive?: boolean; + }): Promise; + + function getRedirectURL(path?: string): string; + + /* identity events */ + const onSignInChanged: WebExtEventListener<(account: AccountInfo, signedIn: boolean) => void> | undefined; +} + +declare namespace browser.idle { + /* idle types */ + enum IdleState { + active = "active", + idle = "idle" + } + + /* idle functions */ + function queryState(detectionIntervalInSeconds: number): Promise; + + function setDetectionInterval(intervalInSeconds: number): void; + + /* idle events */ + const onStateChanged: WebExtEventListener<(newState: IdleState) => void>; +} + +declare namespace browser.management { + /* management types */ + interface IconInfo { + size: number; + url: string; + } + + enum ExtensionDisabledReason { + unknown = "unknown", + permissions_increase = "permissions_increase" + } + + enum ExtensionType { + extension = "extension", + theme = "theme" + } + + enum ExtensionInstallType { + development = "development", + normal = "normal", + sideload = "sideload", + other = "other" + } + + interface ExtensionInfo { + id: string; + name: string; + shortName?: string; + description: string; + version: string; + versionName?: string; + mayDisable: boolean; + enabled: boolean; + disabledReason?: ExtensionDisabledReason; + type: ExtensionType; + homepageUrl?: string; + updateUrl?: string; + optionsUrl: string; + icons?: IconInfo[]; + permissions?: string[]; + hostPermissions?: string[]; + installType: ExtensionInstallType; + } + + /* management functions */ + function getAll(): Promise; + + function get(id: _manifest.ExtensionID): Promise; + + function getSelf(): Promise; + + function uninstallSelf(options?: { + showConfirmDialog?: boolean; + dialogMessage?: string; + }): Promise; + + function setEnabled(id: string, enabled: boolean): Promise; + + /* management events */ + const onDisabled: WebExtEventListener<(info: ExtensionInfo) => void>; + + const onEnabled: WebExtEventListener<(info: ExtensionInfo) => void>; + + const onInstalled: WebExtEventListener<(info: ExtensionInfo) => void>; + + const onUninstalled: WebExtEventListener<(info: ExtensionInfo) => void>; +} + +declare namespace browser.notifications { + /* notifications types */ + enum TemplateType { + basic = "basic", + image = "image", + list = "list", + progress = "progress" + } + + enum PermissionLevel { + granted = "granted", + denied = "denied" + } + + interface NotificationItem { + title: string; + message: string; + } + + interface CreateNotificationOptions { + type: TemplateType; + iconUrl?: string; + appIconMaskUrl?: string; + title: string; + message: string; + contextMessage?: string; + priority?: number; + eventTime?: number; + buttons?: Array<{ + title: string; + iconUrl?: string; + }>; + imageUrl?: string; + items?: NotificationItem[]; + progress?: number; + isClickable?: boolean; + } + + interface UpdateNotificationOptions { + type?: TemplateType; + iconUrl?: string; + appIconMaskUrl?: string; + title?: string; + message?: string; + contextMessage?: string; + priority?: number; + eventTime?: number; + buttons?: Array<{ + title: string; + iconUrl?: string; + }>; + imageUrl?: string; + items?: NotificationItem[]; + progress?: number; + isClickable?: boolean; + } + + /* notifications functions */ + function create(options: CreateNotificationOptions): Promise; + function create(notificationId: string, options: CreateNotificationOptions): Promise; + + const update: ((notificationId: string, options: UpdateNotificationOptions) => Promise) | undefined; + + function clear(notificationId: string): Promise; + + function getAll(): Promise; + + const getPermissionLevel: (() => Promise) | undefined; + + /* notifications events */ + const onClosed: WebExtEventListener<(notificationId: string, byUser: boolean) => void>; + + const onClicked: WebExtEventListener<(notificationId: string) => void>; + + const onButtonClicked: WebExtEventListener<(notificationId: string, buttonIndex: number) => void>; + + const onPermissionLevelChanged: WebExtEventListener<(level: PermissionLevel) => void> | undefined; + + const onShowSettings: WebExtEventListener<() => void> | undefined; + + const onShown: WebExtEventListener<(notificationId: string) => void>; +} + +declare namespace browser.permissions { + /* permissions types */ + interface Permissions { + permissions?: _manifest.OptionalPermission[]; + origins?: _manifest.MatchPattern[]; + } + + interface AnyPermissions { + permissions?: _manifest.Permission[]; + origins?: _manifest.MatchPatternInternal[]; + } + + /* permissions functions */ + function getAll(): Promise; + + function contains(permissions: AnyPermissions): Promise; + + function request(permissions: Permissions): Promise; + + function remove(permissions: Permissions): Promise; + + /* permissions events */ + const onAdded: WebExtEventListener<(permissions: Permissions) => void> | undefined; + + const onRemoved: WebExtEventListener<(permissions: Permissions) => void> | undefined; +} + +declare namespace browser.privacy { +} + +declare namespace browser.privacy.network { + /* privacy.network types */ + enum IPHandlingPolicy { + default = "default", + default_public_and_private_interfaces = "default_public_and_private_interfaces", + default_public_interface_only = "default_public_interface_only", + disable_non_proxied_udp = "disable_non_proxied_udp" + } + + /* privacy.network properties */ + const networkPredictionEnabled: types.Setting; + + const peerConnectionEnabled: types.Setting; + + const webRTCIPHandlingPolicy: types.Setting; +} + +declare namespace browser.privacy.services { + /* privacy.services properties */ + const passwordSavingEnabled: types.Setting; +} + +declare namespace browser.privacy.websites { + /* privacy.websites types */ + enum TrackingProtectionModeOption { + always = "always", + never = "never", + private_browsing = "private_browsing" + } + + /* privacy.websites properties */ + const thirdPartyCookiesAllowed: types.Setting | undefined; + + const hyperlinkAuditingEnabled: types.Setting; + + const referrersEnabled: types.Setting; + + const resistFingerprinting: types.Setting; + + const firstPartyIsolate: types.Setting; + + const protectedContentEnabled: types.Setting | undefined; + + const trackingProtectionMode: types.Setting; +} + +declare namespace browser.proxy { + /* proxy functions */ + function register(url: string): void; + + function unregister(): void; + + function registerProxyScript(url: string): void; + + /* proxy events */ + const onProxyError: WebExtEventListener<(error: object) => void>; +} + +declare namespace browser.runtime { + /* runtime types */ + interface Port { + name: string; + disconnect: () => void; + onDisconnect: events.Event; + onMessage: events.Event; + postMessage: () => void; + sender?: MessageSender; + } + + interface MessageSender { + tab?: tabs.Tab; + frameId?: number; + id?: string; + url?: string; + tlsChannelId?: string; + } + + enum PlatformOs { + mac = "mac", + win = "win", + android = "android", + cros = "cros", + linux = "linux", + openbsd = "openbsd" + } + + enum PlatformArch { + arm = "arm", + x8632 = "x86-32", + x8664 = "x86-64" + } + + interface PlatformInfo { + os: PlatformOs; + arch: PlatformArch; + nacl_arch?: PlatformNaclArch; + } + + interface BrowserInfo { + name: string; + vendor: string; + version: string; + buildID: string; + } + + enum RequestUpdateCheckStatus { + throttled = "throttled", + no_update = "no_update", + update_available = "update_available" + } + + enum OnInstalledReason { + install = "install", + update = "update", + browser_update = "browser_update" + } + + enum OnRestartRequiredReason { + app_update = "app_update", + os_update = "os_update", + periodic = "periodic" + } + + type PlatformNaclArch = any; + + /* runtime properties */ + const lastError: { + message?: string; + } | undefined; + + const id: string; + + /* runtime functions */ + function getBackgroundPage(): Promise; + + function openOptionsPage(): Promise; + + function getManifest(): _manifest.WebExtensionManifest; + + function getURL(path: string): string; + + function setUninstallURL(url: string): Promise; + + function reload(): void; + + const requestUpdateCheck: (() => Promise) | undefined; + + const restart: (() => void) | undefined; + + function connect(connectInfo?: { + name?: string; + includeTlsChannelId?: boolean; + }): Port; + function connect(extensionId: string, connectInfo?: { + name?: string; + includeTlsChannelId?: boolean; + }): Port; + + function connectNative(application: string): Port; + + function sendMessage(message: any, options?: { + includeTlsChannelId?: boolean; + toProxyScript?: boolean; + }, responseCallback?: (response: any) => void): void; + function sendMessage(extensionId: string, message: any, options: { + includeTlsChannelId?: boolean; + toProxyScript?: boolean; + }, responseCallback?: (response: any) => void): void; + + function sendNativeMessage(application: string, message: any, responseCallback?: (response: any) => void): void; + + function getBrowserInfo(): Promise; + + function getPlatformInfo(): Promise; + + const getPackageDirectoryEntry: (() => Promise) | undefined; + + /* runtime events */ + const onStartup: WebExtEventListener<() => void>; + + const onInstalled: WebExtEventListener<(details: { + reason: OnInstalledReason; + previousVersion?: string; + temporary: boolean; + id?: string; + }) => void>; + + const onSuspend: WebExtEventListener<() => void> | undefined; + + const onSuspendCanceled: WebExtEventListener<() => void> | undefined; + + const onUpdateAvailable: WebExtEventListener<(details: { + version: string; + }) => void>; + + const onBrowserUpdateAvailable: WebExtEventListener<() => void> | undefined; + + const onConnect: WebExtEventListener<(port: Port) => void>; + + const onConnectExternal: WebExtEventListener<(port: Port) => void>; + + const onMessage: WebExtEventListener<(message: any, sender: MessageSender, sendResponse: () => void) => boolean> + | WebExtEventListener<(sender: MessageSender, sendResponse: () => void) => boolean>; + + const onMessageExternal: WebExtEventListener<(message: any, sender: MessageSender, sendResponse: () => void) => boolean> + | WebExtEventListener<(sender: MessageSender, sendResponse: () => void) => boolean>; + + const onRestartRequired: WebExtEventListener<(reason: OnRestartRequiredReason) => void> | undefined; +} + +declare namespace browser.storage { + /* storage types */ + interface StorageChange { + oldValue?: any; + newValue?: any; + } + + class StorageArea { + get(keys?: string | string[] | object): Promise; + + getBytesInUse?(keys?: string | string[]): Promise; + + set(items: any): Promise; + + remove(keys: string | string[]): Promise; + + clear(): Promise; + } + + /* storage properties */ + const sync: StorageArea; + + const local: StorageArea; + + const managed: StorageArea; + + /* storage events */ + const onChanged: WebExtEventListener<(changes: StorageChange, areaName: string) => void>; +} + +declare namespace browser.theme { + /* theme types */ + interface ThemeUpdateInfo { + theme: object; + windowId?: number; + } + + /* theme functions */ + function getCurrent(windowId?: number): void; + + function update(details: _manifest.ThemeType): void; + function update(windowId: number, details: _manifest.ThemeType): void; + + function reset(windowId?: number): void; + + /* theme events */ + const onUpdated: WebExtEventListener<(updateInfo: ThemeUpdateInfo) => void>; +} + +declare namespace browser.topSites { + /* topSites types */ + interface MostVisitedURL { + url: string; + title?: string; + } + + /* topSites functions */ + function get(options?: { + providers?: string[]; + }): Promise; +} + +declare namespace browser.types { + /* types types */ + enum SettingScope { + regular = "regular", + regular_only = "regular_only", + incognito_persistent = "incognito_persistent", + incognito_session_only = "incognito_session_only" + } + + enum LevelOfControl { + not_controllable = "not_controllable", + controlled_by_other_extensions = "controlled_by_other_extensions", + controllable_by_this_extension = "controllable_by_this_extension", + controlled_by_this_extension = "controlled_by_this_extension" + } + + class Setting { + get(details: { + incognito?: boolean; + }): Promise<{ + value: any; + levelOfControl: LevelOfControl; + incognitoSpecific?: boolean; + }>; + + set(details: { + value: any; + scope?: SettingScope; + }): Promise; + + clear(details: { + scope?: SettingScope; + }): Promise; + + onChange: WebExtEventListener<(details: { + value: any; + levelOfControl: LevelOfControl; + incognitoSpecific?: boolean; + }) => void>; + } +} + +declare namespace browser.webNavigation { + /* webNavigation types */ + enum TransitionType { + link = "link", + typed = "typed", + auto_bookmark = "auto_bookmark", + auto_subframe = "auto_subframe", + manual_subframe = "manual_subframe", + generated = "generated", + start_page = "start_page", + form_submit = "form_submit", + reload = "reload", + keyword = "keyword", + keyword_generated = "keyword_generated" + } + + enum TransitionQualifier { + client_redirect = "client_redirect", + server_redirect = "server_redirect", + forward_back = "forward_back", + from_address_bar = "from_address_bar" + } + + interface EventUrlFilters { + url: events.UrlFilter[]; + } + + /* webNavigation functions */ + function getFrame(details: { + tabId: number; + processId?: number; + frameId: number; + }): Promise<{ + errorOccurred?: boolean; + url: string; + tabId: number; + frameId: number; + parentFrameId: number; + }>; + + function getAllFrames(details: { + tabId: number; + }): Promise>; + + /* webNavigation events */ + const onBeforeNavigate: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + parentFrameId: number; + timeStamp: number; + }) => void>; + + const onCommitted: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + transitionType?: TransitionType; + transitionQualifiers?: TransitionQualifier[]; + timeStamp: number; + }) => void>; + + const onDOMContentLoaded: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + timeStamp: number; + }) => void>; + + const onCompleted: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + timeStamp: number; + }) => void>; + + const onErrorOccurred: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + error?: string; + timeStamp: number; + }) => void>; + + const onCreatedNavigationTarget: WebExtEventListener<(details: { + sourceTabId: number; + sourceProcessId: number; + sourceFrameId: number; + url: string; + tabId: number; + timeStamp: number; + }) => void>; + + const onReferenceFragmentUpdated: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + transitionType?: TransitionType; + transitionQualifiers?: TransitionQualifier[]; + timeStamp: number; + }) => void>; + + const onTabReplaced: WebExtEventListener<(details: { + replacedTabId: number; + tabId: number; + timeStamp: number; + }) => void>; + + const onHistoryStateUpdated: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + transitionType?: TransitionType; + transitionQualifiers?: TransitionQualifier[]; + timeStamp: number; + }) => void>; +} + +declare namespace browser.webRequest { + /* webRequest types */ + enum ResourceType { + main_frame = "main_frame", + sub_frame = "sub_frame", + stylesheet = "stylesheet", + script = "script", + image = "image", + object = "object", + object_subrequest = "object_subrequest", + xmlhttprequest = "xmlhttprequest", + xbl = "xbl", + xslt = "xslt", + ping = "ping", + beacon = "beacon", + xml_dtd = "xml_dtd", + font = "font", + media = "media", + websocket = "websocket", + csp_report = "csp_report", + imageset = "imageset", + web_manifest = "web_manifest", + other = "other" + } + + enum OnBeforeRequestOptions { + blocking = "blocking", + requestBody = "requestBody" + } + + enum OnBeforeSendHeadersOptions { + requestHeaders = "requestHeaders", + blocking = "blocking" + } + + enum OnSendHeadersOptions { + requestHeaders = "requestHeaders" + } + + enum OnHeadersReceivedOptions { + blocking = "blocking", + responseHeaders = "responseHeaders" + } + + enum OnAuthRequiredOptions { + responseHeaders = "responseHeaders", + blocking = "blocking", + asyncBlocking = "asyncBlocking" + } + + enum OnResponseStartedOptions { + responseHeaders = "responseHeaders" + } + + enum OnBeforeRedirectOptions { + responseHeaders = "responseHeaders" + } + + enum OnCompletedOptions { + responseHeaders = "responseHeaders" + } + + interface RequestFilter { + urls: string[]; + types?: ResourceType[]; + tabId?: number; + windowId?: number; + } + + type HttpHeaders = Array<{ + name: string; + value?: string; + binaryValue?: number[]; + }>; + + interface BlockingResponse { + cancel?: boolean; + redirectUrl?: string; + requestHeaders?: HttpHeaders; + responseHeaders?: HttpHeaders; + authCredentials?: { + username: string; + password: string; + }; + } + + interface UploadData { + bytes?: any; + file?: string; + } + + /* webRequest properties */ + const MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES: number; + + /* webRequest functions */ + function handlerBehaviorChanged(): Promise; + + function filterResponseData(requestId: string): object/*StreamFilter*/; + + /* webRequest events */ + const onBeforeRequest: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + requestBody?: { + error?: string; + formData?: object; + raw?: UploadData[]; + }; + tabId: number; + type: ResourceType; + timeStamp: number; + }) => BlockingResponse>; + + const onBeforeSendHeaders: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + requestHeaders?: HttpHeaders; + }) => BlockingResponse>; + + const onSendHeaders: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + requestHeaders?: HttpHeaders; + }) => void>; + + const onHeadersReceived: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + statusLine: string; + responseHeaders?: HttpHeaders; + statusCode: number; + }) => BlockingResponse>; + + const onAuthRequired: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + scheme: string; + realm?: string; + challenger: { + host: string; + port: number; + }; + isProxy: boolean; + responseHeaders?: HttpHeaders; + statusLine: string; + statusCode: number; + }) => BlockingResponse>; + + const onResponseStarted: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + statusCode: number; + responseHeaders?: HttpHeaders; + statusLine: string; + }) => void>; + + const onBeforeRedirect: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + statusCode: number; + redirectUrl: string; + responseHeaders?: HttpHeaders; + statusLine: string; + }) => void>; + + const onCompleted: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + statusCode: number; + responseHeaders?: HttpHeaders; + statusLine: string; + }) => void>; + + const onErrorOccurred: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + error: string; + }) => void>; +} + +declare namespace browser.bookmarks { + /* bookmarks types */ + enum BookmarkTreeNodeUnmodifiable { + managed = "managed" + } + + enum BookmarkTreeNodeType { + bookmark = "bookmark", + folder = "folder", + separator = "separator" + } + + interface BookmarkTreeNode { + id: string; + parentId?: string; + index?: number; + url?: string; + title: string; + dateAdded?: number; + dateGroupModified?: number; + unmodifiable?: BookmarkTreeNodeUnmodifiable; + type?: BookmarkTreeNodeType; + children?: BookmarkTreeNode[]; + } + + interface CreateDetails { + parentId?: string; + index?: number; + title?: string; + url?: string; + type?: BookmarkTreeNodeType; + } + + export {_import as import}; + + export {_export as export}; + + /* bookmarks functions */ + function get(idOrIdList: string | string[]): Promise; + + function getChildren(id: string): Promise; + + function getRecent(numberOfItems: number): Promise; + + function getTree(): Promise; + + function getSubTree(id: string): Promise; + + function search(query: string | { + query?: string; + url?: string; + title?: string; + }): Promise; + + function create(bookmark: CreateDetails): Promise; + + function move(id: string, destination: { + parentId?: string; + index?: number; + }): Promise; + + function update(id: string, changes: { + title?: string; + url?: string; + }): Promise; + + function remove(id: string): Promise; + + function removeTree(id: string): Promise; + + const _import: (() => Promise) | undefined; + + const _export: (() => Promise) | undefined; + + /* bookmarks events */ + const onCreated: WebExtEventListener<(id: string, bookmark: BookmarkTreeNode) => void>; + + const onRemoved: WebExtEventListener<(id: string, removeInfo: { + parentId: string; + index: number; + node: BookmarkTreeNode; + }) => void>; + + const onChanged: WebExtEventListener<(id: string, changeInfo: { + title: string; + url?: string; + }) => void>; + + const onMoved: WebExtEventListener<(id: string, moveInfo: { + parentId: string; + index: number; + oldParentId: string; + oldIndex: number; + }) => void>; + + const onChildrenReordered: WebExtEventListener<(id: string, reorderInfo: { + childIds: string[]; + }) => void> | undefined; + + const onImportBegan: WebExtEventListener<() => void> | undefined; + + const onImportEnded: WebExtEventListener<() => void> | undefined; +} + +declare namespace browser.browserAction { + /* browserAction types */ + type ColorArray = [number, number, number, number]; + + type ImageDataType = object/*ImageData*/; + + /* browserAction functions */ + function setTitle(details: { + title: string; + tabId?: number; + }): Promise; + + function getTitle(details: { + tabId?: number; + }): Promise; + + function setIcon(details: { + imageData?: ImageDataType | { + [key: number]: ImageDataType; + }; + path?: string | { + [key: number]: string; + }; + tabId?: number; + }): Promise; + + function setPopup(details: { + tabId?: number; + popup: string; + }): Promise; + + function getPopup(details: { + tabId?: number; + }): Promise; + + function setBadgeText(details: { + text: string; + tabId?: number; + }): Promise; + + function getBadgeText(details: { + tabId?: number; + }): Promise; + + function setBadgeBackgroundColor(details: { + color: string | ColorArray; + tabId?: number; + }): Promise; + + function getBadgeBackgroundColor(details: { + tabId?: number; + }): Promise; + + function enable(tabId?: number): Promise; + + function disable(tabId?: number): Promise; + + function openPopup(): void; + + /* browserAction events */ + const onClicked: WebExtEventListener<(tab: tabs.Tab) => void>; +} + +declare namespace browser.browsingData { + /* browsingData types */ + interface RemovalOptions { + since?: extensionTypes.Date; + hostnames?: string[]; + originTypes?: { + unprotectedWeb?: boolean; + protectedWeb?: boolean; + extension?: boolean; + }; + } + + interface DataTypeSet { + cache?: boolean; + cookies?: boolean; + downloads?: boolean; + formData?: boolean; + history?: boolean; + indexedDB?: boolean; + localStorage?: boolean; + serverBoundCertificates?: boolean; + passwords?: boolean; + pluginData?: boolean; + serviceWorkers?: boolean; + } + + /* browsingData functions */ + function settings(): Promise<{ + options: RemovalOptions; + dataToRemove: DataTypeSet; + dataRemovalPermitted: DataTypeSet; + }>; + + function remove(options: RemovalOptions, dataToRemove: DataTypeSet): Promise; + + const removeAppcache: ((options: RemovalOptions) => Promise) | undefined; + + function removeCache(options: RemovalOptions): Promise; + + function removeCookies(options: RemovalOptions): Promise; + + function removeDownloads(options: RemovalOptions): Promise; + + const removeFileSystems: ((options: RemovalOptions) => Promise) | undefined; + + function removeFormData(options: RemovalOptions): Promise; + + function removeHistory(options: RemovalOptions): Promise; + + const removeIndexedDB: ((options: RemovalOptions) => Promise) | undefined; + + function removeLocalStorage(options: RemovalOptions): Promise; + + function removePluginData(options: RemovalOptions): Promise; + + function removePasswords(options: RemovalOptions): Promise; + + const removeWebSQL: ((options: RemovalOptions) => Promise) | undefined; +} + +declare namespace browser.commands { + /* commands types */ + interface Command { + name?: string; + description?: string; + shortcut?: string; + } + + /* commands functions */ + function getAll(): Promise; + + /* commands events */ + const onCommand: WebExtEventListener<(command: string) => void>; +} + +declare namespace browser.devtools { +} + +declare namespace browser.devtools.inspectedWindow { + /* devtools.inspectedWindow types */ + class Resource { + url: string; + + getContent?(): Promise; + + setContent?(content: string, commit: boolean): Promise; + } + + /* devtools.inspectedWindow properties */ + const tabId: number; + + /* devtools.inspectedWindow functions */ + function eval(expression: string, options?: { + frameURL?: string; + useContentScriptContext?: boolean; + contextSecurityOrigin?: string; + }): Promise; + + function reload(reloadOptions?: { + ignoreCache?: boolean; + userAgent?: string; + injectedScript?: string; + preprocessorScript?: string; + }): void; + + const getResources: (() => Promise) | undefined; + + /* devtools.inspectedWindow events */ + const onResourceAdded: WebExtEventListener<(resource: Resource) => void> | undefined; + + const onResourceContentCommitted: WebExtEventListener<(resource: Resource, content: string) => void> | undefined; +} + +declare namespace browser.devtools.network { + /* devtools.network types */ + class Request { + getContent(): Promise; + } + + /* devtools.network functions */ + const getHAR: (() => Promise) | undefined; + + /* devtools.network events */ + const onRequestFinished: WebExtEventListener<(request: Request) => void> | undefined; + + const onNavigated: WebExtEventListener<(url: string) => void>; +} + +declare namespace browser.devtools.panels { + /* devtools.panels types */ + class ElementsPanel { + createSidebarPane(title: string): Promise; + + onSelectionChanged: WebExtEventListener<() => void>; + } + + class SourcesPanel { + createSidebarPane?(title: string): void; + + onSelectionChanged: WebExtEventListener<() => void>; + } + + class ExtensionPanel { + createStatusBarButton?(iconPath: string, tooltipText: string, disabled: boolean): Button; + + onSearch: WebExtEventListener<(action: string, queryString?: string) => void>; + onShown: WebExtEventListener<(window: object/*global*/) => void>; + onHidden: WebExtEventListener<() => void>; + } + + class ExtensionSidebarPane { + setHeight?(height: string): void; + + setExpression(expression: string, rootTitle?: string): Promise; + + setObject(jsonObject: string, rootTitle?: string): Promise; + + setPage?(path: string): void; + + onShown: WebExtEventListener<(window: object/*global*/) => void>; + onHidden: WebExtEventListener<() => void>; + } + + class Button { + update?(tooltipText?: string, disabled?: boolean): void; + update?(disabled?: boolean): void; + update?(iconPath: string, tooltipText: string, disabled?: boolean): void; + + onClicked: WebExtEventListener<() => void>; + } + + /* devtools.panels properties */ + const elements: ElementsPanel; + + const sources: SourcesPanel; + + const themeName: string; + + /* devtools.panels functions */ + function create(title: string, iconPath: string, pagePath: string): Promise; + + const setOpenResourceHandler: (() => Promise) | undefined; + + const openResource: ((url: string, lineNumber: number) => Promise) | undefined; + + /* devtools.panels events */ + const onThemeChanged: WebExtEventListener<(themeName: string) => void>; +} + +declare namespace browser.find { + /* find functions */ + function find(queryphrase: string, params?: { + tabId?: number; + caseSensitive?: boolean; + entireWord?: boolean; + includeRectData?: boolean; + includeRangeData?: boolean; + }): void; + + function highlightResults(params?: { + rangeIndex?: number; + tabId?: number; + noScroll?: boolean; + }): void; + + function removeHighlighting(tabId?: number): void; +} + +declare namespace browser.geckoProfiler { + /* geckoProfiler types */ + enum ProfilerFeature { + java = "java", + js = "js", + leaf = "leaf", + mainthreadio = "mainthreadio", + memory = "memory", + privacy = "privacy", + restyle = "restyle", + stackwalk = "stackwalk", + tasktracer = "tasktracer", + threads = "threads" + } + + /* geckoProfiler functions */ + function start(settings: { + bufferSize: number; + interval: number; + features: ProfilerFeature[]; + threads?: string[]; + }): void; + + function stop(): void; + + function pause(): void; + + function resume(): void; + + function getProfile(): void; + + function getProfileAsArrayBuffer(): void; + + function getSymbols(debugName: string, breakpadId: string): void; + + /* geckoProfiler events */ + const onRunning: WebExtEventListener<(isRunning: boolean) => void>; +} + +declare namespace browser.history { + /* history types */ + enum TransitionType { + link = "link", + typed = "typed", + auto_bookmark = "auto_bookmark", + auto_subframe = "auto_subframe", + manual_subframe = "manual_subframe", + generated = "generated", + auto_toplevel = "auto_toplevel", + form_submit = "form_submit", + reload = "reload", + keyword = "keyword", + keyword_generated = "keyword_generated" + } + + interface HistoryItem { + id: string; + url?: string; + title?: string; + lastVisitTime?: number; + visitCount?: number; + typedCount?: number; + } + + interface VisitItem { + id: string; + visitId: string; + visitTime?: number; + referringVisitId: string; + transition: TransitionType; + } + + /* history functions */ + function search(query: { + text: string; + startTime?: extensionTypes.Date; + endTime?: extensionTypes.Date; + maxResults?: number; + }): Promise; + + function getVisits(details: { + url: string; + }): Promise; + + function addUrl(details: { + url: string; + title?: string; + transition?: TransitionType; + visitTime?: extensionTypes.Date; + }): Promise; + + function deleteUrl(details: { + url: string; + }): Promise; + + function deleteRange(range: { + startTime: extensionTypes.Date; + endTime: extensionTypes.Date; + }): Promise; + + function deleteAll(): Promise; + + /* history events */ + const onVisited: WebExtEventListener<(result: HistoryItem) => void>; + + const onVisitRemoved: WebExtEventListener<(removed: { + allHistory: boolean; + urls: string[]; + }) => void>; + + const onTitleChanged: WebExtEventListener<(changed: { + url: string; + title: string; + }) => void>; +} + +declare namespace browser.contextMenus { + /* contextMenus types */ + enum ContextType { + all = "all", + page = "page", + frame = "frame", + selection = "selection", + link = "link", + editable = "editable", + password = "password", + image = "image", + video = "video", + audio = "audio", + launcher = "launcher", + browser_action = "browser_action", + page_action = "page_action", + tab = "tab" + } + + enum ItemType { + normal = "normal", + checkbox = "checkbox", + radio = "radio", + separator = "separator" + } + + interface OnClickData { + menuItemId: number | string; + parentMenuItemId?: number | string; + mediaType?: string; + linkText?: string; + linkUrl?: string; + srcUrl?: string; + pageUrl?: string; + frameUrl?: string; + selectionText?: string; + editable: boolean; + wasChecked?: boolean; + checked?: boolean; + modifiers: _OnClickDataModifiers[]; + } + + enum _OnClickDataModifiers { + Shift = "Shift", + Alt = "Alt", + Command = "Command", + Ctrl = "Ctrl", + MacCtrl = "MacCtrl" + } + + /* contextMenus properties */ + const ACTION_MENU_TOP_LEVEL_LIMIT: number; + + /* contextMenus functions */ + function create(createProperties: { + type?: ItemType; + id?: string; + icons?: { + [key: number]: string; + }; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + command?: string; + }): number | string; + + function update(id: number | string, updateProperties: { + type?: ItemType; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + }): Promise; + + function remove(menuItemId: number | string): Promise; + + function removeAll(): Promise; + + /* contextMenus events */ + const onClicked: WebExtEventListener<(info: OnClickData, tab?: tabs.Tab) => void>; +} + +declare namespace browser.menus { + /* menus types */ + enum ContextType { + all = "all", + page = "page", + frame = "frame", + selection = "selection", + link = "link", + editable = "editable", + password = "password", + image = "image", + video = "video", + audio = "audio", + launcher = "launcher", + browser_action = "browser_action", + page_action = "page_action", + tab = "tab", + tools_menu = "tools_menu" + } + + enum ItemType { + normal = "normal", + checkbox = "checkbox", + radio = "radio", + separator = "separator" + } + + interface OnClickData { + menuItemId: number | string; + parentMenuItemId?: number | string; + mediaType?: string; + linkText?: string; + linkUrl?: string; + srcUrl?: string; + pageUrl?: string; + frameUrl?: string; + selectionText?: string; + editable: boolean; + wasChecked?: boolean; + checked?: boolean; + modifiers: _OnClickDataModifiers[]; + } + + enum _OnClickDataModifiers { + Shift = "Shift", + Alt = "Alt", + Command = "Command", + Ctrl = "Ctrl", + MacCtrl = "MacCtrl" + } + + /* menus properties */ + const ACTION_MENU_TOP_LEVEL_LIMIT: number; + + /* menus functions */ + function create(createProperties: { + type?: ItemType; + id?: string; + icons?: { + [key: number]: string; + }; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + command?: string; + }): number | string; + + function update(id: number | string, updateProperties: { + type?: ItemType; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + }): Promise; + + function remove(menuItemId: number | string): Promise; + + function removeAll(): Promise; + + /* menus events */ + const onClicked: WebExtEventListener<(info: OnClickData, tab?: tabs.Tab) => void>; +} + +declare namespace browser.menusInternal { + /* menusInternal types */ + interface OnClickData { + menuItemId: number | string; + parentMenuItemId?: number | string; + mediaType?: string; + linkUrl?: string; + srcUrl?: string; + pageUrl?: string; + frameUrl?: string; + selectionText?: string; + editable: boolean; + wasChecked?: boolean; + checked?: boolean; + } +} + +declare namespace browser.omnibox { + /* omnibox types */ + enum DescriptionStyleType { + url = "url", + match = "match", + dim = "dim" + } + + enum OnInputEnteredDisposition { + currentTab = "currentTab", + newForegroundTab = "newForegroundTab", + newBackgroundTab = "newBackgroundTab" + } + + interface SuggestResult { + content: string; + description: string; + descriptionStyles?: Array<{ + offset: number; + type: DescriptionStyleType; + length?: number; + }>; + descriptionStylesRaw?: Array<{ + offset: number; + type: number; + }>; + } + + interface DefaultSuggestResult { + description: string; + descriptionStyles?: Array<{ + offset: number; + type: DescriptionStyleType; + length?: number; + }>; + descriptionStylesRaw?: Array<{ + offset: number; + type: number; + }>; + } + + /* omnibox functions */ + function setDefaultSuggestion(suggestion: DefaultSuggestResult): void; + + /* omnibox events */ + const onInputStarted: WebExtEventListener<() => void>; + + const onInputChanged: WebExtEventListener<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void>; + + const onInputEntered: WebExtEventListener<(text: string, disposition: OnInputEnteredDisposition) => void>; + + const onInputCancelled: WebExtEventListener<() => void>; +} + +declare namespace browser.pageAction { + /* pageAction types */ + type ImageDataType = object/*ImageData*/; + + /* pageAction functions */ + function show(tabId: number): Promise; + + function hide(tabId: number): Promise; + + function setTitle(details: { + tabId: number; + title: string; + }): void; + + function getTitle(details: { + tabId: number; + }): Promise; + + function setIcon(details: { + tabId: number; + imageData?: ImageDataType | { + [key: number]: ImageDataType; + }; + path?: string | { + [key: number]: string; + }; + }): Promise; + + function setPopup(details: { + tabId: number; + popup: string; + }): void; + + function getPopup(details: { + tabId: number; + }): Promise; + + function openPopup(): void; + + /* pageAction events */ + const onClicked: WebExtEventListener<(tab: tabs.Tab) => void>; +} + +declare namespace browser.pkcs11 { + /* pkcs11 functions */ + function isModuleInstalled(name: string): void; + + function installModule(name: string, flags?: number): void; + + function uninstallModule(name: string): void; + + function getModuleSlots(name: string): void; +} + +declare namespace browser.sessions { + /* sessions types */ + interface Filter { + maxResults?: number; + } + + interface Session { + lastModified: number; + tab?: tabs.Tab; + window?: windows.Window; + } + + interface Device { + info: string; + deviceName: string; + sessions: Session[]; + } + + /* sessions properties */ + const MAX_SESSION_RESULTS: number; + + /* sessions functions */ + function forgetClosedTab(windowId: number, sessionId: string): void; + + function forgetClosedWindow(sessionId: string): void; + + function getRecentlyClosed(filter?: Filter): Promise; + + const getDevices: ((filter?: Filter) => Promise) | undefined; + + function restore(sessionId?: string): Promise; + + function setTabValue(tabId: number, key: string, value: any): void; + + function getTabValue(tabId: number, key: string): void; + + function removeTabValue(tabId: number, key: string): void; + + function setWindowValue(windowId: number, key: string, value: any): void; + + function getWindowValue(windowId: number, key: string): void; + + function removeWindowValue(windowId: number, key: string): void; + + /* sessions events */ + const onChanged: WebExtEventListener<() => void>; +} + +declare namespace browser.sidebarAction { + /* sidebarAction types */ + type ImageDataType = object/*ImageData*/; + + /* sidebarAction functions */ + function setTitle(details: { + title: string; + tabId?: number; + }): void; + + function getTitle(details: { + tabId?: number; + }): void; + + function setIcon(details: { + imageData?: ImageDataType | { + [key: number]: ImageDataType; + }; + path?: string; + tabId?: number; + }): void; + + function setPanel(details: { + tabId?: number; + panel: string; + }): void; + + function getPanel(details: { + tabId?: number; + }): void; + + function open(): void; + + function close(): void; +} + +declare namespace browser.tabs { + /* tabs types */ + enum MutedInfoReason { + user = "user", + capture = "capture", + extension = "extension" + } + + interface MutedInfo { + muted: boolean; + reason?: MutedInfoReason; + extensionId?: string; + } + + interface Tab { + id?: number; + index: number; + windowId?: number; + openerTabId?: number; + selected?: boolean; + highlighted: boolean; + active: boolean; + pinned: boolean; + lastAccessed?: number; + audible?: boolean; + mutedInfo?: MutedInfo; + url?: string; + title?: string; + favIconUrl?: string; + status?: string; + discarded?: boolean; + incognito: boolean; + width?: number; + height?: number; + sessionId?: string; + cookieStoreId?: string; + isArticle?: boolean; + isInReaderMode?: boolean; + } + + enum ZoomSettingsMode { + automatic = "automatic", + manual = "manual", + disabled = "disabled" + } + + enum ZoomSettingsScope { + perorigin = "per-origin", + pertab = "per-tab" + } + + interface ZoomSettings { + mode?: ZoomSettingsMode; + scope?: ZoomSettingsScope; + defaultZoomFactor?: number; + } + + interface PageSettings { + orientation?: number; + scaling?: number; + shrinkToFit?: boolean; + showBackgroundColors?: boolean; + showBackgroundImages?: boolean; + paperSizeUnit?: number; + paperWidth?: number; + paperHeight?: number; + headerLeft?: string; + headerCenter?: string; + headerRight?: string; + footerLeft?: string; + footerCenter?: string; + footerRight?: string; + marginLeft?: number; + marginRight?: number; + marginTop?: number; + marginBottom?: number; + } + + enum TabStatus { + loading = "loading", + complete = "complete" + } + + enum WindowType { + normal = "normal", + popup = "popup", + panel = "panel", + app = "app", + devtools = "devtools" + } + + /* tabs properties */ + const TAB_ID_NONE: number; + + /* tabs functions */ + function get(tabId: number): Promise; + + function getCurrent(): Promise; + + function connect(tabId: number, connectInfo?: { + name?: string; + frameId?: number; + }): runtime.Port; + + const sendRequest: ((tabId: number, request: any, responseCallback?: (response: any) => void) => void) | undefined; + + function sendMessage(tabId: number, message: any, options: { + frameId?: number; + }, responseCallback?: (response: any) => void): void; + + const getSelected: ((windowId?: number) => Promise) | undefined; + + const getAllInWindow: ((windowId?: number) => Promise) | undefined; + + function create(createProperties: { + windowId?: number; + index?: number; + url?: string; + active?: boolean; + selected?: boolean; + pinned?: boolean; + openerTabId?: number; + cookieStoreId?: string; + openInReaderMode?: boolean; + }): Promise; + + function duplicate(tabId: number): Promise; + + function query(queryInfo: { + active?: boolean; + pinned?: boolean; + audible?: boolean; + muted?: boolean; + highlighted?: boolean; + currentWindow?: boolean; + lastFocusedWindow?: boolean; + status?: TabStatus; + discarded?: boolean; + title?: string; + url?: string | string[]; + windowId?: number; + windowType?: WindowType; + index?: number; + cookieStoreId?: string; + openerTabId?: number; + }): Promise; + + const highlight: ((highlightInfo: { + windowId?: number; + tabs: number[] | number; + }) => Promise) | undefined; + + function update(updateProperties: { + url?: string; + active?: boolean; + highlighted?: boolean; + selected?: boolean; + pinned?: boolean; + muted?: boolean; + openerTabId?: number; + loadReplace?: boolean; + }): Promise; + function update(tabId: number, updateProperties: { + url?: string; + active?: boolean; + highlighted?: boolean; + selected?: boolean; + pinned?: boolean; + muted?: boolean; + openerTabId?: number; + loadReplace?: boolean; + }): Promise; + + function move(tabIds: number | number[], moveProperties: { + windowId?: number; + index: number; + }): Promise; + + function reload(reloadProperties?: { + bypassCache?: boolean; + }): Promise; + function reload(tabId: number, reloadProperties?: { + bypassCache?: boolean; + }): Promise; + + function remove(tabIds: number | number[]): Promise; + + function discard(tabIds: number | number[]): void; + + function detectLanguage(tabId?: number): Promise; + + function toggleReaderMode(tabId?: number): void; + + function captureVisibleTab(options?: extensionTypes.ImageDetails): Promise; + function captureVisibleTab(windowId: number, options?: extensionTypes.ImageDetails): Promise; + + function executeScript(details: extensionTypes.InjectDetails): Promise; + function executeScript(tabId: number, details: extensionTypes.InjectDetails): Promise; + + function insertCSS(details: extensionTypes.InjectDetails): Promise; + function insertCSS(tabId: number, details: extensionTypes.InjectDetails): Promise; + + function removeCSS(details: extensionTypes.InjectDetails): Promise; + function removeCSS(tabId: number, details: extensionTypes.InjectDetails): Promise; + + function setZoom(zoomFactor: number): Promise; + function setZoom(tabId: number, zoomFactor: number): Promise; + + function getZoom(tabId?: number): Promise; + + function setZoomSettings(zoomSettings: ZoomSettings): Promise; + function setZoomSettings(tabId: number, zoomSettings: ZoomSettings): Promise; + + function getZoomSettings(tabId?: number): Promise; + + function print(): void; + + function printPreview(): Promise; + + function saveAsPDF(pageSettings: PageSettings): Promise; + + /* tabs events */ + const onCreated: WebExtEventListener<(tab: Tab) => void>; + + const onUpdated: WebExtEventListener<(tabId: number, changeInfo: { + status: string; + discarded?: boolean; + url?: string; + pinned?: boolean; + audible?: boolean; + mutedInfo?: MutedInfo; + favIconUrl?: string; + }, tab: Tab) => void>; + + const onMoved: WebExtEventListener<(tabId: number, moveInfo: { + windowId: number; + fromIndex: number; + toIndex: number; + }) => void>; + + const onSelectionChanged: WebExtEventListener<(tabId: number, selectInfo: { + windowId: number; + }) => void> | undefined; + + const onActiveChanged: WebExtEventListener<(tabId: number, selectInfo: { + windowId: number; + }) => void> | undefined; + + const onActivated: WebExtEventListener<(activeInfo: { + tabId: number; + windowId: number; + }) => void>; + + const onHighlightChanged: WebExtEventListener<(selectInfo: { + windowId: number; + tabIds: number[]; + }) => void> | undefined; + + const onHighlighted: WebExtEventListener<(highlightInfo: { + windowId: number; + tabIds: number[]; + }) => void>; + + const onDetached: WebExtEventListener<(tabId: number, detachInfo: { + oldWindowId: number; + oldPosition: number; + }) => void>; + + const onAttached: WebExtEventListener<(tabId: number, attachInfo: { + newWindowId: number; + newPosition: number; + }) => void>; + + const onRemoved: WebExtEventListener<(tabId: number, removeInfo: { + windowId: number; + isWindowClosing: boolean; + }) => void>; + + const onReplaced: WebExtEventListener<(addedTabId: number, removedTabId: number) => void>; + + const onZoomChange: WebExtEventListener<(ZoomChangeInfo: { + tabId: number; + oldZoomFactor: number; + newZoomFactor: number; + zoomSettings: ZoomSettings; + }) => void>; +} + +declare namespace browser.windows { + /* windows types */ + enum WindowType { + normal = "normal", + popup = "popup", + panel = "panel", + app = "app", + devtools = "devtools" + } + + enum WindowState { + normal = "normal", + minimized = "minimized", + maximized = "maximized", + fullscreen = "fullscreen", + docked = "docked" + } + + interface Window { + id?: number; + focused: boolean; + top?: number; + left?: number; + width?: number; + height?: number; + tabs?: tabs.Tab[]; + incognito: boolean; + type?: WindowType; + state?: WindowState; + alwaysOnTop: boolean; + sessionId?: string; + title?: string; + } + + enum CreateType { + normal = "normal", + popup = "popup", + panel = "panel", + detached_panel = "detached_panel" + } + + /* windows properties */ + const WINDOW_ID_NONE: number; + + const WINDOW_ID_CURRENT: number; + + /* windows functions */ + function get(windowId: number, getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function getCurrent(getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function getLastFocused(getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function getAll(getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function create(createData?: { + url?: string | string[]; + tabId?: number; + left?: number; + top?: number; + width?: number; + height?: number; + focused?: boolean; + incognito?: boolean; + type?: CreateType; + state?: WindowState; + allowScriptsToClose?: boolean; + titlePreface?: string; + }): Promise; + + function update(windowId: number, updateInfo: { + left?: number; + top?: number; + width?: number; + height?: number; + focused?: boolean; + drawAttention?: boolean; + state?: WindowState; + titlePreface?: string; + }): Promise; + + function remove(windowId: number): Promise; + + /* windows events */ + const onCreated: WebExtEventListener<(window: Window) => void>; + + const onRemoved: WebExtEventListener<(windowId: number) => void>; + + const onFocusChanged: WebExtEventListener<(windowId: number) => void>; +} diff --git a/types/firefox-webext-browser/tsconfig.json b/types/firefox-webext-browser/tsconfig.json new file mode 100644 index 0000000000..202f6824d1 --- /dev/null +++ b/types/firefox-webext-browser/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "firefox-webext-browser-tests.ts" + ] +} diff --git a/types/firefox-webext-browser/tslint.json b/types/firefox-webext-browser/tslint.json new file mode 100644 index 0000000000..c94feb08d9 --- /dev/null +++ b/types/firefox-webext-browser/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false, + "unified-signatures": false, + "no-unnecessary-qualifier": false + } +} diff --git a/types/first-mate/index.d.ts b/types/first-mate/index.d.ts index c7df2365c3..2fcc7141cb 100644 --- a/types/first-mate/index.d.ts +++ b/types/first-mate/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/first-mate/ // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { Disposable } from "event-kit"; diff --git a/types/fixed-data-table-2/fixed-data-table-2-tests.tsx b/types/fixed-data-table-2/fixed-data-table-2-tests.tsx new file mode 100644 index 0000000000..3b34d6a44a --- /dev/null +++ b/types/fixed-data-table-2/fixed-data-table-2-tests.tsx @@ -0,0 +1,196 @@ +/** + * The tests are based on tests from types/fixed-data-table + */ + +import * as React from "react"; +import { Table, Cell, Column, CellProps } from "fixed-data-table-2"; + +// create your Table +class MyTable1 extends React.Component { + render() { + return ( + + // add columns +
+ ); + } +} + +// create your Columns +class MyTable2 extends React.Component { + render() { + return ( + + Basic content} + width={200} + /> +
+ ); + } +} + +// provide Custom Data +interface MyTable3State { + myTableData: Array<{ name: string }>; +} + +class MyTable3 extends React.Component<{}, MyTable3State> { + constructor(props: {}) { + super(props); + + this.state = { + myTableData: [ + { name: "Rylan" }, + { name: "Amelia" }, + { name: "Estevan" }, + { name: "Florence" }, + { name: "Tressa" }, + ] + }; + } + + render() { + return ( + + Name} + cell={(props) => ( + + {this.state.myTableData[props.rowIndex].name} + + )} + width={200} + /> +
+ ); + } +} + +// Create Reusable Cells +interface RowData { + [field: string]: string; +} + +interface MyCellProps extends CellProps { + field: string; + myData: RowData[]; +} + +class MyTextCell extends React.Component { + render() { + const { rowIndex, field, myData } = this.props; + + return ( + + {myData[rowIndex!][field]} + + ); + } +} + +class MyLinkCell extends React.Component { + render() { + const { rowIndex, field, myData } = this.props; + const link: string = myData[rowIndex!][field]; + + return ( + + {link} + + ); + } +} + +interface MyTable4State { + tableData: RowData[]; +} + +class MyTable4 extends React.Component<{}, MyTable4State> { + constructor(props: {}) { + super(props); + this.state = { + tableData: [ + { name: "Rylan", email: "Angelita_Weimann42@gmail.com" }, + { name: "Amelia", email: "Dexter.Trantow57@hotmail.com" }, + { name: "Estevan", email: "Aimee7@hotmail.com" }, + { name: "Florence", email: "Jarrod.Bernier13@yahoo.com" }, + { name: "Tressa", email: "Yadira1@hotmail.com" } + ] + }; + } + + render() { + return ( + + { + ["name", "email"].map(field => + {field}} + cell={ + + } + width={200} /> + ) + } +
+ ); + } +} + +// Listen for events +class MyTable5 extends React.Component { + render() { + return ( + { }} + onScrollEnd={(x: number, y: number) => { }} + onContentHeightChange={(newHeight: number) => { }} + onRowClick={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowDoubleClick={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowMouseDown={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowMouseEnter={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowMouseLeave={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onColumnResizeEndCallback={(newColumnWidth: number, columnKey: string) => { }}> + // add columns +
+ ); + } +} diff --git a/types/fixed-data-table-2/index.d.ts b/types/fixed-data-table-2/index.d.ts new file mode 100644 index 0000000000..a39397a228 --- /dev/null +++ b/types/fixed-data-table-2/index.d.ts @@ -0,0 +1,677 @@ +// Type definitions for fixed-data-table-2 0.8 +// Project: https://github.com/schrodinger/fixed-data-table-2 +// Definitions by: Ilya Petukhov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; + +export as namespace FixedDataTable; + +export interface RowProps { + /** the row index */ + rowIndex: number; + + /** supplied from the Table or rowHeightGetter */ + height: number; + + /** supplied from the Table */ + width: number; +} + +export interface ColumnReorderEndEvent { + /** the column before the new location of this one */ + columnBefore?: string; + + /** the column after the new location of this one */ + columnAfter?: string; + + /** the column key that was just reordered */ + reorderColumn: string; +} + +export type ElementOrFunc

= string | React.ReactElement | ((props: P) => (string | React.ReactElement)); + +export type TableRowEventHandler = (event: React.SyntheticEvent, rowIndex: number) => void; + +/** + * Data grid component with fixed or scrollable header and columns. + * + * The layout of the data table is as follows: + * + * ``` + * +---------------------------------------------------+ + * | Fixed Column Group | Scrollable Column Group | + * | Header | Header | + * | | | + * +---------------------------------------------------+ + * | | | + * | Fixed Header Columns | Scrollable Header Columns | + * | | | + * +-----------------------+---------------------------+ + * | | | + * | Fixed Body Columns | Scrollable Body Columns | + * | | | + * +-----------------------+---------------------------+ + * | | | + * | Fixed Footer Columns | Scrollable Footer Columns | + * | | | + * +-----------------------+---------------------------+ + * ``` + * + * - Fixed Column Group Header: These are the headers for a group + * of columns if included in the table that do not scroll + * vertically or horizontally. + * + * - Scrollable Column Group Header: The header for a group of columns + * that do not move while scrolling vertically, but move horizontally + * with the horizontal scrolling. + * + * - Fixed Header Columns: The header columns that do not move while scrolling + * vertically or horizontally. + * + * - Scrollable Header Columns: The header columns that do not move + * while scrolling vertically, but move horizontally with the horizontal + * scrolling. + * + * - Fixed Body Columns: The body columns that do not move while scrolling + * horizontally, but move vertically with the vertical scrolling. + * + * - Scrollable Body Columns: The body columns that move while scrolling + * vertically or horizontally. + */ +export interface TableProps extends React.ClassAttributes
{ + /** + * Pixel width of table. If all columns do not fit, + * a horizontal scrollbar will appear. + */ + width: number; + + /** + * Pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either `height` or `maxHeight` must be specified. + */ + height?: number; + + /** + * Class name to be passed into parent container + */ + className?: string; + + /** + * Maximum pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either `height` or `maxHeight` must be specified. + */ + maxHeight?: number; + + /** + * Pixel height of table's owner, this is used in a managed scrolling + * situation when you want to slide the table up from below the fold + * without having to constantly update the height on every scroll tick. + * Instead, vary this property on scroll. By using `ownerHeight`, we + * over-render the table while making sure the footer and horizontal + * scrollbar of the table are visible when the current space for the table + * in view is smaller than the final, over-flowing height of table. It + * allows us to avoid resizing and reflowing table when it is moving in the + * view. + * + * This is used if `ownerHeight < height` (or `maxHeight`). + */ + ownerHeight?: number; + + overflowX?: 'hidden' | 'auto'; + overflowY?: 'hidden' | 'auto'; + + /** + * Boolean flag indicating of touch scrolling should be enabled + * This feature is current in beta and may have bugs + */ + touchScrollEnabled?: boolean; + + /** Boolean flags to control if scrolling with keys is enabled */ + keyboardScrollEnabled?: boolean; + /** Boolean flags to control if scrolling with keys is enabled */ + keyboardPageEnabled?: boolean; + + /** Hide the scrollbar but still enable scroll functionality */ + showScrollbarX?: boolean; + /** Hide the scrollbar but still enable scroll functionality */ + showScrollbarY?: boolean; + + /** + * Callback when horizontally scrolling the grid. + * + * Return false to stop propagation. + */ + onHorizontalScroll?: (scrollPos: number) => boolean; + + /** + * Callback when vertically scrolling the grid. + * + * Return false to stop propagation. + */ + onVerticalScroll?: (scrollPos: number) => boolean; + + /** + * Number of rows in the table. + */ + rowsCount: number; + + /** + * Pixel height of rows unless `rowHeightGetter` is specified and returns + * different value. + */ + rowHeight: number; + + /** + * If specified, `rowHeightGetter(index)` is called for each row and the + * returned value overrides `rowHeight` for particular row. + */ + rowHeightGetter?: (index: number) => number; + + /** + * Pixel height of sub-row unless `subRowHeightGetter` is specified and returns + * different value. Defaults to 0 and no sub-row being displayed. + */ + subRowHeight?: number; + + /** + * If specified, `subRowHeightGetter(index)` is called for each row and the + * returned value overrides `subRowHeight` for particular row. + */ + subRowHeightGetter?: (index: number) => number; + + /** + * The row expanded for table row. + * This can either be a React element, or a function that generates + * a React Element. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * rowIndex; number // (the row index) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Table) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + rowExpanded?: ElementOrFunc; + + /** + * To get any additional CSS classes that should be added to a row, + * `rowClassNameGetter(index)` is called. + */ + rowClassNameGetter?: (index: number) => string; + + /** + * If specified, `rowKeyGetter(index)` is called for each row and the + * returned value overrides `key` for the particular row. + */ + rowKeyGetter?: (index: number) => string; + + /** + * Pixel height of the column group header. + */ + groupHeaderHeight?: number; + + /** + * Pixel height of header. + */ + headerHeight: number; + + /** + * Pixel height of fixedDataTableCellGroupLayout/cellGroupWrapper. + * Default is headerHeight and groupHeaderHeight. + * + * This can be used with CSS to make a header cell span both the group & normal header row. + * Setting this to a value larger than height will cause the content to + * overflow the height. This is useful when adding a 2nd table as the group + * header and vertically merging the 2 headers when a column is not part + * of a group. Here are the necessary CSS changes: + * + * Both headers: + * - cellGroupWrapper needs overflow-x: hidden and pointer-events: none + * - cellGroup needs pointer-events: auto to reenable them on child els + * Group header: + * - Layout/main needs overflow: visible and a higher z-index + * - CellLayout/main needs overflow-y: visible + * - cellGroup needs overflow: visible + */ + cellGroupWrapperHeight?: number; + + /** + * Pixel height of footer. + */ + footerHeight?: number; + + /** + * Value of horizontal scroll. + */ + scrollLeft?: number; + + /** + * Index of column to scroll to. + */ + scrollToColumn?: number; + + /** + * Value of vertical scroll. + */ + scrollTop?: number; + + /** + * Index of row to scroll to. + */ + scrollToRow?: number; + + /** + * Callback that is called when scrolling starts with current horizontal + * and vertical scroll values. + */ + onScrollStart?: (x: number, y: number) => void; + + /** + * Callback that is called when scrolling ends or stops with new horizontal + * and vertical scroll values. + */ + onScrollEnd?: (x: number, y: number) => void; + + /** + * If enabled scroll events will not be propagated outside of the table. + */ + stopScrollPropagation?: boolean; + + /** + * Callback that is called when `rowHeightGetter` returns a different height + * for a row than the `rowHeight` prop. This is necessary because initially + * table estimates heights of some parts of the content. + */ + onContentHeightChange?: (newHeight: number) => void; + + /** + * Callback that is called when a row is clicked. + */ + onRowClick?: TableRowEventHandler; + + /** + * Callback that is called when a row is double clicked. + */ + onRowDoubleClick?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-down event happens on a row. + */ + onRowMouseDown?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-up event happens on a row. + */ + onRowMouseUp?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-enter event happens on a row. + */ + onRowMouseEnter?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-leave event happens on a row. + */ + onRowMouseLeave?: TableRowEventHandler; + + /** + * Callback that is called when a touch-start event happens on a row. + */ + onRowTouchStart?: TableRowEventHandler; + + /** + * Callback that is called when a touch-end event happens on a row. + */ + onRowTouchEnd?: TableRowEventHandler; + + /** + * Callback that is called when a touch-move event happens on a row. + */ + onRowTouchMove?: TableRowEventHandler; + + /** + * Callback that is called when resizer has been released + * and column needs to be updated. + * + * Required if the isResizable property is true on any column. + * + * ``` + * function( + * newColumnWidth: number, + * columnKey: string, + * ) + * ``` + */ + onColumnResizeEndCallback?: (newColumnWidth: number, columnKey: string) => void; + + /** + * Callback that is called when reordering has been completed + * and columns need to be updated. + * + * ``` + * function( + * event { + * columnBefore: string|undefined, // the column before the new location of this one + * columnAfter: string|undefined, // the column after the new location of this one + * reorderColumn: string, // the column key that was just reordered + * } + * ) + * ``` + */ + onColumnReorderEndCallback?: (event: ColumnReorderEndEvent) => void; + + /** + * Whether a column is currently being resized. + */ + isColumnResizing?: boolean; + + /** + * Whether columns are currently being reordered. + */ + isColumnReordering?: boolean; + + /** + * The number of rows outside the viewport to prerender. Defaults to roughly + * half of the number of visible rows. + */ + bufferRowCount?: number; +} + +export class Table extends React.Component { +} + +export interface ColumnHeaderProps { + columnKey?: string; + + /** supplied from the Table or rowHeightGetter */ + height: number; + + /** supplied from the Column */ + width: number; +} + +export interface ColumnCellProps extends ColumnHeaderProps { + /** the row index of the cell */ + rowIndex: number; +} + +/** + * Component that defines the attributes of table column. + */ +export interface ColumnProps extends React.ClassAttributes { + /** + * The horizontal alignment of the table cell content. + */ + align?: 'left' | 'center' | 'right'; + + /** + * Controls if the column is fixed when scrolling in the X axis. + * + * defaultValue: false + */ + fixed?: boolean; + + /** + * Controls if the column is fixed to the right side of the table + * when scrolling in the X axis. + * + * defaultValue: false + */ + fixedRight?: boolean; + + /** + * The header cell for this column. + * This can either be a string a React element, or a function that generates + * a React Element. Passing in a string will render a default header cell + * with that string. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + header?: ElementOrFunc; + + /** + * This is the body cell that will be cloned for this column. + * This can either be a string a React element, or a function that generates + * a React Element. Passing in a string will render a default header cell + * with that string. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * rowIndex; number // (the row index of the cell) + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + cell?: ElementOrFunc; + + /** + * This is the footer cell for this column. + * This can either be a string a React element, or a function that generates + * a React Element. Passing in a string will render a default header cell + * with that string. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + footer?: ElementOrFunc; + + /** + * This is used to uniquely identify the column, and is not required unless + * you a resizing columns. This will be the key given in the + * `onColumnResizeEndCallback` on the Table. + */ + columnKey?: string | number; + + /** + * The pixel width of the column. + */ + width: number; + + /** + * If this is a resizable column this is its minimum pixel width. + */ + minWidth?: number; + + /** + * If this is a resizable column this is its maximum pixel width. + */ + maxWidth?: number; + + /** + * The grow factor relative to other columns. Same as the flex-grow API + * from http://www.w3.org/TR/css3-flexbox/. Basically, take any available + * extra width and distribute it proportionally according to all columns' + * flexGrow values. Defaults to zero (no-flexing). + */ + flexGrow?: number; + + /** + * Whether the column can be resized with the + * FixedDataTableColumnResizeHandle. Please note that if a column + * has a flex grow, once you resize the column this will be set to 0. + * + * This property only provides the UI for the column resizing. If this + * is set to true, you will need to set the onColumnResizeEndCallback table + * property and render your columns appropriately. + */ + isResizable?: boolean; + + /** + * Whether the column can be dragged to reorder. + */ + isReorderable?: boolean; + + /** + * Whether cells in this column can be removed from document when outside + * of viewport as a result of horizontal scrolling. + * Setting this property to true allows the table to not render cells in + * particular column that are outside of viewport for visible rows. This + * allows to create table with many columns and not have vertical scrolling + * performance drop. + * Setting the property to false will keep previous behaviour and keep + * cell rendered if the row it belongs to is visible. + * + * defaultValue: false + */ + allowCellsRecycling?: boolean; + + /** + * Flag to enable performance check when rendering. Stops the component from + * rendering if none of it's passed in props have changed + */ + pureRendering?: boolean; +} + +export class Column extends React.Component { +} + +export interface ColumnGroupHeaderProps { + /* supplied from the groupHeaderHeight */ + height: number; + + /* supplied from the Column */ + width: number; +} + +/** + * Component that defines the attributes of a table column group. + */ +export interface ColumnGroupProps extends React.ClassAttributes { + /** + * The horizontal alignment of the table cell content. + */ + align?: 'left' | 'center' | 'right'; + + /** + * Controls if the column group is fixed when scrolling in the X axis. + * + * defaultValue: false + */ + fixed?: boolean; + + /** + * This is the header cell for this column group. + * This can either be a string or a React element. Passing in a string + * will render a default footer cell with that string. By default, the React + * element passed in can expect to receive the following props: + * + * ``` + * props: { + * height: number // (supplied from the groupHeaderHeight) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * You can also pass in a function that returns a react elemnt, with the + * props object above passed in as the first parameter. + */ + header?: string | React.ReactElement | ((props: ColumnGroupHeaderProps) => (string | React.ReactElement)); +} + +export class ColumnGroup extends React.Component { +} + +/** + * Component that handles default cell layout and styling. + * + * All props unless specified below will be set onto the top level `div` + * rendered by the cell. + * + * Example usage via from a `Column`: + * ``` + * const MyColumn = ( + * ( + * + * Cell number: {rowIndex} + * + * )} + * width={100} + * /> + * ); + * ``` + */ +export interface CellProps extends React.HTMLAttributes { + /** + * Outer height of the cell. + */ + height?: number; + + /** + * Outer width of the cell. + */ + width?: number; + + /** + * Optional prop that if specified on the `Column` will be passed to the + * cell. It can be used to uniquely identify which column is the cell is in. + */ + columnKey?: string | number; + + /** + * Optional prop that represents the rows index in the table. + * For the 'cell' prop of a Column, this parameter will exist for any + * cell in a row with a positive index. + * + * Below that entry point the user is welcome to consume or + * pass the prop through at their discretion. + */ + rowIndex?: number; +} + +export class Cell extends React.Component { +} diff --git a/types/fixed-data-table-2/tsconfig.json b/types/fixed-data-table-2/tsconfig.json new file mode 100644 index 0000000000..c548d5c369 --- /dev/null +++ b/types/fixed-data-table-2/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts", + "fixed-data-table-2-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "jsx":"preserve", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/fixed-data-table-2/tslint.json b/types/fixed-data-table-2/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/fixed-data-table-2/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/flot/index.d.ts b/types/flot/index.d.ts index 84ab0daeb8..a75142b49e 100644 --- a/types/flot/index.d.ts +++ b/types/flot/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Flot // Project: http://www.flotcharts.org/ -// Definitions by: Matt Burland , Timo Mühlbach +// Definitions by: Matt Burland +// Timo Mühlbach +// Ariel Kuechler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -120,6 +122,10 @@ declare namespace jquery.flot { tickLength?: number; alignTicksWithAxis?: number; + + timezone?: string; // "browser" or timezone (only makes sense for mode: "time") + timeformat?: string; // null or format string + twelveHourClock?: boolean; } interface seriesTypeBase { diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 82bd401c39..575df86b4d 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -289,7 +289,7 @@ export interface WriteFileOptions { export interface WriteOptions extends WriteFileOptions { fs?: object; replacer?: any; - spaces?: number; + spaces?: number | string; } export interface ReadResult { diff --git a/types/fs-plus/fs-plus-tests.ts b/types/fs-plus/fs-plus-tests.ts new file mode 100644 index 0000000000..92ae917266 --- /dev/null +++ b/types/fs-plus/fs-plus-tests.ts @@ -0,0 +1,151 @@ +import * as path from "path"; +import * as fs from "fs-plus"; + +const homeDir = fs.getHomeDirectory(); + +console.log(fs.absolute("~") === fs.realpathSync(homeDir)); +console.log( + fs.absolute(path.join("~", "does", "not", "exist")) === + path.join(homeDir, "does", "not", "exist") +); + +console.log(fs.normalize("~/foo") === path.join(homeDir, "foo")); + +console.log(fs.tildify(homeDir) === "~"); + +console.log( + fs.getAppDataDirectory() === + path.join(fs.getHomeDirectory(), "Library", "Application Support") +); + +console.log(fs.isAbsolute("/a/b/c")); + +console.log(fs.existsSync("/a/b/c")); + +console.log(fs.isDirectorySync("/a/b/c")); + +fs.isDirectory("a/b/c", result => { + console.log(result); +}); + +console.log(fs.isFileSync("/a/b/c")); + +console.log(fs.isSymbolicLinkSync("/a/b/c")); + +fs.isSymbolicLink("a/b/c", result => { + console.log(result); +}); + +console.log(fs.isExecutableSync("/a/b/c")); + +console.log(fs.getSizeSync("/a/b/c") === -1); + +console.log(fs.listSync("/a/b").indexOf("c") === 0); +console.log(fs.listSync("/a/b", [".ts", ".tsx"]).indexOf("c.tsx") === 0); + +fs.list("/a/b", (err, result) => { + if (err) { + console.error(err); + return; + } + console.log(result.indexOf("c") === 0); +}); +fs.list("/a/b", [".ts", ".tsx"], (err, result) => { + if (err) { + console.error(err); + return; + } + console.log(result.indexOf("c.tsx") === 0); +}); + +console.log(fs.listTreeSync("/a/b").indexOf("c") === 0); + +fs.moveSync("/a/b", "a/c"); + +fs.move("/a/b", "a/c", err => { + console.log(err); +}); + +fs.removeSync("/a/b"); + +fs.remove("/a/b", err => { + console.log(err); +}); + +fs.writeFileSync("a/b/c", "data"); +fs.writeFileSync("a/b/c", "data", "utf8"); +fs.writeFileSync("a/b/c", "data", { encoding: "utf8" }); + +fs.writeFile("a/b/c", "data", err => { + console.log(err); +}); +fs.writeFile("a/b/c", "data", "utf8", err => { + console.log(err); +}); +fs.writeFile("a/b/c", "data", { encoding: "utf8" }, err => { + console.log(err); +}); + +fs.copySync("/a/b", "a/c"); + +fs.copy("/a/b", "a/c", err => { + console.log(err); +}); + +fs.copyFileSync("/a/b", "a/c"); +fs.copyFileSync("/a/b", "a/c", 32 * 1024); + +fs.makeTreeSync("/a/b"); + +fs.makeTree("/a/b", err => { + console.log(err); +}); + +fs.traverseTreeSync( + "a/b/c", + file => { + console.log("file", file); + }, + dir => { + console.log("directory", dir); + return true; + } +); + +fs.traverseTree( + "a/b/c", + file => { + console.log("file", file); + }, + dir => { + console.log("directory", dir); + }, + err => { + console.error(err); + } +); + +console.log(fs.md5ForPath("a/b/c")); + +console.log(fs.resolve("a/b/c", "sample.js")); +console.log(fs.resolve("a/b/c", "sample", [".js"])); + +console.log(fs.resolveOnLoadPath("sample.js")); +console.log(fs.resolveOnLoadPath("sample", [".js"])); + +console.log(fs.resolveExtension("a/b/c", [".js"])); + +console.log(fs.isCompressedExtension(".tar.gz")); + +console.log(fs.isImageExtension(".jpg")); + +console.log(fs.isPdfExtension(".pdf")); + +console.log(fs.isBinaryExtension(".exe")); + +console.log(fs.isReadmePath("a/b/README.md")); + +console.log(fs.isMarkdownExtension(".md")); + +console.log(fs.isCaseInsensitive()); +console.log(fs.isCaseSensitive()); diff --git a/types/fs-plus/index.d.ts b/types/fs-plus/index.d.ts new file mode 100644 index 0000000000..0151de2c73 --- /dev/null +++ b/types/fs-plus/index.d.ts @@ -0,0 +1,305 @@ +// Type definitions for fs-plus 3.0 +// Project: https://github.com/atom/fs-plus +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Stats } from "fs"; + +export * from "fs"; + +/** + * Returns the absolute path to the home directory. + */ +export function getHomeDirectory(): string; + +/** + * Make the given path absolute by resolving it against the current working directory. + */ +export function absolute(relativePath: string): string; + +/** + * Normalize the given path treating a leading `~` segment as referring to the home directory. This method does not query the filesystem. + */ +export function normalize(pathToNormalize: string): string; + +/** + * Convert an absolute path to tilde path for Linux and macOS. + */ +export function tildify(pathToTildify: string): string; + +/** + * Get path to store application specific data. + * + * * Mac: `~/Library/Application Support/` + * * Win: `%AppData%` + * * Linux: `/var/lib` + */ +export function getAppDataDirectory(): string; + +/** + * Returns true if the given path is absolute. + */ +export function isAbsolute(pathToCheck: string): boolean; + +/** + * Returns true if a file or folder at the specified path exists. + */ +export function existsSync(pathToCheck: string): boolean; + +/** + * Returns true if the given path exists and is a directory. + */ +export function isDirectorySync(directoryPath: string): boolean; + +/** + * Asynchronously checks that the given path exists and is a directory. + */ +export function isDirectory( + directoryPath: string, + callback: (result: boolean) => void +): void; + +/** + * Returns true if the specified path exists and is a file. + */ +export function isFileSync(filePath: string): boolean; + +/** + * Returns true if the specified path is a symbolic link. + */ +export function isSymbolicLinkSync(symlinkPath: string): boolean; + +/** + * Calls back with true if the specified path is a symbolic link. + */ +export function isSymbolicLink( + symlinkPath: string, + callback: (result: boolean) => void +): void; + +/** + * Returns true if the specified path is executable. + */ +export function isExecutableSync(pathToCheck: string): boolean; + +/** + * Returns the size of the specified path. + */ +export function getSizeSync(pathToCheck: string): number; + +/** + * Returns an Array with the paths of the files and directories contained within the directory path. It is not recursive. + */ +export function listSync(rootPath: string, extensions?: string[]): string[]; + +/** + * Asynchronously lists the files and directories in the given path. The listing is not recursive. + */ +export function list( + rootPath: string, + callback: (err: Error, result: string[]) => void +): void; + +/** + * Asynchronously lists the files and directories in the given path. The listing is not recursive. + */ +export function list( + rootPath: string, + extensions: string[], + callback: (err: Error, result: string[]) => void +): void; + +/** + * Get all paths under the given path. + */ +export function listTreeSync(rootPath: string): string[]; + +/** + * Moves the source file or directory to the target. + */ +export function moveSync(source: string, target: string): void; + +/** + * Asynchronously moves the source file or directory to the target. + */ +export function move( + source: string, + target: string, + callback: (err: Error) => void +): void; + +/** + * Removes the file or directory at the given path. + */ +export function removeSync(pathToRemove: string): void; + +/** + * Asynchronously removes the file or directory at the given path. + */ +export function remove( + pathToRemove: string, + callback: (err: Error) => void +): void; + +/** + * Open, write, flush, and close a file, writing the given content synchronously. + */ +export function writeFileSync( + filePath: string, + content: string, + options?: + | { encoding?: string | null; mode?: number | string; flag?: string } + | string + | null +): void; + +/** + * Open, write, flush, and close a file, writing the given content asynchronously. + */ +export function writeFile( + filePath: string, + content: any, + callback: (err: any) => void +): void; + +/** + * Open, write, flush, and close a file, writing the given content asynchronously. + */ +export function writeFile( + filePath: string, + content: any, + options: + | { encoding?: string | null; mode?: number | string; flag?: string } + | string + | undefined + | null, + callback: (err: any) => void +): void; + +/** + * Copies the given path. + */ +export function copySync(source: string, target: string): void; + +/** + * Asynchronously copies the given path. + */ +export function copy( + source: string, + target: string, + callback: (err: any) => void +): void; + +/** + * Copies the given path synchronously, buffering reads and writes to keep memory footprint to a minimum. If the destination directory doesn't exist, it creates it. + */ +export function copyFileSync( + source: string, + target: string, + bufferSize?: number +): void; + +/** + * Create a directory at the specified path including any missing parent directories. + */ +export function makeTreeSync(directoryPath: string): void; + +/** + * Asynchronously create a directory at the specified path including any missing parent directories. + */ +export function makeTree( + directoryPath: string, + callback: (err: any) => void +): void; + +/** + * Recursively walk the given path and execute the given functions. + */ +export function traverseTreeSync( + rootPath: string, + onFile: (file: string) => void, + onDirectory: (dir: string) => boolean | void +): void; + +/** + * Asynchronously walk the given path and execute the given functions. + */ +export function traverseTree( + rootPath: string, + onFile: (file: string) => void, + onDirectory: (dir: string) => boolean | void, + onDone: (err: any) => void +): void; + +/** + * Hashes the contents of the given file. + */ +export function md5ForPath(pathToDigest: string): string; + +/** + * Finds a relative path among the given array of paths. + */ +export function resolve( + loadPath: string, + pathToResolve: string, + extensions?: string[] +): string | undefined; + +/** + * Finds a relative path using Node's module paths as load paths. + */ +export function resolveOnLoadPath( + pathToResolve: string, + extensions?: string[] +): string | undefined; + +/** + * Finds the first file in the given path which matches the extension in the order given. + */ +export function resolveExtension( + pathToResolve: string, + extensions: string[] +): string | undefined; + +/** + * Returns true for extensions associated with compressed files. + */ +export function isCompressedExtension(ext: string): boolean; + +/** + * Returns true for extensions associated with image files. + */ +export function isImageExtension(ext: string): boolean; + +/** + * Returns true for extensions associated with PDF files. + */ +export function isPdfExtension(ext: string): boolean; + +/** + * Returns true for extensions associated with binary files. + */ +export function isBinaryExtension(ext: string): boolean; + +/** + * Returns true for files named similarily to `README`. + */ +export function isReadmePath(readmePath: string): boolean; + +/** + * Returns true for extensions associated with Markdown files. + */ +export function isMarkdownExtension(ext: string): boolean; + +/** + * Is the filesystem case insensitive? + */ +export function isCaseInsensitive(): boolean; + +/** + * Is the filesystem case sensitive? + */ +export function isCaseSensitive(): boolean; diff --git a/types/fs-plus/tsconfig.json b/types/fs-plus/tsconfig.json new file mode 100644 index 0000000000..1ab0098d52 --- /dev/null +++ b/types/fs-plus/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-plus-tests.ts" + ] +} diff --git a/types/fs-plus/tslint.json b/types/fs-plus/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fs-plus/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fullcalendar/index.d.ts b/types/fullcalendar/index.d.ts index 196de10898..3d5ff28f12 100644 --- a/types/fullcalendar/index.d.ts +++ b/types/fullcalendar/index.d.ts @@ -995,7 +995,7 @@ declare global { /** * Immediately switches to a different view. */ - fullCalendar(method: 'changeView', viewName: string): void; + fullCalendar(method: 'changeView', viewName: string, dateOrRange?: moment.Moment | Date | string | TimeRange): void; /** * Moves the calendar one step back (either by a month, week, or day). diff --git a/types/fuzzyset.js/fuzzyset.js-tests.ts b/types/fuzzyset.js/fuzzyset.js-tests.ts new file mode 100644 index 0000000000..97a0d45008 --- /dev/null +++ b/types/fuzzyset.js/fuzzyset.js-tests.ts @@ -0,0 +1,10 @@ +import FuzzySet = require('fuzzyset.js'); + +const fuzzyset: FuzzySet = FuzzySet(['coucou', 'foo', 'bar', 'toto']); +const results = fuzzyset.get('foo'); + +fuzzyset.length(); + +fuzzyset.isEmpty(); + +fuzzyset.values(); diff --git a/types/fuzzyset.js/index.d.ts b/types/fuzzyset.js/index.d.ts new file mode 100644 index 0000000000..04914683bc --- /dev/null +++ b/types/fuzzyset.js/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for fuzzyset.js 0.0 +// Project: https://github.com/Glench/fuzzyset.js +// Definitions by: Louis Grignon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface FuzzySet { + get(candidate: string, defaultValue?: T, minScore?: number): Array<[number, string]> | T | null; + add(value: string): boolean; + length(): number; + isEmpty(): boolean; + values(): string[]; +} + +declare function FuzzySet( + source: string[], + useLevenshtein?: boolean, + gramSizeLower?: number, + gramSizeUpper?: number, +): FuzzySet; + +export = FuzzySet; +export as namespace FuzzySet; diff --git a/types/fuzzyset.js/tsconfig.json b/types/fuzzyset.js/tsconfig.json new file mode 100644 index 0000000000..a1eeb06b97 --- /dev/null +++ b/types/fuzzyset.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fuzzyset.js-tests.ts" + ] +} diff --git a/types/fuzzyset.js/tslint.json b/types/fuzzyset.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fuzzyset.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gapi.youtube/index.d.ts b/types/gapi.youtube/index.d.ts index b09779cdb3..bf2aebaf3a 100644 --- a/types/gapi.youtube/index.d.ts +++ b/types/gapi.youtube/index.d.ts @@ -778,7 +778,7 @@ interface GoogleApiYouTubeActivityResource { /** * A map of thumbnail images associated with the resource that is primarily associated with the activity. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * Channel title for the channel responsible for this activity */ @@ -1082,7 +1082,7 @@ interface GoogleApiYouTubeChannelResource { /** * A map of thumbnail images associated with the channel. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; } /** * The contentDetails object encapsulates information about the channels content. @@ -1526,7 +1526,7 @@ interface GoogleApiYouTubePlaylistItemResource { /** * A map of thumbnail images associated with the playlist item. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * The channel title of the channel that the playlist item belongs to. */ @@ -1713,7 +1713,7 @@ interface GoogleApiYouTubeSearchResource { /** * A map of thumbnail images associated with the search result. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * The title of the channel that published the resource that the search result identifies. */ @@ -1774,7 +1774,7 @@ interface GoogleApiYouTubeSubscriptionResource { /** * A map of thumbnail images associated with the subscription. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; } /** * @@ -1796,7 +1796,7 @@ interface GoogleApiYouTubeSubscriptionResource { title: string; description: string; channelId: string; - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; } } @@ -1902,7 +1902,7 @@ interface GoogleApiYouTubeVideoResource { /** * A map of thumbnail images associated with the video. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * Channel title for the channel that the video belongs to. */ diff --git a/types/gifffer/gifffer-tests.ts b/types/gifffer/gifffer-tests.ts new file mode 100644 index 0000000000..b069e0020c --- /dev/null +++ b/types/gifffer/gifffer-tests.ts @@ -0,0 +1,28 @@ +import Gifffer from 'gifffer'; + +let gifs: HTMLButtonElement[]; + +gifs = Gifffer({ + playButtonStyles: { + width: '60px', + height: '60px', + 'border-radius': '30px', + background: 'rgba(0, 0, 0, 0.3)', + position: 'absolute', + top: '50%', + left: '50%', + margin: '-30px 0 0 -30px' + }, + playButtonIconStyles: { + width: '0', + height: '0', + 'border-top': '14px solid transparent', + 'border-bottom': '14px solid transparent', + 'border-left': '14px solid rgba(0, 0, 0, 0.5)', + position: 'absolute', + left: '26px', + top: '16px' + } +}); + +gifs[0].click(); diff --git a/types/gifffer/index.d.ts b/types/gifffer/index.d.ts new file mode 100644 index 0000000000..ac0f7663cc --- /dev/null +++ b/types/gifffer/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gifffer 1.5 +// Project: https://github.com/krasimir/gifffer#readme +// Definitions by: William Lohan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @see {@link https://github.com/krasimir/gifffer#styling|Styling} + */ +export interface GiffferOptions { + playButtonStyles: { [style: string]: string; }; + playButtonIconStyles: { [style: string]: string; }; +} + +/** + * @see {@link https://github.com/krasimir/gifffer#usage|Usage} + */ +export default function Gifffer(options?: GiffferOptions): HTMLButtonElement[]; diff --git a/types/gifffer/tsconfig.json b/types/gifffer/tsconfig.json new file mode 100644 index 0000000000..273e998048 --- /dev/null +++ b/types/gifffer/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gifffer-tests.ts" + ] +} diff --git a/types/gifffer/tslint.json b/types/gifffer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gifffer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts index 544f2e095f..a614ea4982 100644 --- a/types/google-cloud__storage/index.d.ts +++ b/types/google-cloud__storage/index.d.ts @@ -153,6 +153,7 @@ declare namespace Storage { interface FileMetadata { contentType?: string; metadata?: CustomFileMetadata; + cacheControl?: string; } /** diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 5e977257b8..1d46ee467f 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1158,17 +1158,17 @@ declare namespace google.maps { export interface GeocoderRequest { address?: string; bounds?: LatLngBounds|LatLngBoundsLiteral; - componentRestrictions?: GeocoderComponentRestrictions; + components?: GeocoderComponents; location?: LatLng|LatLngLiteral; placeId?: string; region?: string; } - export interface GeocoderComponentRestrictions { - administrativeArea?: string; + export interface GeocoderComponents { + administrative_area?: string; country?: string | string[]; locality?: string; - postalCode?: string; + postal_code?: string; route?: string; } diff --git a/types/gridstack/index.d.ts b/types/gridstack/index.d.ts index 20f01186c6..ec7899217c 100644 --- a/types/gridstack/index.d.ts +++ b/types/gridstack/index.d.ts @@ -321,7 +321,7 @@ interface IGridstackOptions { /** * if true widgets could be removed by dragging outside of the grid. It could also be a jQuery selector string, */ - removable?: boolean; + removable?: boolean | string; /** * time in milliseconds before widget is being removed while dragging outside of the grid. (default: 2000) */ diff --git a/types/hapi-auth-basic/hapi-auth-basic-tests.ts b/types/hapi-auth-basic/hapi-auth-basic-tests.ts index 7f78fe9f65..1a7192af6f 100644 --- a/types/hapi-auth-basic/hapi-auth-basic-tests.ts +++ b/types/hapi-auth-basic/hapi-auth-basic-tests.ts @@ -22,21 +22,22 @@ const users: {[index: string]: User} = { } }; -const validate: Basic.ValidateFunc = function (request, username, password, callback) { +const validate: Basic.Validate = async (request, username, password, h) => { const user = users[username]; if (!user) { - return callback(null, false); + return { isValid: false, credentials: null }; } - Bcrypt.compare(password, user.password, (err, isValid) => { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name }); - }); + return { isValid, credentials: { id: user.id, name: user.name } }; }; -server.register(Basic, (err) => { +server.register(Basic).then(() => { + + server.auth.strategy('simple', 'basic', { validate }); + server.auth.default('simple'); - server.auth.strategy('simple', 'basic', { validateFunc: validate }); server.route({ method: 'GET', path: '/', config: { auth: 'simple' } }); }); diff --git a/types/hapi-auth-basic/index.d.ts b/types/hapi-auth-basic/index.d.ts index 54d463c2b3..ddf05c348a 100644 --- a/types/hapi-auth-basic/index.d.ts +++ b/types/hapi-auth-basic/index.d.ts @@ -1,18 +1,24 @@ -// Type definitions for hapi 4.2 +// Type definitions for hapi-bauth-basic 5.0.0 // Project: https://github.com/hapijs/hapi-auth-basic // Definitions by: AJP +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Hapi from 'hapi'; declare namespace Basic { - interface ValidateFuncCallback { - (err: Error | null, isValid: boolean, userCredentials?: any): void; + interface ValidateCustomResponse { + response: any, } - interface ValidateFunc { - (request: Hapi.Request, username: string, password: string, callback: ValidateFuncCallback): void; + interface ValidateResponse { + isValid: boolean, + credentials?: any, + } + + interface Validate { + (request: Hapi.Request, username: string, password: string, h: object): Promise; } } diff --git a/types/heatmap.js/heatmap.js-tests.ts b/types/heatmap.js/heatmap.js-tests.ts index c2f2d34c16..af0c021b3f 100644 --- a/types/heatmap.js/heatmap.js-tests.ts +++ b/types/heatmap.js/heatmap.js-tests.ts @@ -1,42 +1,271 @@ +declare const container: HTMLElement; +// -- h337.HeatmapConfiguration -- -var baseLayer = L.tileLayer( - 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade', - maxZoom: 18 - }); +{ + const config: h337.HeatmapConfiguration = { container }; + config; // $ExpectType HeatmapConfiguration<"value", "x", "y"> +} -var testData: HeatmapData = { - max: 8, - data: [ - { - lat: 24.6408, - lng:46.7728, - count: 3 - }, { - lat: 50.75, - lng: -1.55, - count: 1 +{ + const config: h337.HeatmapConfiguration = { + container, + xField: 'x', + yField: 'y', + valueField: 'value', + }; +} + +{ + // $ExpectError + const config: h337.HeatmapConfiguration = { + container, + valueField: 'foo', + }; +} + +{ + const config: h337.HeatmapConfiguration<'foo'> = { + container, + valueField: 'foo', + }; + config; // $ExpectType HeatmapConfiguration<"foo", "x", "y"> +} + +// -- h337.create -- + +{ + // $ExpectType Heatmap<"value", "x", "y"> + h337.create({ container }); + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + h337.create<"count", "xPos", "yPos">({ + container, + valueField: "count", + xField: "xPos", + yField: "yPos", + }); + + const config: h337.HeatmapConfiguration<"count", "xPos", "yPos"> = { + container, + valueField: "count", + xField: "xPos", + yField: "yPos", + }; + // $ExpectType Heatmap<"count", "xPos", "yPos"> + h337.create(config); +} + +// -- Heatmap#addData -- + +{ + const heatmap = h337.create({ container }); + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.addData({ x: 1, y: 1, value: 5 }); + + heatmap.addData([ + { x: 1, y: 1, value: 1 }, + { x: 2, y: 2, value: 2 }, + ]); + + heatmap.addData({ x: null, y: 1, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, y: null, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, y: 1, value: null }); // $ExpectError + heatmap.addData({ y: 1, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, y: 1, }); // $ExpectError +} + +{ + const heatmap = h337.create<"count", "xPos", "yPos">({ + container, + xField: "xPos", + yField: "yPos", + valueField: "count", + }); + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + heatmap.addData({ xPos: 1, yPos: 1, count: 5 }); + + heatmap.addData([ + { xPos: 1, yPos: 1, count: 1 }, + { xPos: 2, yPos: 2, count: 2 }, + ]); + + heatmap.addData({ xPos: null, yPos: 1, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, yPos: null, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, yPos: 1, count: null }); // $ExpectError + heatmap.addData({ yPos: 1, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, yPos: 1, }); // $ExpectError +} + +// -- Heatmap#setData -- + +{ + const validData: ReadonlyArray = + [{ x: 1, y: 2, value: 1 }]; + + const heatmap = h337.create({ container }); + heatmap.setData({ max: 5, data: validData }); // $ExpectError + heatmap.setData({ min: 5, data: validData }); // $ExpectError + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.setData({ + min: 0, + max: 1, + data: validData + }); + + heatmap.setData({ // $ExpectError + min: 0, + max: 1, + data: [{ xPos: 1, yPos: 2, value: 5 }] + }); +} + +{ + const validData: ReadonlyArray> = + [{ xPos: 1, yPos: 2, count: 1 }]; + + const heatmap = h337.create<"count", "xPos", "yPos">({ container }); + heatmap.setData({ max: 5, data: validData }); // $ExpectError + heatmap.setData({ min: 5, data: validData }); // $ExpectError + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + heatmap.setData({ + min: 0, + max: 1, + data: validData + }); + + heatmap.setData({ // $ExpectError + min: 0, + max: 1, + data: [{ x: 1, y: 2, value: 5 }] + }); +} + +// -- Heatmap#setDataMax / Heatmap#setDataMin -- + +{ + const heatmap = h337.create({ container }); + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.setDataMax(500); + heatmap.setDataMax(null); // $ExpectError + heatmap.setDataMax(); // $ExpectError + + heatmap.setDataMin(500); + heatmap.setDataMin(null); // $ExpectError + heatmap.setDataMin(); // $ExpectError +} + +// -- Heatmap#configure -- + +{ + const heatmap = h337.create({ container }); + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.configure({ container }); + + const nextHeatmap = heatmap.configure<"count", "xPos", "yPos">({ + container, + valueField: "count", + xField: "xPos", + yField: "yPos" + }); + + nextHeatmap; // $ExpectType Heatmap<"count", "xPos", "yPos"> + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + nextHeatmap.configure({ container }); +} + +// -- Heatmap#getValueAt -- + +{ + // $ExpectType number + h337.create({ container }).getValueAt({ x: 0, y: 1 }); + + // $ExpectType number + h337.create<"foo", "bar", "baz">({ container }).getValueAt({ x: 0, y: 1 }); +} + +// -- Heatmap#getData -- + +{ + // $ExpectType HeatmapData + h337.create({ container }).getData(); + + // $ExpectType HeatmapData + h337.create<"foo", "bar", "baz">({ container }).getData(); +} + +// -- Heatmap#getDataURL -- + +{ + // $ExpectType string + h337.create({ container }).getDataURL(); +} + +// -- Heatmap#repaint -- +{ + // $ExpectType Heatmap<"value", "x", "y"> + h337.create({ container }).repaint(); + + // $ExpectType Heatmap<"foo", "bar", "baz"> + h337.create<"foo", "bar", "baz">({ container }).repaint(); +} + +// -- Leaflet plugin -- + +{ + const baseLayer = L.tileLayer( + 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { + // tslint:disable-next-line max-line-length + attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade', + maxZoom: 18 } - ] -}; + ); -var config : HeatmapConfiguration = { - radius: 2, - maxOpacity: .8, - scaleRadius: true, - useLocalExtrema: true, - latField: 'lat', - lngField: 'lng', - valueField: 'count' -}; + const testData: h337.HeatmapData> = { + min: 1, + max: 3, + data: [ + { + lat: 24.6408, + lng: 46.7728, + count: 3 + }, { + lat: 50.75, + lng: -1.55, + count: 1 + } + ] + }; -var heatmapLayer = new HeatmapOverlay(config); + const config: h337.HeatmapOverlayConfiguration<'count'> = { + radius: 2, + maxOpacity: .8, + scaleRadius: true, + useLocalExtrema: true, + latField: 'lat', + lngField: 'lng', + valueField: 'count' + }; + config; // $ExpectType HeatmapOverlayConfiguration<"count", "lat", "lng"> -var map = new L.Map('map-canvas', { - center: new L.LatLng(25.6586, -80.3568), - zoom: 4, - layers: [baseLayer, heatmapLayer] -}); + const heatmapLayer = new HeatmapOverlay(config); + heatmapLayer; // $ExpectType HeatmapOverlay<"count", "lat", "lng"> -heatmapLayer.setData(testData); + const map = new L.Map('map-canvas', { + center: new L.LatLng(25.6586, -80.3568), + zoom: 4, + layers: [baseLayer, heatmapLayer] + }); + + // $ExpectType void + heatmapLayer.setData(testData); +} diff --git a/types/heatmap.js/index.d.ts b/types/heatmap.js/index.d.ts index e6c0a4aec1..265f17f5fb 100644 --- a/types/heatmap.js/index.d.ts +++ b/types/heatmap.js/index.d.ts @@ -1,143 +1,390 @@ -// Type definitions for heatmap.js v2.0 +// Type definitions for heatmap.js 2.0 // Project: https://github.com/pa7/heatmap.js/ // Definitions by: Yang Guan +// Rhys van der Waerden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 + +export as namespace h337; + +/** + * Create a heatmap instance. A Heatmap can be customized with the configObject. + * + * @example + * + * // create configuration object + * var config = { + * container: document.getElementById('heatmapContainer'), + * radius: 10, + * maxOpacity: .5, + * minOpacity: 0, + * blur: .75 + * }; + * // create heatmap with configuration + * var heatmapInstance = h337.create(config); + * + * @example + * + * // create configuration object + * var config = { + * container: document.getElementById('heatmapContainer'), + * radius: 10, + * maxOpacity: .5, + * minOpacity: 0, + * blur: .75, + * gradient: { + * // enter n keys between 0 and 1 here + * // for gradient color customization + * '.5': 'blue', + * '.8': 'red', + * '.95': 'white' + * } + * }; + * var heatmapInstance = h337.create(config); + */ +export function create< + V extends string = 'value', + X extends string = 'x', + Y extends string = 'y' +>( + configObject: HeatmapConfiguration +): Heatmap; + +export function register(pluginKey: string, plugin: any): void; + +/** + * Heatmap instances are returned by h337.create. A heatmap instance has its own + * internal datastore and renderer where you can manipulate data. As a result + * the heatmap gets updated (either partially or completely, depending on + * whether it's necessary). + */ +export class Heatmap { + /** + * Use this functionality only for adding datapoints on the fly, not for data + * initialization! heatmapInstance.addData adds a single or multiple + * datapoints to the heatmap's datastore. + * + * @example + * + * var dataPoint = { + * x: 5, // x coordinate of the datapoint, a number + * y: 5, // y coordinate of the datapoint, a number + * value: 100 // the value at datapoint(x, y) + * }; + * heatmapInstance.addData(dataPoint); + * + * @example + * + * // for data initialization use setData!! + * var dataPoints = [dataPoint, dataPoint, dataPoint, dataPoint]; + * heatmapInstance.addData(dataPoints); + */ + addData(dataPoint: DataPoint | ReadonlyArray>): this; + + /** + * Initialize a heatmap instance with the given dataset. Removes all + * previously existing points from the heatmap instance and re-initializes + * the datastore. + * + * @example + * + * var data = { + * max: 100, + * min: 0, + * data: [ + * dataPoint, dataPoint, dataPoint, dataPoint + * ] + * }; + * heatmapInstance.setData(data); + */ + setData(data: HeatmapData>): this; + + /** + * Changes the upper bound of your dataset and triggers a complete + * rerendering. + * + * @example + * + * heatmapInstance.setDataMax(200); + * // setting the maximum value triggers a complete rerendering of the heatmap + * heatmapInstance.setDataMax(100); + */ + setDataMax(number: number): this; + + /** + * Changes the lower bound of your dataset and triggers a complete + * rerendering. + * + * @example + * + * heatmapInstance.setDataMin(10); + * // setting the minimum value triggers a complete rerendering of the heatmap + * heatmapInstance.setDataMin(0); + */ + setDataMin(number: number): this; + + /** + * Reconfigures a heatmap instance after it has been initialized. Triggers a + * complete rerendering. + * + * NOTE: This returns a reference to itself, but also offers an opportunity + * to change the `xField`, `yField` and `valueField` options, which can + * change the type of the `Heatmap` instance. + * + * @example + * + * var nuConfig = { + * radius: 10, + * maxOpacity: .5, + * minOpacity: 0, + * blur: .75 + * }; + * heatmapInstance.configure(nuConfig); + */ + configure< + Vn extends string = V, + Xn extends string = X, + Yn extends string = Y + >(configObject: HeatmapConfiguration): Heatmap; + + /** + * Returns value at datapoint position. + * + * The returned value is an interpolated value based on the gradient blending + * if point is not in store. + * + * @example + * + * heatmapInstance.addData({ x: 10, y: 10, value: 100}); + * // get the value at x=10, y=10 + * heatmapInstance.getValueAt({ x: 10, y: 10 }); // returns 100 + */ + getValueAt(point: { x: number, y: number }): number; + + /** + * Returns a persistable and reimportable (with setData) JSON object. + * + * @example + * + * var currentData = heatmapInstance.getData(); + * // now let's create a new instance and set the data + * var heatmap2 = h337.create(config); + * heatmap2.setData(currentData); // now both heatmap instances have the same content + */ + getData(): HeatmapData; + + /** + * Returns dataURL string. + * + * The returned value is the base64 encoded dataURL of the heatmap instance. + * + * @example + * + * heatmapInstance.getDataURL(); // data:image/png;base64... + * // ready for saving locally or on the server + */ + getDataURL(): string; + + /** + * Repaints the whole heatmap canvas. + */ + repaint(): this; +} + +export interface BaseHeatmapConfiguration { + /** + * A background color string in form of hexcode, color name, or rgb(a) + */ + backgroundColor?: string; + + /** + * The blur factor that will be applied to all datapoints. The higher the + * blur factor is, the smoother the gradients will be + * Default value: 0.85 + */ + blur?: number; + + /** + * An object that represents the gradient. + * Syntax: {[key: number in range [0,1]]: color} + */ + gradient?: { [key: string]: string }; + + /** + * The maximal opacity the highest value in the heatmap will have. (will be + * overridden if opacity set) + * Default value: 0.6 + */ + maxOpacity?: number; + + /** + * The minimum opacity the lowest value in the heatmap will have (will be + * overridden if opacity set) + */ + minOpacity?: number; + + /** + * A global opacity for the whole heatmap. This overrides maxOpacity and + * minOpacity if set + * Default value: 0.6 + */ + opacity?: number; + + /** + * The radius each datapoint will have (if not specified on the datapoint + * itself) + */ + radius?: number; + + /** + * Scales the radius based on map zoom. + */ + scaleRadius?: boolean; + + /** + * The property name of the value/weight in a datapoint + * Default value: 'value' + */ + valueField?: V; + + /** + * Pass a callback to receive extrema change updates. Useful for DOM + * legends. + */ + onExtremaChange?: () => void; + + /** + * Indicate whether the heatmap should use a global extrema or a local + * extrema (the maximum and minimum of the currently displayed viewport) + */ + useLocalExtrema?: boolean; +} + +/** + * Configuration object of a heatmap + */ +export interface HeatmapConfiguration< + V extends string = 'value', + X extends string = 'x', + Y extends string = 'y', +> extends BaseHeatmapConfiguration { + /** + * A DOM node where the heatmap canvas should be appended (heatmap will adapt to + * the node's size) + */ + container: HTMLElement; + + /** + * The property name of your x coordinate in a datapoint + * Default value: 'x' + */ + xField?: X; + + /** + * The property name of your y coordinate in a datapoint + * Default value: 'y' + */ + yField?: Y; +} + +export interface HeatmapOverlayConfiguration< + V extends string = 'value', + TLat extends string = 'lat', + TLong extends string = 'lng', +> extends BaseHeatmapConfiguration { + /** + * The property name of your latitude coordinate in a datapoint + * Default value: 'x' + */ + latField?: TLat; + + /** + * The property name of your longitude coordinate in a datapoint + * Default value: 'y' + */ + lngField?: TLong; +} + +/** + * A single data point on a heatmap. The interface of the data point can be + * overridden by providing alternative values for `xKey` and `yKey` in the + * config object. + */ +export type DataPoint< + V extends string = 'value', + X extends string = 'x', + Y extends string = 'y', +> = Record; + +/** + * Type of data returned by `Heatmap#hello`, which ignores custom `xField`, + * `yField` and `valueField`. + */ +export interface DataCircle { + x: number; + y: number; + value: number; + radius: number; +} + +/** + * An object representing the set of data points on a heatmap + */ +export interface HeatmapData { + /** + * An array of data points + */ + data: ReadonlyArray; + + /** + * Max value of the valueField + */ + max: number; + + /** + * Min value of the valueField + */ + min: number; +} + +// -- Leaflet plugin -- import * as Leaflet from "leaflet"; declare global { - /* - * Configuration object of a heatmap - */ - interface HeatmapConfiguration { - - /* - * A background color string in form of hexcode, color name, or rgb(a) - */ - backgroundColor?: string; - - /* - * The blur factor that will be applied to all datapoints. The higher the - * blur factor is, the smoother the gradients will be - * Default value: 0.85 - */ - blur?: number; - - /* - * An object that represents the gradient - */ - gradient?: any; - - /* - * The property name of your latitude coordinate in a datapoint - * Default value: 'x' - */ - latField?: string; - - /* - * The property name of your longitude coordinate in a datapoint - * Default value: 'y' - */ - lngField?: string; - - /* - * The maximal opacity the highest value in the heatmap will have. (will be - * overridden if opacity set) - * Default value: 0.6 - */ - maxOpacity?: number; - - /* - * The minimum opacity the lowest value in the heatmap will have (will be - * overridden if opacity set) - */ - minOpacity?: number; - - /* - * A global opacity for the whole heatmap. This overrides maxOpacity and - * minOpacity if set - */ - opacity?: number; - - /* - * The radius each datapoint will have (if not specified on the datapoint - * itself) - */ - radius?: number; + /** + * The overlay layer to be added onto leaflet map + */ + class HeatmapOverlay< + V extends string, + TLat extends string, + TLng extends string + > implements Leaflet.ILayer { + /** + * Initialization function + */ + constructor(configuration: HeatmapOverlayConfiguration); /** - * Scales the radius based on map zoom. + * Initialize a heatmap instance with the given dataset */ - scaleRadius?: boolean; + setData(data: HeatmapData>): void; - /* - * Indicate whether the heatmap should use a global extrema or a local - * extrema (the maximum and minimum of the currently displayed viewport) - */ - useLocalExtrema?: boolean; + /** + * Experimential... not ready. + */ + addData(data: DataPoint | ReadonlyArray>): void; - /* - * The property name of the value/weight in a datapoint - * Default value: 'value' - */ - valueField?: string; - } - - /* - * A single data point on a heatmap. The keys are specified by - * HeatmapConfig.latField, HeatmapConfig.lngField and HeatmapConfig.valueField - */ - interface HeatmapDataPoint { - [index: string]: number; - } - - /* - * An object representing the set of data points on a heatmap - */ - interface HeatmapData { - - /* - * An array of HeatmapDataPoints - */ - data: HeatmapDataPoint[]; - - /* - * Max value of the valueField - */ - max?: number; - - /* - * Min value of the valueField - */ - min?: number; - } - - /* - * The overlay layer to be added onto leaflet map - */ - class HeatmapOverlay { - - /* - * Initialization function - */ - constructor(configuration: HeatmapConfiguration) - - /* - * Create DOM elements for an overlay, adding them to map panes and puts - * listeners on relevant map events - */ + /** + * Create DOM elements for an overlay, adding them to map panes and puts + * listeners on relevant map events + */ onAdd(map: Leaflet.Map): void; - /* - * Remove the overlay's elements from the DOM and remove listeners - * previously added by onAdd() - */ + /** + * Remove the overlay's elements from the DOM and remove listeners + * previously added by onAdd() + */ onRemove(map: Leaflet.Map): void; - - /* - * Initialize a heatmap instance with the given dataset - */ - setData(data: HeatmapData): void; } } diff --git a/types/heatmap.js/tsconfig.json b/types/heatmap.js/tsconfig.json index 06fa28716f..2e22853a34 100644 --- a/types/heatmap.js/tsconfig.json +++ b/types/heatmap.js/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/heatmap.js/tslint.json b/types/heatmap.js/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/heatmap.js/tslint.json +++ b/types/heatmap.js/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/homeworks/homeworks-tests.ts b/types/homeworks/homeworks-tests.ts index 16bce6d106..5c41b7fffc 100644 --- a/types/homeworks/homeworks-tests.ts +++ b/types/homeworks/homeworks-tests.ts @@ -1,33 +1,38 @@ const element: JQuery = $('#element'); const target: JQuery = $('#target'); +homeworks.disableHook(); + element.checkbox({ - /* Empty options */ -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); + /* Empty options */ +}) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); element.converter({ - /* Empty options */ + /* Empty options */ }); element.dropdown({ - /* Empty options */ + /* Empty options */ }); const dropdownHandlerTarget: JQuery = element.addHandler(target); element.input({ - /* Empty options */ -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); + /* Empty options */ +}) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); element.modal({ - /* Any options */ -}).each(() => { - /* Chaining */ -}); + /* Any options */ +}) + .each(() => { + /* Chaining */ + }); element.modal('show'); element.modal('hide'); element.modal('open'); @@ -35,59 +40,70 @@ element.modal('close'); notification('title', 'content', 'url', 'success'); -element.ripple({ - /* Object options */ -}); -element.start({ - x: 1, - y: 2 -}); +element + .ripple({ + /* Object options */ + }) + .on('start', (event: homeworks.RippleEvent) => { + }); + +element + .start({ + x: 1, + y: 2 + }); element.spinner({ - type: 'any', - empty: 'any' -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); - -element.step('method'); -element.step({ - active: 0 -}).bind('move', (event: HomeWorksStepEventObject) => { - /* HomeWorks step event */ -}); + type: 'any', + empty: 'any' +}) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); element.tab('method'); element.tab({ - active: 0 -}).bind('move', (event: HomeWorksTabEventObject) => { - /* HomeWorks step event */ -}); + active: 0 +}) + .on('move', (event: homeworks.TabEvent) => { + /* HomeWorks step event */ + }); + +element.step('method'); +element.step({ + active: 0 +}) + .on('move', (event: homeworks.StepEvent) => { + /* HomeWorks step event */ + }); toast('hello homeworks'); toast({ - message: 'hello homeworks' + message: 'hello homeworks' }); -element.toggle({ - placeholder: 'placeholder' -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); +element + .toggle({ + placeholder: 'placeholder' + }) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); -element.upload({ - url: 'url', - type: 'type', - data: {}, - dest: 'dest', - isBtn: true, - beforeStart() { - }, - complete(data: any) { - }, - success(data?: any, state?: any, xhr?: any) { - }, - error(xhr?: any, state?: any, error?: any) { - }, - extensions: 'any' -}); +element + .upload({ + url: 'url', + type: 'type', + data: {}, + dest: 'dest', + isBtn: true, + beforeStart() { + }, + complete(data: any) { + }, + success(data?: any, state?: any, xhr?: any) { + }, + error(xhr?: any, state?: any, error?: any) { + }, + extensions: 'any' + }); diff --git a/types/homeworks/index.d.ts b/types/homeworks/index.d.ts index 4449483d35..7a25666659 100644 --- a/types/homeworks/index.d.ts +++ b/types/homeworks/index.d.ts @@ -6,208 +6,242 @@ /// -/** - * * [MAIN] - * @ EVENT - * - */ +type _NativeEvent = Event; -declare interface HomeWorksEventObject { - element: JQuery; - value: string; - checked?: boolean; -} +interface JQuery { + /** + * jQuery homeworks chaining functions + */ -declare interface JQuery { + /** + * @since 1.0.0 + */ bind(eventType: string, handler: (...parameters: any[]) => void): JQuery; + /** + * @since 1.0.0 + */ knock(): JQuery; -} - -/** - * * [COMPONENT] - * @ CHECKBOX - * - */ -interface CheckboxOptions { -} - -declare interface JQuery { - checkbox(options?: CheckboxOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ CONVERTER - * - */ - -interface ConverterOptions { -} - -declare interface JQuery { - converter(options?: ConverterOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ DROPDOIWN - * - */ - -interface DropdownOptions { -} - -declare interface JQuery { - dropdown(options?: DropdownOptions): JQuery; - addHandler(target: JQuery): JQuery; -} - -/** - * * [COMPONENT] - * @ INPUT - * - */ - -interface InputOptions { -} - -declare interface JQuery { - input(options?: InputOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ MODAL - * - */ - -declare interface JQuery { - modal(options?: any): JQuery; - modal(method?: string, options?: any): JQuery; -} - -/** - * * [COMPONENT] - * @ NOTIFICATION - * - */ - -declare function notification(title: string, content: string, url: string, status?: string): void; - -/** - * * [COMPONENT] - * @ RIPPLE - * - */ - -interface RippleStartOptions { - x: number; - y: number; -} - -declare interface JQuery { + /** + * @since 1.0.0 + */ + checkbox(options?: homeworks.CheckboxOptions): JQuery; + /** + * @since 1.0.0 + */ + converter(options?: homeworks.ConverterOptions): JQuery; + /** + * @since 1.0.0 + */ + spinner(options?: homeworks.SpinnerOptions): JQuery; + /** + * @since 1.0.0 + */ + dropdown(options?: homeworks.DropdownOptions): JQuery; + /** + * @since 1.0.0 + */ ripple(options?: any): JQuery; - start(options?: RippleStartOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ SPINNER - * - */ - -interface SpinnerOptions { - type?: any; - empty?: any; -} - -declare interface JQuery { - spinner(options?: SpinnerOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ STEP - * - */ - -interface StepOptions { - active?: number; -} - -declare interface JQuery { - step(method?: string): JQuery; - step(options?: StepOptions): JQuery; -} - -declare interface HomeWorksStepEventObject { - header: JQuery[]; - index: number; - length: number; -} - -/** - * * [COMPONENT] - * @ TAB - * - */ - -interface TabOptions { - active?: number; -} - -declare interface JQuery { + /** + * @since 1.0.0 + */ + input(options?: homeworks.InputOptions): JQuery; + /** + * @since 1.0.0 + */ + modal(options?: any): JQuery; + /** + * @since 1.0.0 + */ + modal(method?: string, options?: any): JQuery; + /** + * @since 1.0.0 + */ tab(method?: string): JQuery; - tab(options?: TabOptions): JQuery; -} + /** + * @since 1.0.0 + */ + tab(options?: homeworks.TabOptions): JQuery; + /** + * @since 1.0.0 + */ + step(method?: string): JQuery; + /** + * @since 1.0.0 + */ + step(options?: homeworks.StepOptions): JQuery; + /** + * @since 1.0.0 + */ + toggle(options: homeworks.ToggleOptions): JQuery; + /** + * @since 1.0.0 + */ + upload(options?: homeworks.UploadOptions): JQuery; + /** + * @since 1.0.0 + * @summary dropdown method + */ + addHandler(target: JQuery): JQuery; + /** + * @since 1.0.0 + * @summary ripple method + */ + start(event?: homeworks.RippleEvent): JQuery; -declare interface HomeWorksTabEventObject { - header: JQuery[]; - index: number; - length: number; + /** + * jQuery homeworks events + */ + + /** + * @since 1.0.44 + */ + on(event: homeworks.TabMoveEventType, handler: JQuery.EventHandlerBase): JQuery; + /** + * @since 1.0.44 + */ + on(event: homeworks.StepMoveEventType, handler: JQuery.EventHandlerBase): JQuery; + /** + * @since 1.0.44 + */ + on(event: homeworks.RippleStartEventType, handler: JQuery.EventHandlerBase): JQuery; } /** - * * [COMPONENT] - * @ TOAST - * + * @since 1.0.44 */ +declare function notification( + title: string, + content: string, + url: string, + status?: string): void; +/** + * @since 1.0.44 + */ declare function toast(message: any): void; -/** - * * [COMPONENT] - * @ TOGGLE - * - */ +declare namespace homeworks { + /** + * @since 1.0.0 + */ + interface CheckboxOptions { + } -interface ToggleOptions { - placeholder?: string; -} - -declare interface JQuery { - toggle(options: ToggleOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ UPLOAD - * - */ - -interface UploadOptions { - url: string; - type?: string; - data?: any; - dest?: string; - isBtn?: boolean; - beforeStart?: () => void; - complete?: (data?: any) => void; - success?: (data?: any, state?: any, xhr?: any) => void; - error?: (xhr?: any, state?: any, error?: any) => void; - extensions?: any; -} - -declare interface JQuery { - upload(options?: UploadOptions): JQuery; + /** + * @since 1.0.0 + */ + interface ConverterOptions { + } + + /** + * @since 1.0.0 + */ + interface DropdownOptions { + } + + /** + * @since 1.0.0 + */ + interface InputOptions { + } + + /** + * @since 1.0.0 + */ + interface ToggleOptions { + placeholder?: string; + } + + /** + * @since 1.0.0 + */ + interface UploadOptions { + url: string; + type?: string; + data?: any; + dest?: string; + isBtn?: boolean; + beforeStart?: () => void; + complete?: (data?: any) => void; + success?: (data?: any, state?: any, xhr?: any) => void; + error?: (xhr?: any, state?: any, error?: any) => void; + extensions?: any; + } + + /** + * @since 1.0.0 + */ + interface SpinnerOptions { + type?: any; + empty?: any; + } + + /** + * @since 1.0.0 + */ + interface StepOptions { + active?: number; + } + + /** + * @since 1.0.0 + */ + interface TabOptions { + active?: number; + } + + /** + * @since 1.0.44 + */ + interface Event { + element: JQuery; + value: string | string[] | number; + checked?: boolean; + } + + /** + * @since 1.0.44 + */ + interface StepEvent { + header: JQuery[]; + index: number; + length: number; + } + + /** + * @since 1.0.44 + */ + interface TabEvent { + header: JQuery[]; + index: number; + length: number; + } + + /** + * @since 1.0.44 + */ + interface RippleEvent { + x: number; + y: number; + } + + /** + * @since 1.0.0 + */ + type TabMoveEventType = 'move'; + + /** + * @since 1.0.0 + */ + type StepMoveEventType = 'move'; + + /** + * @since 1.0.0 + */ + type RippleStartEventType = 'start'; + + /** + * @since 1.0.44 + */ + function disableHook(): void; } diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index ec1dbe3512..512c1567a7 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -78,9 +78,9 @@ declare namespace IORedis { strlen(key: string, callback: (err: Error, res: number) => void): void; strlen(key: string): Promise; - del(key: string, ...keys: string[]): any; + del(...keys: string[]): any; - exists(key: string, ...keys: string[]): any; + exists(...keys: string[]): any; setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; setbit(key: string, offset: number, value: any): Promise; @@ -103,11 +103,11 @@ declare namespace IORedis { decr(key: string, callback: (err: Error, res: number) => void): void; decr(key: string): Promise; - mget(key: string, ...keys: string[]): any; + mget(...keys: string[]): any; - rpush(key: string, value: any, ...values: string[]): any; + rpush(key: string, ...values: any[]): any; - lpush(key: string, value: any, ...values: string[]): any; + lpush(key: string, ...values: any[]): any; rpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; rpushx(key: string, value: any): Promise; @@ -124,9 +124,9 @@ declare namespace IORedis { lpop(key: string, callback: (err: Error, res: string) => void): void; lpop(key: string): Promise; - brpop(key: string, ...keys: string[]): any; + brpop(...keys: string[]): any; - blpop(key: string, ...keys: string[]): any; + blpop(...keys: string[]): any; brpoplpush(source: string, destination: string, timeout: number, callback: (err: Error, res: any) => void): void; brpoplpush(source: string, destination: string, timeout: number): Promise; @@ -173,17 +173,17 @@ declare namespace IORedis { srandmember(key: string, count: number, callback: (err: Error, res: any) => void): void; srandmember(key: string, count?: number): Promise; - sinter(key: string, ...keys: string[]): any; + sinter(...keys: string[]): any; - sinterstore(destination: string, key: string, ...keys: string[]): any; + sinterstore(destination: string, ...keys: string[]): any; - sunion(key: string, ...keys: string[]): any; + sunion(...keys: string[]): any; - sunionstore(destination: string, key: string, ...keys: string[]): any; + sunionstore(destination: string, ...keys: string[]): any; - sdiff(key: string, ...keys: string[]): any; + sdiff(...keys: string[]): any; - sdiffstore(destination: string, key: string, ...keys: string[]): any; + sdiffstore(destination: string, ...keys: string[]): any; smembers(key: string, callback: (err: Error, res: any) => void): void; smembers(key: string): Promise; @@ -193,10 +193,10 @@ declare namespace IORedis { zincrby(key: string, increment: number, member: string, callback: (err: Error, res: any) => void): void; zincrby(key: string, increment: number, member: string): Promise; - zrem(key: string, member: string, ...members: any[]): any; + zrem(key: string, ...members: any[]): any; - zremrangebyscore(key: string, min: number, max: number, callback: (err: Error, res: any) => void): void; - zremrangebyscore(key: string, min: number, max: number): Promise; + zremrangebyscore(key: string, min: number | string, max: number | string, callback: (err: Error, res: any) => void): void; + zremrangebyscore(key: string, min: number | string, max: number | string): Promise; zremrangebyrank(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; zremrangebyrank(key: string, start: number, stop: number): Promise; @@ -213,12 +213,12 @@ declare namespace IORedis { zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; zrevrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; - zrangebyscore(key: string, min: number, max: number, ...args: string[]): any; + zrangebyscore(key: string, min: number | string, max: number | string, ...args: string[]): any; - zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): any; + zrevrangebyscore(key: string, max: number | string, min: number | string, ...args: string[]): any; - zcount(key: string, min: number, max: number, callback: (err: Error, res: number) => void): void; - zcount(key: string, min: number, max: number): Promise; + zcount(key: string, min: number | string, max: number | string, callback: (err: Error, res: number) => void): void; + zcount(key: string, min: number | string, max: number | string): Promise; zcard(key: string, callback: (err: Error, res: number) => void): void; zcard(key: string): Promise; @@ -241,9 +241,11 @@ declare namespace IORedis { hget(key: string, field: string, callback: (err: Error, res: string) => void): void; hget(key: string, field: string): Promise; - hmset(key: string, field: string, value: any, ...args: string[]): any; + hmset(key: string, field: string, value: any, ...args: string[]): Promise<0 | 1>; + hmset(key: string, data: any, callback: (err: Error, res: 0 | 1) => void): void; + hmset(key: string, data: any): Promise<0 | 1>; - hmget(key: string, field: string, ...fields: string[]): any; + hmget(key: string, ...fields: string[]): any; hincrby(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; hincrby(key: string, field: string, increment: number): Promise; @@ -251,7 +253,7 @@ declare namespace IORedis { hincrbyfloat(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; hincrbyfloat(key: string, field: string, increment: number): Promise; - hdel(key: string, field: string, ...fields: string[]): any; + hdel(key: string, ...fields: string[]): any; hlen(key: string, callback: (err: Error, res: number) => void): void; hlen(key: string): Promise; @@ -388,18 +390,18 @@ declare namespace IORedis { config(...args: any[]): any; - subscribe(channel: string, ...channels: any[]): any; + subscribe(...channels: any[]): any; unsubscribe(...channels: string[]): any; - psubscribe(pattern: string, ...patterns: string[]): any; + psubscribe(...patterns: string[]): any; punsubscribe(...patterns: string[]): any; publish(channel: string, message: string, callback: (err: Error, res: number) => void): void; publish(channel: string, message: string): Promise; - watch(key: string, ...keys: string[]): any; + watch(...keys: string[]): any; unwatch(callback: (err: Error, res: string) => void): void; unwatch(): Promise; @@ -432,11 +434,11 @@ declare namespace IORedis { zscan(key: string, cursor: number, ...args: any[]): any; - pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): any; + pfmerge(destkey: string, ...sourcekeys: string[]): any; - pfadd(key: string, element: string, ...elements: string[]): any; + pfadd(key: string, ...elements: string[]): any; - pfcount(key: string, ...keys: string[]): any; + pfcount(...keys: string[]): any; pipeline(commands?: string[][]): Pipeline; @@ -464,9 +466,9 @@ declare namespace IORedis { strlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; - del(key: string, ...keys: string[]): Pipeline; + del(...keys: string[]): Pipeline; - exists(key: string, ...keys: string[]): Pipeline; + exists(...keys: string[]): Pipeline; setbit(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; @@ -482,11 +484,11 @@ declare namespace IORedis { decr(key: string, callback?: (err: Error, res: number) => void): Pipeline; - mget(key: string, ...keys: string[]): Pipeline; + mget(...keys: string[]): Pipeline; - rpush(key: string, value: any, ...values: string[]): Pipeline; + rpush(key: string, ...values: any[]): Pipeline; - lpush(key: string, value: any, ...values: string[]): Pipeline; + lpush(key: string, ...values: any[]): Pipeline; rpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; @@ -498,9 +500,9 @@ declare namespace IORedis { lpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; - brpop(key: string, ...keys: string[]): Pipeline; + brpop(...keys: string[]): Pipeline; - blpop(key: string, ...keys: string[]): Pipeline; + blpop(...keys: string[]): Pipeline; brpoplpush(source: string, destination: string, timeout: number, callback?: (err: Error, res: any) => void): Pipeline; @@ -534,17 +536,17 @@ declare namespace IORedis { srandmember(key: string, callback?: (err: Error, res: any) => void): Pipeline; srandmember(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; - sinter(key: string, ...keys: string[]): Pipeline; + sinter(...keys: string[]): Pipeline; - sinterstore(destination: string, key: string, ...keys: string[]): Pipeline; + sinterstore(destination: string, ...keys: string[]): Pipeline; - sunion(key: string, ...keys: string[]): Pipeline; + sunion(...keys: string[]): Pipeline; - sunionstore(destination: string, key: string, ...keys: string[]): Pipeline; + sunionstore(destination: string, ...keys: string[]): Pipeline; - sdiff(key: string, ...keys: string[]): Pipeline; + sdiff(...keys: string[]): Pipeline; - sdiffstore(destination: string, key: string, ...keys: string[]): Pipeline; + sdiffstore(destination: string, ...keys: string[]): Pipeline; smembers(key: string, callback?: (err: Error, res: any) => void): Pipeline; @@ -552,9 +554,9 @@ declare namespace IORedis { zincrby(key: string, increment: number, member: string, callback?: (err: Error, res: any) => void): Pipeline; - zrem(key: string, member: string, ...members: any[]): Pipeline; + zrem(key: string, ...members: any[]): Pipeline; - zremrangebyscore(key: string, min: number, max: number, callback?: (err: Error, res: any) => void): Pipeline; + zremrangebyscore(key: string, min: number | string, max: number | string, callback?: (err: Error, res: any) => void): Pipeline; zremrangebyrank(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; @@ -568,11 +570,11 @@ declare namespace IORedis { zrevrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; - zrangebyscore(key: string, min: number, max: number, ...args: string[]): Pipeline; + zrangebyscore(key: string, min: number | string, max: number | string, ...args: string[]): Pipeline; - zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): Pipeline; + zrevrangebyscore(key: string, max: number | string, min: number | string, ...args: string[]): Pipeline; - zcount(key: string, min: number, max: number, callback?: (err: Error, res: number) => void): Pipeline; + zcount(key: string, min: number | string, max: number | string, callback?: (err: Error, res: number) => void): Pipeline; zcard(key: string, callback?: (err: Error, res: number) => void): Pipeline; @@ -590,13 +592,13 @@ declare namespace IORedis { hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; - hmget(key: string, field: string, ...fields: string[]): Pipeline; + hmget(key: string, ...fields: string[]): Pipeline; hincrby(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; hincrbyfloat(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; - hdel(key: string, field: string, ...fields: string[]): Pipeline; + hdel(key: string, ...fields: string[]): Pipeline; hlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; @@ -692,17 +694,17 @@ declare namespace IORedis { config(...args: any[]): Pipeline; - subscribe(channel: string, ...channels: any[]): Pipeline; + subscribe(...channels: any[]): Pipeline; unsubscribe(...channels: string[]): Pipeline; - psubscribe(pattern: string, ...patterns: string[]): Pipeline; + psubscribe(...patterns: string[]): Pipeline; punsubscribe(...patterns: string[]): Pipeline; publish(channel: string, message: string, callback?: (err: Error, res: number) => void): Pipeline; - watch(key: string, ...keys: string[]): Pipeline; + watch(...keys: string[]): Pipeline; unwatch(callback?: (err: Error, res: string) => void): Pipeline; @@ -732,11 +734,11 @@ declare namespace IORedis { zscan(key: string, cursor: number, ...args: any[]): Pipeline; - pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): Pipeline; + pfmerge(destkey: string, ...sourcekeys: string[]): Pipeline; - pfadd(key: string, element: string, ...elements: string[]): Pipeline; + pfadd(key: string, ...elements: string[]): Pipeline; - pfcount(key: string, ...keys: string[]): Pipeline; + pfcount(...keys: string[]): Pipeline; } interface Cluster extends NodeJS.EventEmitter, Commander { diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 02b62def62..99c7efada3 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -104,3 +104,6 @@ redis.multi([ ]).exec((err, results) => { // results = [[null, 'OK'], [null, 'bar']] }); + +const keys = [ 'foo', 'bar' ]; +redis.mget(...keys); diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 41a8063cac..cc13a9deca 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -16,7 +16,7 @@ export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; -export type LanguageOptions = string | false | null | { +export type LanguageOptions = string | boolean | null | { [key: string]: LanguageOptions; }; diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 785360746e..34fc5271e0 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -1,5 +1,4 @@ import Joi = require('joi'); -import { GuidVersions } from 'joi'; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -772,7 +771,7 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({ version: ['uuidv1' as GuidVersions, 'uuidv2' as GuidVersions, 'uuidv3' as GuidVersions, 'uuidv4' as GuidVersions, 'uuidv5' as GuidVersions]}); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); diff --git a/types/joi/v10/index.d.ts b/types/joi/v10/index.d.ts index 372975ed9e..9270c411aa 100644 --- a/types/joi/v10/index.d.ts +++ b/types/joi/v10/index.d.ts @@ -15,7 +15,7 @@ export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; -export type LanguageOptions = string | false | null | { +export type LanguageOptions = string | boolean | null | { [key: string]: LanguageOptions; }; diff --git a/types/joi/v10/joi-tests.ts b/types/joi/v10/joi-tests.ts index 226abb3a7f..bfc6268ef7 100644 --- a/types/joi/v10/joi-tests.ts +++ b/types/joi/v10/joi-tests.ts @@ -765,7 +765,7 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); diff --git a/types/joi/v10/tslint.json b/types/joi/v10/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/joi/v10/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/jquery-jcrop/index.d.ts b/types/jquery-jcrop/index.d.ts new file mode 100644 index 0000000000..af2afaf9d7 --- /dev/null +++ b/types/jquery-jcrop/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for jcrop 2.0 +// Project: https://github.com/tapmodo/Jcrop/ +// Definitions by: Joe Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +declare namespace JQuery.Jcrop { + interface Options { + /** Aspect ratio of w/h (e.g. 1 for square) */ + aspectRatio?: number; + /** Minimum width/height, use 0 for unbounded dimension; [width, height] */ + minSize?: [number, number]; + /** Maximum width/height, use 0 for unbounded dimension; [width, height] */ + maxSize?: [number, number]; + minSelect?: [number, number]; + /** Set an initial selection area; [x, y, x2, y2] */ + setSelect?: [number, number, number, number]; + + /** Set color of background container @default 'black' */ + bgColor?: string; + /** Opacity of outer image when cropping; between 0 and 1 @default .6 */ + bgOpacity?: number; + baseClass?: string; + addClass?: string; + bgFade?: boolean; + borderOpacity?: number; + handleOpacity?: number; + handleSize?: number | null; + + /** Called when selection is completed */ + onSelect?: JCropEventHandler; + /** Called when the selection is moving */ + onChange?: JCropEventHandler; + /** Called when double-clicked */ + onDblClick?: JCropEventHandler; + /** Called when the selection is released */ + onRelease?: JCropEventHandler; + + /** Maximum width of cropping area @default 0 (no limit) */ + boxWidth?: number; + /** Maximum height of cropping area @default 0 (no limit) */ + boxHeight?: number; + boundary?: number; + fadeTime?: number; + animationDelay?: number; + swingSpeed?: number; + + /** Specify the true size of the image */ + trueSize?: [number, number]; + + // Basic Settings + allowSelect?: boolean; + allowMove?: boolean; + allowResize?: boolean; + + trackDocument?: boolean; + + keySupport?: boolean; + createHandles?: Array; + createDragbars?: CardinalDirection[]; + createBorders?: CardinalDirection[]; + drawBorders?: boolean; + dragEdges?: boolean; + fixedSupport?: boolean; + touchSupport?: boolean | null; + shade?: boolean | null; + } + + type CardinalDirection = 'n' | 's' | 'e' | 'w'; + type IntermediateDirection = 'nw' | 'ne' | 'se' | 'sw'; + type JCropEventHandler = (c: SelectionInfo) => void; + interface SelectionInfo { + x: number; + y: number; + x2: number; + y2: number; + w: number; + h: number; + } + + interface Api { + /** Set selection, format: [ x,y,x2,y2 ] */ + setSelect: (selection: [number, number, number, number]) => void; + /** Animate selection to new selection, format: [ x,y,x2,y2 ] */ + animateTo: (selection: [number, number, number, number]) => void; + /** Release current selection */ + release: () => void; + + /** Query current selection values (true size) */ + tellSelect: () => SelectionInfo; + /** Query current selection values (interface) */ + tellScaled: () => SelectionInfo; + + /** Disables Jcrop interactivity */ + disable: () => void; + /** Enables Jcrop interactivity */ + enable: () => void; + /** Remove Jcrop entirely */ + remove: () => void; + } +} + +interface JQuery { + Jcrop(options?: JQuery.Jcrop.Options, callback?: (this: JQuery.Jcrop.Api) => void): JQuery; +} diff --git a/types/jquery-jcrop/jquery-jcrop-tests.ts b/types/jquery-jcrop/jquery-jcrop-tests.ts new file mode 100644 index 0000000000..f5fb25f39c --- /dev/null +++ b/types/jquery-jcrop/jquery-jcrop-tests.ts @@ -0,0 +1,54 @@ +jQuery(($) => { + $('#target').Jcrop(); +}); + +function showCoords(c: { x: number, y: number, x2: number; y2: number; w: number; h: number; }) { + // variables can be accessed here as + // c.x, c.y, c.x2, c.y2, c.w, c.h +} + +jQuery(($) => { + $('#target').Jcrop({ + onSelect: showCoords, + onChange: showCoords + }); +}); + +jQuery(($) => { + $('#target').Jcrop({ + onSelect: showCoords, + bgColor: 'black', + bgOpacity: .4, + setSelect: [100, 100, 50, 50], + aspectRatio: 16 / 9 + }); +}); + +let jcrop_api; +$('#target').Jcrop({}, function() { + jcrop_api = this; +}); + +jQuery(($) => { + let jcrop_api: JQuery.Jcrop.Api; + + $('#target').Jcrop({ + bgColor: 'red' + }, function() { + jcrop_api = this; + }); + + $('#animbutton').click((e) => { + jcrop_api.animateTo([120, 120, 80, 80]); + return false; + }); + + $('#delselect').click((e) => { + jcrop_api.release(); + return false; + }); +}); + +(() => { + $('#cropbox').Jcrop({ boxWidth: 450, boxHeight: 400 }); +}); diff --git a/types/jquery-jcrop/tsconfig.json b/types/jquery-jcrop/tsconfig.json new file mode 100644 index 0000000000..add23691c0 --- /dev/null +++ b/types/jquery-jcrop/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery-jcrop-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-jcrop/tslint.json b/types/jquery-jcrop/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/jquery-jcrop/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jquery-notifier/index.d.ts b/types/jquery-notifier/index.d.ts new file mode 100644 index 0000000000..bf9d0ff93b --- /dev/null +++ b/types/jquery-notifier/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for notifier 1.0 +// Project: https://github.com/allipierre/jquery-notifier +// Definitions by: Alli Pierre Yotti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace notifier { + /** + * notifier.show(title, msg, type, icon, timeout); + * {title} title + * {msg} msg + * {type} type + * {icon} icon + * {timeout} timeout + */ + function show(title: string, msg: string, type: string, icon: string, timeout?: number): string | number; + + function hide(notificationId: string | number): boolean; +} diff --git a/types/jquery-notifier/jquery-notifier-tests.ts b/types/jquery-notifier/jquery-notifier-tests.ts new file mode 100644 index 0000000000..18804758be --- /dev/null +++ b/types/jquery-notifier/jquery-notifier-tests.ts @@ -0,0 +1,31 @@ +notifier.show('Hello!', 'I am a default notification.', '', '', 0); +notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', '', 0); +notifier.show('Well Done!', 'You just submit your resume successfuly.', '', '', 0); +notifier.show('Warning!', 'The data presented here can be change.', '', '', 0); +notifier.show('Sorry!', 'Could not complete your transaction.', '', '', 0); + +notifier.show('Default!', 'I am a default notification.', '', 'img/clock-48.png', 0); +notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', 'img/survey-48.png', 0); +notifier.show('Well Done!', 'You just submit your resume successfuly.', '', 'img/ok-48.png', 0); +notifier.show('Warning!', 'The data presented here can be change.', '', 'img/medium_priority-48.png', 0); +notifier.show('Sorry!', 'Could not complete your transaction.', '', 'img/high_priority-48.png', 0); + +notifier.show('Default!', 'I am a default notification.', '', 'img/clock-48.png', 4000); +notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', 'img/survey-48.png', 4000); +notifier.show('Well Done!', 'You just submit your resume successfuly.', '', 'img/ok-48.png', 4000); +notifier.show('Warning!', 'The data presented here can be change.', '', 'img/medium_priority-48.png', 4000); +notifier.show('Sorry!', 'Could not complete your transaction.', '', 'img/high_priority-48.png', 4000); + +let notificationId: string | number; + +let showNotification = () => { + notificationId = notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', 'img/survey-48.png', 4000); +}; + +let hideNotification = () => { + notifier.hide(notificationId); +}; + +document.querySelector('#btn-nt-show').addEventListener('click', showNotification); + +document.querySelector('#btn-nt-hide').addEventListener('click', hideNotification); diff --git a/types/jquery.tooltipster/tsconfig.json b/types/jquery-notifier/tsconfig.json similarity index 80% rename from types/jquery.tooltipster/tsconfig.json rename to types/jquery-notifier/tsconfig.json index edc2812c82..b2178bf718 100644 --- a/types/jquery.tooltipster/tsconfig.json +++ b/types/jquery-notifier/tsconfig.json @@ -5,8 +5,8 @@ "es6", "dom" ], - "noImplicitAny": false, - "noImplicitThis": false, + "noImplicitAny": true, + "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "jquery.tooltipster-tests.ts" + "jquery-notifier-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jquery-notifier/tslint.json b/types/jquery-notifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jquery-notifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery.tooltipster/index.d.ts b/types/jquery.tooltipster/index.d.ts deleted file mode 100644 index 44536908ff..0000000000 --- a/types/jquery.tooltipster/index.d.ts +++ /dev/null @@ -1,285 +0,0 @@ -// Type definitions for jQuery Tooltipster 3.3.0 -// Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee , -// Dmitry Pesterev , -// Leonard Thieu , -// Jan Hirzel -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -interface JQueryTooltipsterOptions { - /** - * Determines how the tooltip will animate in and out. Feel free to modify or create custom transitions in the tooltipster.css file. In IE9 and 8, all animations default to a JavaScript generated, fade animation. Default: 'fade' - * fade, grow, swing, slide, fall - */ - animation?: string; - /** - * Adds the "speech bubble arrow" to the tooltip. Default: true - */ - arrow?: boolean; - /** - * Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color - * hex code / rgb - */ - arrowColor?: string; - /** - * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true - */ - autoClose?: boolean; - /** - * If set, this will override the content of the tooltip. Default: null - * @type string, jQuery object - */ - content?: string | JQuery; - /** - * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false - */ - contentAsHTML?: boolean; - /** - * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true - */ - contentCloning?: boolean; - /** - * Tooltipster logs notices into the console when you're doing something you ideally shouldn't be doing. Set to false to disable logging. Default: true - */ - debug?: boolean; - /** - * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 - */ - delay?: number; - /** - * Set a minimum width for the tooltip. Default: 0 (auto width) - */ - minWidth?: number; - /** - * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) - */ - maxWidth?: number; - /** - * Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {} - */ - functionInit?: (origin: JQuery, content: string) => void | string; - /** - * Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); } - */ - functionBefore?: (origin: JQuery, continueTooltip: Function) => void; - /** - * Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {} - */ - functionReady?: (origin: JQuery, tooltip: JQuery) => void; - /** - * Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {} - */ - functionAfter?: (origin: JQuery) => void; - /** - * If true, the tooltip will close if its origin is clicked. This option only applies when 'trigger' is 'hover' and 'autoClose' is false. Default: false - */ - hideOnClick?: boolean; - /** - * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' - * @type string, jQuery object - */ - icon?: string | JQuery; - /** - * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true - */ - iconCloning?: boolean; - /** - * Generate an icon next to your content that is responsible for activating the tooltip on non-touch devices. Default: false - */ - iconDesktop?: boolean; - /** - * If using the iconDesktop or iconTouch options, this sets the class on the icon (used to style the icon). Default: 'tooltipster-icon' - */ - iconTheme?: string; - /** - * Generate an icon next to your content that is responsible for activating the tooltip on touch devices (tablets, phones, etc). Default: false - */ - iconTouch?: boolean; - /** - * Give users the possibility to interact with the tooltip. Unless autoClose is set to false, the tooltip will still close if the user moves away from or clicks out of the tooltip. Default: false - */ - interactive?: boolean; - /** - * If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350 - */ - interactiveTolerance?: number; - /** - * Allows you to put multiple tooltips on a single element. Read further instructions down this page. Default: false - */ - multiple?: boolean; - /** - * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 - */ - offsetX?: number; - /** - * Offsets the tooltip (in pixels) farther up/down from the origin. Default: 0 - */ - offsetY?: number; - /** - * If true, only one tooltip will be allowed to be active at a time. Non-autoclosing tooltips will not be closed though. Default: false - */ - onlyOne?: boolean; - /** - * Set the position of the tooltip. Default: 'top' - * right, left, top, top-right, top-left, bottom, bottom-right, bottom-left - */ - position?: string; - /** - * Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false - */ - positionTracker?: boolean; - /** - * Called after the tooltip has been repositioned by the position tracker (if enabled). Default: A function that will close the tooltip if the trigger is 'hover' and autoClose is false. - */ - positionTrackerCallback?: (origin: JQuery) => void; - /** - * Specify if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' method. This attribute may be omitted, or be restored with the value that existed before Tooltipster was initialized, or be restored with the stringified value of the current content. Note: in case of multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. Default: 'current' - */ - restoration?: string; - /** - * Sets the side of the tooltip. The value may one of the following: 'top', 'bottom', 'left', 'right'. It may also be an array containing one or more of these values. When using an array, the order of values is taken into account as order of fallbacks and the absence of a side disables it (see the sides section). Default: ['top', 'bottom', 'right', 'left'] - */ - side?: string | string[]; - /** - * Set the speed of the animation. Default: 350 - */ - speed?: number; - /** - * How long the tooltip should be allowed to live before closing. Default: 0 (disabled) - */ - timer?: number; - /** - * Set the theme used for your tooltip. Default: 'tooltipster-default' - */ - theme?: string; - /** - * If set to false, tooltips will not show on pure-touch devices, unless you open them yourself with the 'show' method. Touch gestures on devices which also have a mouse will still open the tooltips though. Default: true - */ - touchDevices?: boolean; - /** - * Set how tooltips should be activated and closed. See the advanced section to learn how to build custom triggers. Default: 'hover' - * hover, click, custom - */ - trigger?: string; - /** - * If a tooltip is open while its content is updated, play a subtle animation when the content changes. Default: true - */ - updateAnimation?: boolean; -} - -interface JQuery { - - /** - * Show a tooltip (the 'callback' argument is optional) - * @param methodName show - * @param callback Function for call back - */ - tooltipster(methodName: "show", callback?: Function): JQuery; - - /** - * Hide a tooltip (the 'callback' argument is optional) - * @param methodName hide - * @param callback Function for call back - */ - tooltipster(methodName: "hide", callback?: Function): JQuery; - - /** - * Update tooltip content - * @param methodName content - * @param newContent New content - */ - tooltipster(methodName: "content", newContent: string): JQuery; - - /** - * Update tooltip content - * @param methodName option - * @param optionName Option name - */ - tooltipster(methodName: "option", optionName: string): JQuery; - - /** - * Set the value of an option (use at your own risk, we do not provide support for issues you may encounter when using this method) - * @param methodName option - * @param optionName Option name - * @param optionValue New vale for option - */ - tooltipster(methodName: "option", optionName: string, optionValue: string): JQuery; - - - /** - * Temporarily disable a tooltip from being able to open - * @param methodName disable - */ - tooltipster(methodName: "disable"): JQuery; - - /** - * Temporarily disable a tooltip from being able to open - * @param methodName enable - */ - tooltipster(methodName: "enable"): JQuery; - - /** - * Hide and destroy tooltip functionality - * @param methodName destroy - */ - tooltipster(methodName: "destroy"): JQuery; - - /** - * Return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned) - * @param methodName content - */ - tooltipster(methodName: "content"): string; - - /** - * Reposition and resize the tooltip - * @param methodName reposition - */ - tooltipster(methodName: "reposition"): JQuery; - - /** - * Return the HTML root element of the tooltip - * @param methodName elementTooltip - */ - tooltipster(methodName: "elementTooltip"): JQuery; - - /** - * Return the HTML root element of the icon if there is one, 'undefined' otherwise - * @param methodName elementIcon - */ - tooltipster(methodName: "elementIcon"): JQuery; - - /** - * Change default options for all future instances - * @param methodName setDefaults - * @param {object} options The options that should be made defaults - */ - tooltipster(methodName: 'setDefaults', options: JQueryTooltipsterOptions): JQuery; - - /** - * Generics - */ - tooltipster(methodName: string, optionName: string, optionValue?: string): JQuery; - tooltipster(methodName: string): JQuery | string; - - /** - * Creates a new tooltip with the specified, or default, options. - * @param options The options - * @example - * $('.tooltip').tooltipster({ - * animation: 'fade', - * delay: 200, - * theme: 'tooltipster-default', - * touchDevices: false, - * trigger: 'hover' - * }); - */ - tooltipster(options?: JQueryTooltipsterOptions): JQuery; - - /** - * Initiate the Tooltipster plugin - */ - tooltipster(): JQuery; -} diff --git a/types/jquery.tooltipster/jquery.tooltipster-tests.ts b/types/jquery.tooltipster/jquery.tooltipster-tests.ts deleted file mode 100644 index 3d48c29bcc..0000000000 --- a/types/jquery.tooltipster/jquery.tooltipster-tests.ts +++ /dev/null @@ -1,202 +0,0 @@ - - -// Type definition tests for jQuery Tooltipster 3.3.0 -// Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee , Dmitry Pesterev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Tests taken from the getting started section of the Tooltipster website - -$(document).ready(function () { - - $('.tooltip').tooltipster(); - - $('#my-tooltip').tooltipster({ - content: $(' This text is in bold case !') - }); - - $('#my-tooltip').tooltipster({ - content: 'string test' - }); -}); - - -$(document).ready(function () { - $('.tooltip').tooltipster({ - contentAsHTML: true - }); -}); - -$('.tooltip').tooltipster({ - theme: 'tooltipster-noir' -}); - -$('.tooltip').tooltipster({ - animation: 'fade', - delay: 200, - theme: 'tooltipster-default', - touchDevices: false, - trigger: 'hover' -}); - -$.fn.tooltipster('setDefaults', { - position: 'bottom' -}); - -var myNewContent = ''; - -function callback(): void { - -} - -// temporarily disable a tooltip from being able to open -$('.tooltip').tooltipster('disable'); - -// if a tooltip was disabled from opening, reenable its previous functionality -$('.tooltip').tooltipster('enable'); - -// hide and destroy tooltip functionality -$('.tooltip').tooltipster('destroy'); - -// return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned) -$('.tooltip').tooltipster('content'); - -// update tooltip content -$('.tooltip').tooltipster('content', myNewContent); - -//update option -$('.tooltip').tooltipster('option', 'delay', '200'); - -// reposition and resize the tooltip -$('.tooltip').tooltipster('reposition'); - -// return the HTML root element of the tooltip -$('.tooltip').tooltipster('elementTooltip'); - -// return the HTML root element of the icon if there is one, 'undefined' otherwise -$('.tooltip').tooltipster('elementIcon'); - -$('.tooltip').tooltipster({ - content: 'Loading...', - functionBefore: function (origin, continueTooltip) { - - // we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data - continueTooltip(); - - // next, we want to check if our data has already been cached - if (origin.data('ajax') !== 'cached') { - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - // update our tooltip content with our returned data and cache it - origin.tooltipster('content', data).data('ajax', 'cached'); - } - }); - } - } -}); - - - -$('.tooltip').tooltipster({ - content: 'Loading...', - functionBefore: (origin, continueTooltip) => { - - // we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data - continueTooltip(); - - // next, we want to check if our data has already been cached - if (origin.data('ajax') !== 'cached') { - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - // update our tooltip content with our returned data and cache it - origin.tooltipster('content', data).data('ajax', 'cached'); - } - }); - } - } -}); - -$('.tooltip').tooltipster({ - functionInit: function (origin, content) { - - if (content === 'This is bad content') { - - // when the request has finished loading, we will change the tooltip's content - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - origin.tooltipster('content', 'New content has been loaded : ' + data); - } - }); - - // this returned string will overwrite the content of the tooltip for the time being - return 'Wait while we load new content...'; - } - else { - // return nothing : the initialization continues normally with its content unchanged. - } - } -}); - -$('.tooltip').tooltipster({ - functionInit: (origin, content) => { - - if (content === 'This is bad content') { - - // when the request has finished loading, we will change the tooltip's content - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - origin.tooltipster('content', 'New content has been loaded : ' + data); - } - }); - - // this returned string will overwrite the content of the tooltip for the time being - return 'Wait while we load new content...'; - } - else { - // return nothing : the initialization continues normally with its content unchanged. - } - } -}); - -$(document).ready(function () { - - // first on page load, initiate the Tooltipster plugin - $('.tooltip').tooltipster(); - - $('.tooltip').tooltipster({ - contentAsHTML: true - }); - - $('.tooltip').tooltipster({ - content: $(' This text is in bold case !') - }); - - // then immediately show the tooltip - $('#example').tooltipster('show'); - - // as soon as a key is pressed on the keyboard, hide the tooltip. - $(window).keypress(function () { - $('#example').tooltipster('hide'); - }); - - $('#example').tooltipster('show', function () { - alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); - }); - - $('#example').tooltipster('show', () => { - alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); - }); - - $(window).keypress(function () { - $('#example').tooltipster('hide', function () { - alert('The tooltip is now fully closed'); - }); - }); -}); diff --git a/types/jsonwebtoken/index.d.ts b/types/jsonwebtoken/index.d.ts index 335a6f52b7..766042e627 100644 --- a/types/jsonwebtoken/index.d.ts +++ b/types/jsonwebtoken/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for jsonwebtoken 7.2.0 +// Type definitions for jsonwebtoken 7.2.1 // Project: https://github.com/auth0/node-jsonwebtoken -// Definitions by: Maxime LUCE , Daniel Heim +// Definitions by: Maxime LUCE , +// Daniel Heim , +// Brice BERNARD // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -51,7 +53,6 @@ export interface SignOptions { noTimestamp?: boolean; header?: object; encoding?: string; - } export interface VerifyOptions { @@ -61,7 +62,7 @@ export interface VerifyOptions { issuer?: string | string[]; ignoreExpiration?: boolean; ignoreNotBefore?: boolean; - jwtId?: string; + jwtid?: string; subject?: string; /** *@deprecated @@ -76,14 +77,17 @@ export interface DecodeOptions { } export interface VerifyCallback { - (err: JsonWebTokenError | NotBeforeError | TokenExpiredError, decoded: object | string): void; + ( + err: JsonWebTokenError | NotBeforeError | TokenExpiredError, + decoded: object | string, + ): void; } export interface SignCallback { (err: Error, encoded: string): void; } -export type Secret = string | Buffer | {key: string, passphrase: string} +export type Secret = string | Buffer | { key: string; passphrase: string }; /** * Synchronously sign the given payload into a JSON Web Token string @@ -92,7 +96,11 @@ export type Secret = string | Buffer | {key: string, passphrase: string} * @param {SignOptions} [options] - Options for the signature * @returns {String} The JSON Web Token string */ -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions): string; +export declare function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options?: SignOptions, +): string; /** * Sign the given payload into a JSON Web Token string @@ -101,8 +109,17 @@ export declare function sign(payload: string | Buffer | object, secretOrPrivateK * @param {SignOptions} [options] - Options for the signature * @param {Function} callback - Callback to get the encoded token on */ -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback): void; -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, callback: SignCallback): void; +export declare function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + callback: SignCallback, +): void; +export declare function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options: SignOptions, + callback: SignCallback, +): void; /** * Synchronously verify given token using a secret or a public key to get a decoded token @@ -111,8 +128,15 @@ export declare function sign(payload: string | Buffer | object, secretOrPrivateK * @param {VerifyOptions} [options] - Options for the verification * @returns The decoded token. */ -declare function verify(token: string, secretOrPublicKey: string | Buffer): object | string; -declare function verify(token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions): object | string; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, +): object | string; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, + options?: VerifyOptions, +): object | string; /** * Asynchronously verify given token using a secret or a public key to get a decoded token @@ -121,8 +145,17 @@ declare function verify(token: string, secretOrPublicKey: string | Buffer, optio * @param {VerifyOptions} [options] - Options for the verification * @param {Function} callback - Callback to get the decoded token on */ -declare function verify(token: string, secretOrPublicKey: string | Buffer, callback?: VerifyCallback): void; -declare function verify(token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, + callback?: VerifyCallback, +): void; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, + options?: VerifyOptions, + callback?: VerifyCallback, +): void; /** * Returns the decoded payload without verifying if the signature is valid. @@ -130,4 +163,7 @@ declare function verify(token: string, secretOrPublicKey: string | Buffer, optio * @param {DecodeOptions} [options] - Options for decoding * @returns {Object} The decoded Token */ -declare function decode(token: string, options?: DecodeOptions): null | object | string; +declare function decode( + token: string, + options?: DecodeOptions, +): null | object | string; diff --git a/types/jss/index.d.ts b/types/jss/index.d.ts index 18278d80d1..d0136216ed 100644 --- a/types/jss/index.d.ts +++ b/types/jss/index.d.ts @@ -1,50 +1,127 @@ -// Type definitions for jss v0.6 -// Project: https://github.com/Box9/jss -// Definitions by: Valentin Robert +// Type definitions for jss 9.3 +// Project: https://github.com/cssinjs/jss#readme +// Definitions by: Brenton Simpson +// Oleg Slobodskoi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -interface Properties { - [name: string]: string; +export interface Rule { + className: string; + selector: string; + applyTo(element: HTMLElement): void; + prop(key: string): string; + prop(key: string, value: any): this; + toJSON(): string; } - -interface Selectors { - [selector: string]: Properties; +export interface StyleSheet { + // Gives auto-completion on the rules declared in `createStyleSheet` without + // causing errors for rules added dynamically after creation. + classes: { + [K in keyof T]: string; + } & { [key: string]: string }; + options: any; + linked: boolean; + attached: boolean; + /** + * Attach renderable to the render tree. + */ + attach(): this; + /** + * Remove renderable from render tree. + */ + detach(): this; + /** + * Add a rule to the current stylesheet. + * Will insert a rule also after the stylesheet has been rendered first time. + */ + addRule(style: Style, options?: Partial): Rule; + addRule(name: string, style: Style, options?: Partial): Rule; + /** + * Create and add rules. + * Will render also after Style Sheet was rendered the first time. + */ + addRules(styles: { [key: string]: Style }, options?: Partial): Rule[]; + /** + * Get a rule by name. + */ + getRule(name: string): Rule; + /** + * Delete a rule by name. + * Returns `true`: if rule has been deleted from the DOM. + */ + deleteRule(name: string): boolean; + /** + * Get index of a rule. + */ + indexOf(rule: Rule): number; + /** + * Update the function values with a new data. + */ + update(data?: {}): this; + update(name: string, data: {}): this; + /** + * Convert rules to a CSS string. + */ + toString(options?: { indent?: number }): string; } - -interface JSS { - /** - * Retrieve all rules added via JSS, organized by selectors - */ - get(): Selectors; - - /** - * Retrieve rules added via JSS for a given selector - * @param s CSS selector - */ - get(s: string): Properties; - - /** - * Retrieve all rules specified for a given selector (not necessarily added via JSS) - * @param s CSS selector - */ - getAll(s: string): Properties; - - /** - * Remove all rules added via JSS - */ - remove(): void; - - /** - * Remove all rules added via JSS for the given selector - */ - remove(s: string): void; - - /** - * Add or extend an existing rule - * @param s CSS selector - * @param p CSS properties - */ - set(s: string, p: Properties): void; +export type GenerateClassName = (rule: Rule, sheet?: StyleSheet) => string; +export interface Style { + [key: string]: any; } - -declare var jss: JSS; +export interface JSSPlugin { + [key: string]: () => Partial<{ + onCreateRule(name: string, style: Style, options: RuleOptions): Rule, + onProcessRule(rule: Rule, sheet: StyleSheet): void, + onProcessStyle(style: Style, rule: Rule, sheet: StyleSheet): Style, + onProcessSheet(sheet: StyleSheet): void, + onChangeValue(value: any, prop: string, rule: Rule): any, + onUpdate(data: {}, rule: Rule, sheet: StyleSheet): void, + }>; +} +export interface JSSOptions { + createGenerateClassName(): GenerateClassName; + plugins: ReadonlyArray; + virtual: boolean; + insertionPoint: string | HTMLElement; +} +export interface RuleFactoryOptions { + selector: string; + classes: { [key: string]: string }; + sheet: StyleSheet; + index: number; + jss: JSS; + generateClassName: GenerateClassName; +} +export interface RuleOptions { + index: number; + className: string; +} +declare class JSS { + constructor(options?: Partial); + createStyleSheet( + styles: T, + options?: Partial<{ + media: string, + meta: string, + link: boolean, + element: HTMLStyleElement, + index: number, + generateClassName: GenerateClassName, + classNamePrefix: string, + }>, + ): StyleSheet; + removeStyleSheet(sheet: StyleSheet): this; + setup(options?: Partial): this; + use(plugin: JSSPlugin): this; + createRule(style: Style, options?: Partial): Rule; + createRule(name: string, style: Style, options?: Partial): Rule; +} +/** + * Creates a new instance of JSS. + */ +export function create(options?: Partial): JSS; +declare const sharedInstance: JSS; +/** + * A global JSS instance. + */ +export default sharedInstance; diff --git a/types/jss/jss-tests.ts b/types/jss/jss-tests.ts index 2863bbfb66..0cf3f51350 100644 --- a/types/jss/jss-tests.ts +++ b/types/jss/jss-tests.ts @@ -1,16 +1,62 @@ +// API docs at http://cssinjs.org/js-api +import { + create as createJSS, + default as sharedInstance +} from 'jss'; -jss.set('.demo', { - 'font-size': '15px', - 'color': 'red' +const jss = createJSS().setup({}); + +const styleSheet = jss.createStyleSheet( + { + ruleWithMockObservable: { + subscribe() {} + }, + container: { + display: 'flex', + width: 100, + opacity: .5, + }, + }, + { + link: true, + } +).attach(); + +styleSheet.classes.container; // $ExpectType string +styleSheet.classes.ruleWithMockObservable; // $ExpectType string + +const rule = styleSheet.addRule('dynamicRule', { color: 'indigo' }); +rule.prop('border-radius', 5).prop('color'); // $ExpectType string +styleSheet.classes.dynamicRule; // $ExpectType string + +styleSheet.deleteRule('dynamicRule'); + +// test that `addRule` supports the shorthand signature +const dynamicRule = styleSheet.addRule({ color: 'red' }); + +const div = document.createElement('div'); +dynamicRule.applyTo(div); + +const containerRule = styleSheet.getRule('container'); +const containerJSON = containerRule.toJSON(); +const css = styleSheet.toString(); + +styleSheet.addRules({ + rule1: { + fontFamily: 'Roboto', + color: '#FFFFFF', + }, + rule2: { + fontFamily: 'Inconsolata', + fontSize: 17, + }, }); -jss.get('.demo'); +styleSheet.detach(); -jss.get(); - -jss.getAll('.demo'); - -jss.remove('.demo'); - -jss.remove(); +sharedInstance.createStyleSheet({ + container: { + background: '#000099', + } +}); diff --git a/types/jss/tsconfig.json b/types/jss/tsconfig.json index d22eb9d75e..f34791192c 100644 --- a/types/jss/tsconfig.json +++ b/types/jss/tsconfig.json @@ -2,11 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +21,4 @@ "index.d.ts", "jss-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jss/tslint.json b/types/jss/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/jss/tslint.json +++ b/types/jss/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/klaw/index.d.ts b/types/klaw/index.d.ts index 8134b728c0..7b4e586842 100644 --- a/types/klaw/index.d.ts +++ b/types/klaw/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for klaw v2.1.0 +// Type definitions for klaw v2.1.1 // Project: https://github.com/jprichardson/node-klaw // Definitions by: Matthew McEachen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -30,7 +30,7 @@ declare module "klaw" { type Event = "close" | "data" | "end" | "readable" | "error" - interface Walker { + interface Walker extends Readable { on(event: Event, listener: Function): this on(event: "close", listener: () => void): this on(event: "data", listener: (item: Item) => void): this diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index e96dfbefd8..479e38c286 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Knex.js // Project: https://github.com/tgriesser/knex -// Definitions by: Qubo , Baronfel , Pablo Rodríguez +// Definitions by: Qubo +// Baronfel +// Pablo Rodríguez +// Matt R. Wilson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -510,7 +513,7 @@ declare namespace Knex { interface Config { debug?: boolean; - client?: string; + client?: string | typeof Client; dialect?: string; version?: string; connection?: string | ConnectionConfig | MariaSqlConnectionConfig | @@ -676,6 +679,22 @@ declare namespace Knex { interface FunctionHelper { now(): Raw; } + + // + // Clients + // + + class Client extends events.EventEmitter { + constructor(config: Config); + config: Config; + dialect: string; + driverName: string; + connectionSettings: object; + + acquireRawConnection(): Promise; + destroyRawConnection(connection: any): Promise; + validateConnection(connection: any): Promise; + } } export = Knex; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index c7c99813f1..910f0ee427 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -128,6 +128,13 @@ var knex = Knex({ useNullAsDefault: true, }); +// Using custom client +class TestClient extends Knex.Client {} + +var knex = Knex({ + client: TestClient, +}); + knex('books').insert({title: 'Test'}).returning('*').toString(); // Migrations diff --git a/types/koa-conditional-get/index.d.ts b/types/koa-conditional-get/index.d.ts new file mode 100644 index 0000000000..3e4839fc88 --- /dev/null +++ b/types/koa-conditional-get/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for koa-conditional-get 2.0 +// Project: https://github.com/koajs/conditional-get#readme +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; + +declare function koaConditionalGet(): koa.Middleware; + +export = koaConditionalGet; diff --git a/types/koa-conditional-get/koa-conditional-get-tests.ts b/types/koa-conditional-get/koa-conditional-get-tests.ts new file mode 100644 index 0000000000..a197ba7398 --- /dev/null +++ b/types/koa-conditional-get/koa-conditional-get-tests.ts @@ -0,0 +1,4 @@ +import Koa = require('koa'); +import conditional = require('koa-conditional-get'); + +new Koa().use(conditional()); diff --git a/types/koa-conditional-get/tsconfig.json b/types/koa-conditional-get/tsconfig.json new file mode 100644 index 0000000000..111408f39b --- /dev/null +++ b/types/koa-conditional-get/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-conditional-get-tests.ts" + ] +} diff --git a/types/koa-conditional-get/tslint.json b/types/koa-conditional-get/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-conditional-get/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-etag/index.d.ts b/types/koa-etag/index.d.ts new file mode 100644 index 0000000000..807fd7803b --- /dev/null +++ b/types/koa-etag/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for koa-etag 3.0 +// Project: https://github.com/koajs/etag#readme +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; +import * as etag from 'etag'; + +declare function koaEtag(options?: etag.Options): koa.Middleware; + +export = koaEtag; diff --git a/types/koa-etag/koa-etag-tests.ts b/types/koa-etag/koa-etag-tests.ts new file mode 100644 index 0000000000..fa2d5515d6 --- /dev/null +++ b/types/koa-etag/koa-etag-tests.ts @@ -0,0 +1,8 @@ +import koaEtag = require('koa-etag'); +import * as Koa from 'koa'; + +new Koa().use(koaEtag()); + +new Koa().use(koaEtag({})); + +new Koa().use(koaEtag({ weak: true })); diff --git a/types/koa-etag/tsconfig.json b/types/koa-etag/tsconfig.json new file mode 100644 index 0000000000..d6b1feb52c --- /dev/null +++ b/types/koa-etag/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-etag-tests.ts" + ] +} diff --git a/types/koa-etag/tslint.json b/types/koa-etag/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-etag/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index fb7164d47d..bf3f387d31 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -15,17 +15,12 @@ interface Spec { type: string; body?: Joi.AnySchema; params?: Joi.AnySchema; - [status: number]: Joi.AnySchema; + output?: {[status: number]: Joi.AnySchema}; }; } -interface Router { - route(spec: Spec): Router; - middleware(): Koa.Middleware; -} - interface createRouter { - (): Router; + (): createRouter.Router; Joi: typeof Joi; } @@ -38,6 +33,12 @@ declare namespace createRouter { interface Context extends Koa.Context { request: Request; } + + interface Router { + routes: Spec[]; + route(spec: Spec|Spec[]): Router; + middleware(): Koa.Middleware; + } } declare var createRouter: createRouter; diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index e36ce95746..76a392bdec 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -38,7 +38,9 @@ const spec4 = { path: '/user', validate: { type: 'json', - 201: Joi.object(), + output: { + 201: Joi.object(), + } }, handler: (ctx: router.Context) => { ctx.status = 201; @@ -69,3 +71,7 @@ const spec6 = { }; router().route(spec6); + +router().route([spec1, spec2, spec3]); + +router().routes.map(({ path }) => path); diff --git a/types/koa-send/index.d.ts b/types/koa-send/index.d.ts index a15f5b688d..65228c9981 100644 --- a/types/koa-send/index.d.ts +++ b/types/koa-send/index.d.ts @@ -1,24 +1,46 @@ -// Type definitions for koa-send v3.3 +// Type definitions for koa-send 4.1 // Project: https://github.com/koajs/send // Definitions by: Peter Safranek +// Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from 'koa'; +import { + Context, +} from "koa"; -interface ISendOptions { - root?: string; - index?: string; - maxAge?: number; - hidden?: boolean; - format?: boolean; - gzip?: boolean; - setHeaders?: Function; - extensions?: string[]; +import { + Stats, +} from "fs"; + +declare function send(ctx: Context, path: string, opts?: send.SendOptions): Promise; + +declare namespace send { + type SetHeaders = (res: Context["res"], path: string, stats: Stats) => any; + + interface SendOptions { + /** Browser cache max-age in milliseconds. (defaults to 0) */ + maxage?: number; + maxAge?: SendOptions["maxage"]; + /** Tell the browser the resource is immutable and can be cached indefinitely. (defaults to false) */ + immutable?: boolean; + /** Allow transfer of hidden files. (defaults to false) */ + hidden?: boolean; + /** Root directory to restrict file access. (defaults to '') */ + root?: string; + /** Name of the index file to serve automatically when visiting the root location. (defaults to none) */ + index?: string; + /** Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. (defaults to true). */ + gzip?: boolean; + /** Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists. (defaults to true). */ + brotli?: boolean; + /** If not false (defaults to true), format the path to serve static file servers and not require a trailing slash for directories, so that you can do both /directory and /directory/. */ + format?: boolean; + /** Function to set custom headers on response. */ + setHeaders?: SetHeaders; + /** Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false) */ + extensions?: string[] | false; + } } -declare function send(ctx: Koa.Context, path: string, opts?: ISendOptions): Promise; - -declare namespace send {} - export = send; diff --git a/types/koa-send/koa-send-tests.ts b/types/koa-send/koa-send-tests.ts index 88a6f16abb..a3b136ea9a 100644 --- a/types/koa-send/koa-send-tests.ts +++ b/types/koa-send/koa-send-tests.ts @@ -1,4 +1,3 @@ - import * as Koa from 'koa'; import * as send from 'koa-send'; @@ -16,7 +15,7 @@ app.use(async (ctx: Koa.Context) => { hidden: true, format: true, gzip: true, - setHeaders: () => {}, + setHeaders: () => { }, extensions: ['shemp'], }); }); diff --git a/types/koa-send/tslint.json b/types/koa-send/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/koa-send/tslint.json +++ b/types/koa-send/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/koa-sslify/index.d.ts b/types/koa-sslify/index.d.ts new file mode 100644 index 0000000000..0bf6c0a1ff --- /dev/null +++ b/types/koa-sslify/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for koa-sslify 2.1 +// Project: https://github.com/turboMaCk/koa-sslify#readme +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; + +declare namespace sslify { + interface Options { + trustProtoHeader?: boolean; + trustAzureHeader?: boolean; + port?: number; + hostname?: string; + ignoreUrl?: boolean; + temporary?: boolean; + redirectMethods?: string[]; + internalRedirectMethods?: string[]; + specCompliantDisallow?: boolean; + } +} + +declare function sslify(options: sslify.Options): koa.Middleware; + +export = sslify; diff --git a/types/koa-sslify/koa-sslify-tests.ts b/types/koa-sslify/koa-sslify-tests.ts new file mode 100644 index 0000000000..c8dae23bb4 --- /dev/null +++ b/types/koa-sslify/koa-sslify-tests.ts @@ -0,0 +1,40 @@ +import Koa = require('koa'); +import sslify = require('koa-sslify'); + +new Koa().use(sslify({})); + +new Koa().use(sslify({ + trustAzureHeader: true, +})); + +new Koa().use(sslify({ + trustProtoHeader: true, +})); + +new Koa().use(sslify({ + specCompliantDisallow: true, +})); + +new Koa().use(sslify({ + port: 1234, +})); + +new Koa().use(sslify({ + hostname: 'my-host', +})); + +new Koa().use(sslify({ + temporary: false, +})); + +new Koa().use(sslify({ + internalRedirectMethods: ['GET'], +})); + +new Koa().use(sslify({ + redirectMethods: ['GET'], +})); + +new Koa().use(sslify({ + ignoreUrl: true, +})); diff --git a/types/koa-sslify/tsconfig.json b/types/koa-sslify/tsconfig.json new file mode 100644 index 0000000000..64615e2ab9 --- /dev/null +++ b/types/koa-sslify/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-sslify-tests.ts" + ] +} diff --git a/types/koa-sslify/tslint.json b/types/koa-sslify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-sslify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/left-pad/index.d.ts b/types/left-pad/index.d.ts deleted file mode 100644 index 1296c4fe02..0000000000 --- a/types/left-pad/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for left-pad 1.1 -// Project: https://github.com/stevemao/left-pad -// Definitions by: Zlatko Andonovski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function leftPad(str: string|number, len: number, ch?: string|number): string; - -export = leftPad; diff --git a/types/left-pad/left-pad-tests.ts b/types/left-pad/left-pad-tests.ts deleted file mode 100644 index a3749feb16..0000000000 --- a/types/left-pad/left-pad-tests.ts +++ /dev/null @@ -1,15 +0,0 @@ -import leftPad = require("left-pad"); - -// Tests based on examples in https://github.com/stevemao/left-pad#usage - -leftPad("foo", 5); -// => " foo" - -leftPad("foobar", 6); -// => "foobar"' - -leftPad(1, 2, "0"); -// => "01" - -leftPad(17, 5, 0); -// => "00017" diff --git a/types/less2sass/index.d.ts b/types/less2sass/index.d.ts new file mode 100644 index 0000000000..25848117f2 --- /dev/null +++ b/types/less2sass/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for less2sass 1.0 +// Project: https://github.com/ekryski/less2sass +// Definitions by: William Lohan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Less2Sass { + convert(file: string): string; +} + +declare const less2sass: Less2Sass; +export = less2sass; diff --git a/types/less2sass/less2sass-tests.ts b/types/less2sass/less2sass-tests.ts new file mode 100644 index 0000000000..578b731887 --- /dev/null +++ b/types/less2sass/less2sass-tests.ts @@ -0,0 +1,4 @@ +import * as less2sass from 'less2sass'; + +let scss: string; +scss = less2sass.convert('@myColor: #f938ab; .myClass { color: @myColor; }'); diff --git a/types/less2sass/tsconfig.json b/types/less2sass/tsconfig.json new file mode 100644 index 0000000000..e70848dca8 --- /dev/null +++ b/types/less2sass/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "less2sass-tests.ts" + ] +} diff --git a/types/less2sass/tslint.json b/types/less2sass/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/less2sass/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/loadware/index.d.ts b/types/loadware/index.d.ts new file mode 100644 index 0000000000..7c45225d44 --- /dev/null +++ b/types/loadware/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for loadware 2.0 +// Project: https://github.com/franciscop/loadware +// Definitions by: A.J.J. Lyman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// tslint:disable-next-line:ban-types +type AnyFunction = Function; + +declare function loadware(...loadable: Array>): ReadonlyArray; + +declare namespace loadware { + type Loadable = string | F | RecursiveLoadable; + interface RecursiveLoadable extends Array> { } +} + +export = loadware; diff --git a/types/loadware/loadware-tests.ts b/types/loadware/loadware-tests.ts new file mode 100644 index 0000000000..630d3fd351 --- /dev/null +++ b/types/loadware/loadware-tests.ts @@ -0,0 +1,20 @@ +import loadware = require("loadware"); + +interface Context { __ContextMarker: never; } +interface Response { __ResponseMarker: never; } +type Middleware = (ctx: Context) => void; + +loadware( + (_: Context) => {}, + [ + (_: Context) => {}, + 'loadware/requires-strings' + ], + [ + [ + [ + (_: Context) => {} + ] + ] + ] +); diff --git a/types/left-pad/tsconfig.json b/types/loadware/tsconfig.json similarity index 94% rename from types/left-pad/tsconfig.json rename to types/loadware/tsconfig.json index 383ebedf76..5921615bf8 100644 --- a/types/left-pad/tsconfig.json +++ b/types/loadware/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "left-pad-tests.ts" + "loadware-tests.ts" ] } \ No newline at end of file diff --git a/types/loadware/tslint.json b/types/loadware/tslint.json new file mode 100644 index 0000000000..6746359dda --- /dev/null +++ b/types/loadware/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 76c3c7a115..07c9e1227b 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -11585,6 +11585,10 @@ declare namespace _ { lower: number, upper: number ): number; + clamp( + number: number, + upper: number + ): number; } interface LoDashImplicitWrapper { @@ -11595,6 +11599,9 @@ declare namespace _ { lower: number, upper: number ): number; + clamp( + upper: number + ): number; } interface LoDashExplicitWrapper { @@ -11605,6 +11612,9 @@ declare namespace _ { lower: number, upper: number ): LoDashExplicitWrapper; + clamp( + upper: number + ): LoDashExplicitWrapper; } //_.inRange diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index a4c01223ea..49c705827f 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -9802,8 +9802,10 @@ namespace TestInClamp { let result: number; result = _.clamp(3, 2, 4); + result = _.clamp(3, 4); result = _(3).clamp(2, 4); + result = _(3).clamp(4); } { diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index 514a8fa578..e16851b52b 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -626,6 +626,19 @@ declare namespace lunr { */ function stemmer(token: Token): Token; + /** + * lunr.generateStopWordFilter builds a stopWordFilter function from the provided + * list of stop words. + * + * The built in lunr.stopWordFilter is built using this generator and can be used + * to generate custom stopWordFilters for applications or non English languages. + * + * @param stopWords - The list of stop words + * @see lunr.Pipeline + * @see lunr.stopWordFilter + */ + function generateStopWordFilter(stopWords: string[]): PipelineFunction; + /** * lunr.stopWordFilter is an English language stop word list filter, any words * contained in the list will not be passed through the filter. @@ -784,7 +797,7 @@ declare namespace lunr { * * @see lunr.tokenizer */ - const separator: RegExp; + let separator: RegExp; } /** diff --git a/types/moment-business-time/index.d.ts b/types/moment-business-time/index.d.ts new file mode 100644 index 0000000000..dc4022f161 --- /dev/null +++ b/types/moment-business-time/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for moment-business-time 0.7 +// Project: https://github.com/lennym/moment-business-time +// Definitions by: Tomasz Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ On this line, import the module which this module adds to */ +import * as moment from 'moment'; + +/*~ Here, declare the same module as the one you imported above */ +declare module 'moment' { + interface Moment { + nextWorkingDay: () => Moment; + nextWorkingTime: () => Moment; + + lastWorkingDay: () => Moment; + lastWorkingTime: () => Moment; + + addWorkingTime: (...args: Array) => Moment; + subtractWorkingTime: (...args: Array) => Moment; + + workingDiff: (moment: Moment, unit: unitOfTime.Base, fractions?: boolean) => Moment; + + isWorkingDay: () => boolean; + isWorkingTime: () => boolean; + } + + interface WorkingHoursMap { + 0: string[] | null; + 1: string[] | null; + 2: string[] | null; + 3: string[] | null; + 4: string[] | null; + 5: string[] | null; + 6: string[] | null; + } + + interface LocaleSpecification { + workinghours?: WorkingHoursMap; + holidays?: string[]; + } +} diff --git a/types/moment-business-time/moment-business-time-tests.ts b/types/moment-business-time/moment-business-time-tests.ts new file mode 100644 index 0000000000..79f25a720a --- /dev/null +++ b/types/moment-business-time/moment-business-time-tests.ts @@ -0,0 +1,56 @@ +import * as moment from 'moment'; +import 'moment-business-time'; + +moment('2015-02-28T10:00:00Z').nextWorkingDay(); +moment('2015-02-28T20:00:00Z').nextWorkingDay(); +moment('2015-02-28T10:00:00Z').nextWorkingTime(); +moment('2015-02-28T20:00:00Z').nextWorkingTime(); +moment('2015-02-28T10:00:00Z').lastWorkingDay(); +// Fri Feb 27 2015 10:00:00 GMT+0000 +moment('2015-02-28T20:00:00Z').lastWorkingDay(); +// Fri Feb 27 2015 20:00:00 GMT+0000 +moment('2015-02-27T10:00:00Z').addWorkingTime(5, 'hours'); +// Fri Feb 27 2015 15:00:00 GMT+0000 +moment('2015-02-28T10:00:00Z').addWorkingTime(5, 'hours'); +// Mon Mar 02 2015 14:00:00 GMT+0000 +moment('2015-02-27T10:00:00Z').addWorkingTime(5, 'hours', 30, 'minutes'); +// Fri Feb 27 2015 15:30:00 GMT+0000 +moment('2015-02-27T16:00:00Z').subtractWorkingTime(5, 'hours'); +// Fri Feb 27 2015 11:00:00 GMT+0000 +moment('2015-02-28T16:00:00Z').subtractWorkingTime(5, 'hours'); +// Fri Feb 27 2015 12:00:00 GMT+0000 +moment('2015-02-27T16:00:00Z').subtractWorkingTime(5, 'hours', 30, 'minutes'); +// Fri Feb 27 2015 10:30:00 GMT+0000 +moment('2015-02-27T16:30:00Z').workingDiff(moment('2015-02-26T12:00:00Z'), 'hours'); +// 12 +moment('2015-02-27T16:30:00Z').workingDiff(moment('2015-02-26T12:00:00Z'), 'hours', true); +// 12.5 +// set opening time to 09:30 and close early on Wednesdays +moment.updateLocale('en', { + workinghours: { + 0: null, + 1: ['09:30:00', '17:00:00'], + 2: ['09:30:00', '17:00:00'], + 3: ['09:30:00', '13:00:00'], + 4: ['09:30:00', '17:00:00'], + 5: ['09:30:00', '17:00:00'], + 6: null + } +}); +moment('2015-02-25T15:00:00Z').isWorkingTime(); // false +moment('2015-02-23T09:00:00Z').isWorkingTime(); // false +moment.updateLocale('en', { + holidays: [ + '2015-05-04' + ] +}); +moment('2015-05-04T09:30:00Z').isWorkingDay(); // false +moment.updateLocale('en', { + holidays: [ + '*-12-25' + ] +}); +moment('2015-12-25T16:30:00Z').isWorkingDay(); // false +moment('2016-12-25T16:30:00Z').isWorkingDay(); // false +moment('2017-12-25T16:30:00Z').isWorkingDay(); // false +moment('2018-12-25T16:30:00Z').isWorkingDay(); // false diff --git a/types/moment-business-time/tsconfig.json b/types/moment-business-time/tsconfig.json new file mode 100644 index 0000000000..c1212caa2f --- /dev/null +++ b/types/moment-business-time/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "moment-business-time-tests.ts" + ] +} diff --git a/types/moment-business-time/tslint.json b/types/moment-business-time/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-business-time/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 32bc523d38..0c7b90edfd 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -5,7 +5,7 @@ // Gady Piazza // Jason Dreyzehner // Gaurav Lahoti -// Mariano Cortesi +// Mariano Cortesi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -22,7 +22,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp } from 'bson'; +export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index f86dea4f8a..7eb768f3c8 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -366,11 +366,11 @@ declare module "mongoose" { auth?: any; /** Use ssl connection (needs to have a mongod server with ssl support) (default: true) */ ssl?: boolean; - /** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */ - sslValidate?: object; - /** Reconnect on error (default: true) */ - poolSize?: number; /** Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) */ + sslValidate?: object; + /** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */ + poolSize?: number; + /** Reconnect on error (default: true) */ autoReconnect?: boolean; /** TCP KeepAlive on the socket with a X ms delay before start (default: 0). */ keepAlive?: number; @@ -380,10 +380,13 @@ declare module "mongoose" { socketTimeoutMS?: number; /** If the database authentication is dependent on another databaseName. */ authSource?: string; - /** Attempt to reconnect #times (default: 30) */ - retries?: number; + /** If you're connected to a single server or mongos proxy (as opposed to a replica set), + * the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries + * times, and give up afterward. When the driver gives up, the mongoose connection emits a + * reconnectFailed event. (default: 30) */ + reconnectTries?: number; /** Will wait # milliseconds between retries (default: 1000) */ - reconnectWait?: number; + reconnectInterval?: number; /** The name of the replicaset to connect to. */ replicaSet?: string; /** The current value of the parameter native_parser */ @@ -400,6 +403,14 @@ declare module "mongoose" { readPreference?: string; /** An object representing read preference tags, see: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */ readPreferencetags?: object; + /** Triggers the server instance to call ismaster (default: true). */ + monitoring?: boolean; + /** The interval of calling ismaster when monitoring is enabled (default: 10000). */ + haInterval?: number; + /** Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit (default: false). */ + domainsEnabled?: boolean; + /** How long driver keeps waiting for servers to come back up (default: Number.MAX_VALUE) */ + bufferMaxEntries?: number; // TODO safe?: any; diff --git a/types/nes/client.d.ts b/types/nes/client.d.ts index 8314894683..5d348b267e 100644 --- a/types/nes/client.d.ts +++ b/types/nes/client.d.ts @@ -1,6 +1,7 @@ -// Type definitions for nes 6.4.2 +// Type definitions for nes 7.0.0 // Project: https://github.com/hapijs/nes // Definitions by: Ivo Stratev +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Client { @@ -9,14 +10,14 @@ declare class Client { onConnect: () => void; onDisconnect: () => void; onUpdate: (message: any) => void; - connect(options: Client.ClientConnectOptions, callback: (err?: any) => void): void; - connect(callback: (err?: any) => void): void; - disconnect(): void; + connect(options: Client.ClientConnectOptions): Promise; + connect(): Promise; + disconnect(): Promise; id: any; // can be `null | number` but also the "socket" value from websocket message data. - request(options: string | Client.ClientRequestOptions, callback: (err: any, payload: any, statusCode?: number, headers?: Object) => void): void; - message(message: any, callback: (err: any, message: any) => void): void; - subscribe(path: string, handler: Client.Handler, callback: (err?: any) => void): void; - unsubscribe(path: string, handler: Client.Handler, callback: (err?: any) => void): void; + request(options: string | Client.ClientRequestOptions): Promise; + message(message: any): Promise; + subscribe(path: string, handler: Client.Handler): Promise; + unsubscribe(path: string, handler: Client.Handler): Promise; subscriptions(): string[]; overrideReconnectionAuth(auth: any): void; } diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index a6ed90a7b7..c4d26ecda0 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for nes 6.2.1 +// Type definitions for nes 7.0.0 // Project: https://github.com/hapijs/nes // Definitions by: Ivo Stratev +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -62,12 +63,12 @@ declare module nes { index?: boolean; } - export type ServerOnSubscribeWithParams = (socket: Socket, path: string, params: any, next: (err?: any) => void) => void; - export type ServerOnSubscribeWithoutParams = (socket: Socket, path: string, next: (err?: any) => void) => void; + export type ServerOnSubscribeWithParams = (socket: Socket, path: string, params: any) => Promise; + export type ServerOnSubscribeWithoutParams = (socket: Socket, path: string) => Promise; export type ServerOnSubscribe = ServerOnSubscribeWithParams | ServerOnSubscribeWithoutParams; - export type ServerOnUnSubscribeWithParams = (socket: Socket, path: string, params: any, next: () => void) => void; - export type ServerOnUnSubscribeWithoutParams = (socket: Socket, path: string, next: () => void) => void; + export type ServerOnUnSubscribeWithParams = (socket: Socket, path: string, params: any) => void; + export type ServerOnUnSubscribeWithoutParams = (socket: Socket, path: string) => void; export type ServerOnUnSubscribe = ServerOnUnSubscribeWithParams | ServerOnUnSubscribeWithoutParams; interface ServerSubscriptionOptions { @@ -91,10 +92,10 @@ declare module nes { id: string; app: Object; auth: nes.SocketAuthObject; - disconnect(callback?: () => void): void; - send(message: any, callback?: (err?: any) => void): void; - publish(path: string, message: any, callback?: (err?: any) => void): void; - revoke(path: string, message: any, callback?: (err?: any) => void): void; + disconnect(): Promise; + send(message: any): Promise; + publish(path: string, message: any): Promise; + revoke(path: string, message: any): Promise; } /** diff --git a/types/nes/test/broadcast-client.ts b/types/nes/test/broadcast-client.ts index 4c94b8c575..5563a202d3 100644 --- a/types/nes/test/broadcast-client.ts +++ b/types/nes/test/broadcast-client.ts @@ -3,7 +3,7 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { client.onUpdate = function (update) { @@ -16,7 +16,7 @@ client.connect(function (err) { import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { client.onUpdate = function (update) { diff --git a/types/nes/test/broadcast-server.ts b/types/nes/test/broadcast-server.ts index dcfcb3400e..6ef8f7aafa 100644 --- a/types/nes/test/broadcast-server.ts +++ b/types/nes/test/broadcast-server.ts @@ -4,11 +4,10 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register(Nes, function (err) { +server.register(Nes).then(() => { - server.start(function (err) { + return server.start().then(() => { server.broadcast('welcome!'); }); diff --git a/types/nes/test/nes-tests.ts b/types/nes/test/nes-tests.ts index 90afe68f3e..85cff1e208 100644 --- a/types/nes/test/nes-tests.ts +++ b/types/nes/test/nes-tests.ts @@ -2,66 +2,55 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server: Hapi.Server = new Hapi.Server(); -server.connection({port: 8080}); -server.register(Nes, (regErr) => { - if(regErr) { - console.log('register err'); - console.log(regErr); - } else { - // No longer need to cast to Nes.Server as Hapi.Server has been modified directly. - // let wsServer: Nes.Server = server as Nes.Server; - let wsServer: Hapi.Server = server; - wsServer.subscription('/item/{id}'); - wsServer.route( { - method: 'GET', - path: '/test', - config: { - handler: (request, reply) => { - reply({test: 'passes ' + request.socket.id}); - } +server.register(Nes).then(() => { + // No longer need to cast to Nes.Server as Hapi.Server has been modified directly. + // let wsServer: Nes.Server = server as Nes.Server; + let wsServer: Hapi.Server = server; + wsServer.subscription('/item/{id}'); + wsServer.route( { + method: 'GET', + path: '/test', + config: { + handler: (request, h) => { + return {test: 'passes ' + request.socket.id}; } - }); - wsServer.start((err: any) => { - if(err) { - console.log('start err'); - console.log(err); - } else { - setTimeout(() => { - wsServer.publish('/item/5', { id: 5, status: 'complete' }); - wsServer.publish('/item/6', { id: 6, status: 'initial' }); - }, 100); - } - }); - } + } + }); + wsServer.start().then(() => { + setTimeout(() => { + wsServer.publish('/item/5', { id: 5, status: 'complete' }); + wsServer.publish('/item/6', { id: 6, status: 'initial' }); + }, 100); + }).catch((err) => { + console.log('start err'); + console.log(err); + }); +}).catch((regErr: any) => { + console.log('register err'); + console.log(regErr); }); let options: Nes.ClientConnectOptions = {delay: 3}; -let wsClient: Nes.Client = new Nes.Client('ws://localhost:8080', options); -wsClient.connect((err: any) => { - if(err) { - console.log('start err'); - console.log(err); - } else { - wsClient.subscribe('/item/5', (update) => { - wsClient.request('/test', (reqErr, payload, statusCode) => { - if(reqErr) { - console.log('request err'); - console.log(reqErr); - } else { - console.log(update); - console.log(payload); - if(payload.test === 'passes') { - process.exit(0); - } - } - }) - }, (subErr) => { - if(subErr) { - console.log('subscribe err'); - console.log(subErr); +let wsClient: Nes.Client = new Nes.Client('ws://localhost', options); +wsClient.connect().then(() => { + wsClient.subscribe('/item/5', (update) => { + wsClient.request('/test').then(({ payload, statusCode }) => { + console.log(update); + console.log(payload); + if(payload.test === 'passes') { + process.exit(0); } - }); - } + }).catch((reqErr: any) => { + console.log('request err'); + console.log(reqErr); + }) + }).catch((subErr: any) => { + console.log('subscribe err'); + console.log(subErr); + }); +}).catch((err: any) => { + console.log('start err'); + console.log(err); }); diff --git a/types/nes/test/route-authentication-client.ts b/types/nes/test/route-authentication-client.ts index fe57eb8d56..f1eb8b9659 100644 --- a/types/nes/test/route-authentication-client.ts +++ b/types/nes/test/route-authentication-client.ts @@ -3,12 +3,9 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'Hello John Doe' - }); + client.request('hello'); }); // Added in addition to nes doc example code @@ -16,10 +13,7 @@ client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'Hello John Doe' - }); + return client.request('hello'); }); diff --git a/types/nes/test/route-authentication-server.ts b/types/nes/test/route-authentication-server.ts index 5b4634d77d..2080f04ef4 100644 --- a/types/nes/test/route-authentication-server.ts +++ b/types/nes/test/route-authentication-server.ts @@ -8,7 +8,7 @@ import Nes = require('nes'); var server = new Hapi.Server(); server.connection(); -server.register([Basic, Nes], function (err) { +server.register([Basic, Nes]).then(() => { // Set up HTTP Basic authentication @@ -28,20 +28,20 @@ server.register([Basic, Nes], function (err) { } }; - var validate: Basic.ValidateFunc = function (request, username, password, callback) { + var validate: Basic.Validate = async (request, username, password, h) => { var user = users[username]; if (!user) { - return callback(null, false); + return { credentials: null, isValid: false }; } - Bcrypt.compare(password, user.password, function (err, isValid) { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name }); - }); + return { isValid, credentials: { id: user.id, name: user.name } }; }; - server.auth.strategy('simple', 'basic', 'required', { validateFunc: validate }); + server.auth.strategy('simple', 'basic', { validateFunc: validate }); + server.auth.default('simple'); // Configure route with authentication @@ -50,12 +50,12 @@ server.register([Basic, Nes], function (err) { path: '/h', config: { id: 'hello', - handler: function (request, reply) { + handler: function (request, h) { - return reply('Hello ' + request.auth.credentials.name); + return 'Hello ' + request.auth.credentials.name; } } }); - server.start(function (err) { /* ... */ }); + return server.start(); }); diff --git a/types/nes/test/route-invocation-client.ts b/types/nes/test/route-invocation-client.ts index 7b144e3a9c..34c40fe151 100644 --- a/types/nes/test/route-invocation-client.ts +++ b/types/nes/test/route-invocation-client.ts @@ -3,12 +3,9 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'world!' - }); + return client.request('hello'); }); // Added in addition to nes doc example code @@ -16,10 +13,7 @@ client.connect(function (err) { import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'world!' - }); + return client.request('hello'); }); diff --git a/types/nes/test/route-invocation-server.ts b/types/nes/test/route-invocation-server.ts index c32780baa9..d6893495c9 100644 --- a/types/nes/test/route-invocation-server.ts +++ b/types/nes/test/route-invocation-server.ts @@ -4,21 +4,20 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register(Nes, function (err) { +server.register(Nes).then(() => { server.route({ method: 'GET', path: '/h', config: { id: 'hello', - handler: function (request, reply) { + handler: (request, h) => { - return reply('world!'); + return 'world!'; } } }); - server.start(function (err) { /* ... */ }); + return server.start(); }); diff --git a/types/nes/test/socket.ts b/types/nes/test/socket.ts index 7f7617d462..029dbb1d2f 100644 --- a/types/nes/test/socket.ts +++ b/types/nes/test/socket.ts @@ -4,13 +4,11 @@ import Nes = require('nes'); const socket: Nes.Socket = undefined; -const cb = () => { }; -socket.disconnect(cb); +socket.disconnect(); const s: string = socket.id; const o: Object = socket.app; const auth: Nes.SocketAuthObject = socket.auth; -const cb2 = (err?: any) => { }; -socket.send('message', (err?: any) => { }); -socket.publish('path', 'message', cb2); -socket.revoke('path', 'message', cb2); +socket.send('message'); +socket.publish('path', 'message'); +socket.revoke('path', 'message'); diff --git a/types/nes/test/subscription-filter-client.ts b/types/nes/test/subscription-filter-client.ts index 3f8d3ffb8b..05253539a4 100644 --- a/types/nes/test/subscription-filter-client.ts +++ b/types/nes/test/subscription-filter-client.ts @@ -6,15 +6,15 @@ var client = new Nes.Client('ws://localhost'); // Authenticate as 'john' -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - var handler: Nes.Handler = function (err, update) { + var handler: Nes.Handler = (update) => { // First publish is not received (filtered due to updater key) // update -> { id: 6, status: 'initial', updater: 'steve' } }; - client.subscribe('/items', handler, function (err) { }); + return client.subscribe('/items', handler); }); // Added in addition to nes doc example code @@ -25,13 +25,13 @@ var client = new NesClient('ws://localhost'); // Authenticate as 'john' -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - var handler: NesClient.Handler = function (err, update) { + var handler: NesClient.Handler = (update) => { // First publish is not received (filtered due to updater key) // update -> { id: 6, status: 'initial', updater: 'steve' } }; - client.subscribe('/items', handler, function (err) { }); + return client.subscribe('/items', handler); }); diff --git a/types/nes/test/subscription-filter-server.ts b/types/nes/test/subscription-filter-server.ts index be2dda8d7f..7a63abf151 100644 --- a/types/nes/test/subscription-filter-server.ts +++ b/types/nes/test/subscription-filter-server.ts @@ -6,9 +6,8 @@ import Bcrypt = require('bcrypt'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register([Basic, Nes], function (err) { +server.register([Basic, Nes]).then(() => { // Set up HTTP Basic authentication @@ -28,31 +27,31 @@ server.register([Basic, Nes], function (err) { } }; - var validate: Basic.ValidateFunc = function (request, username, password, callback) { + var validate: Basic.Validate = async (request, username, password, h) => { var user = users[username]; if (!user) { - return callback(null, false); + return { credentials: null, isValid: false }; } - Bcrypt.compare(password, user.password, function (err, isValid) { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name, username: user.username }); - }); + return { isValid, credentials: { id: user.id, name: user.name, username: user.username } }; }; - server.auth.strategy('simple', 'basic', 'required', { validateFunc: validate }); + server.auth.strategy('simple', 'basic', { validate }); + server.auth.default('simple') // Set up subscription server.subscription('/items', { - filter: function (path, message, options, next) { + filter: (path, message, options) => { - return next(message.updater !== options.credentials.username); + return message.updater !== options.credentials.username; } }); - server.start(function (err) { + server.start().then(() => { server.publish('/items', { id: 5, status: 'complete', updater: 'john' }); server.publish('/items', { id: 6, status: 'initial', updater: 'steve' }); diff --git a/types/nes/test/subscriptions-client.ts b/types/nes/test/subscriptions-client.ts index a9ac55fc6d..9f6150f90c 100644 --- a/types/nes/test/subscriptions-client.ts +++ b/types/nes/test/subscriptions-client.ts @@ -3,15 +3,15 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect(function (err) { + client.connect().then(() => {; - var handler: Nes.Handler = function (update, flags) { + var handler: Nes.Handler = (update, flags) => { // update -> { id: 5, status: 'complete' } // Second publish is not received (doesn't match) }; - client.subscribe('/item/5', handler, function (err) { }); + return client.subscribe('/item/5', handler); }); // Added in addition to nes doc example code @@ -19,13 +19,13 @@ client.connect(function (err) { import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { - var handler: NesClient.Handler = function (update, flags) { + var handler: NesClient.Handler = (update, flags) => { // update -> { id: 5, status: 'complete' } // Second publish is not received (doesn't match) }; - client.subscribe('/item/5', handler, function (err) { }); + return client.subscribe('/item/5', handler); }); diff --git a/types/nes/test/subscriptions-server.ts b/types/nes/test/subscriptions-server.ts index 23212f21ea..1280f2afd1 100644 --- a/types/nes/test/subscriptions-server.ts +++ b/types/nes/test/subscriptions-server.ts @@ -4,15 +4,14 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register(Nes, function (err) { +server.register(Nes).then(() =>{; server.subscription('/item/{id}'); - server.start(function (err) { + return server.start().then(() => { - server.publish('/item/5', { id: 5, status: 'complete' }); - server.publish('/item/6', { id: 6, status: 'initial' }); + server.publish('/item/5', {id: 5, status: 'complete'}); + server.publish('/item/6', {id: 6, status: 'initial'}); }); -}); +}) diff --git a/types/ng-file-upload/index.d.ts b/types/ng-file-upload/index.d.ts index 85a055772b..d17327dc7c 100644 --- a/types/ng-file-upload/index.d.ts +++ b/types/ng-file-upload/index.d.ts @@ -253,6 +253,10 @@ declare module 'angular' { * @type {string} */ url: string; + /** + * Add which HTTP method to use: 'POST' or 'PUT' (html5) + */ + method: string; /** * This is to accommodate server implementations expecting nested data object keys in .key or [key] format. * Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file diff --git a/types/node-rsa/index.d.ts b/types/node-rsa/index.d.ts index faafdf7d24..63d569378d 100644 --- a/types/node-rsa/index.d.ts +++ b/types/node-rsa/index.d.ts @@ -122,7 +122,7 @@ declare namespace NodeRSA { type Encoding = | 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' - | 'base64' | 'hex' | 'binary'; + | 'base64' | 'hex' | 'binary' | 'buffer'; interface KeyComponents { n: Buffer; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 61fd375e6f..9980eee71d 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -15,6 +15,7 @@ // Alvis HT Tang // Oliver Joseph Ash // Sebastian Silbermann +// Hannes Magnusson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -44,8 +45,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -104,8 +115,8 @@ declare namespace setImmediate { declare function clearImmediate(immediateId: any): void; // TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -/* tslint:disable:callable-types */ interface NodeRequireFunction { +/* tslint:disable-next-line:callable-types */ (id: string): any; } @@ -310,6 +321,80 @@ declare namespace NodeJS { new(stdout: WritableStream, stderr?: WritableStream): Console; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; @@ -801,8 +886,10 @@ declare module "querystring" { decodeURIComponent?: Function; } + interface ParsedUrlQuery { [key: string]: string | string[]; } + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): { [key: string]: string | string[] }; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; export function escape(str: string): string; export function unescape(str: string): string; @@ -1664,16 +1751,8 @@ declare module "https" { servername?: string; } - export interface AgentOptions extends http.AgentOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; + export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { rejectUnauthorized?: boolean; - serverName?: string; - secureProtocol?: string; maxCachedSessions?: number; } @@ -2221,7 +2300,9 @@ declare module "child_process" { } declare module "url" { - export interface UrlObject { + import { ParsedUrlQuery } from 'querystring'; + + export interface UrlObjectCommon { auth?: string; hash?: string; host?: string; @@ -2229,16 +2310,21 @@ declare module "url" { href?: string; path?: string; pathname?: string; - port?: string | number; protocol?: string; - query?: string | null | { [key: string]: string | string[] }; search?: string; slashes?: boolean; } - export interface Url extends UrlObject { + // Input to `url.format` + export interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + export interface Url extends UrlObjectCommon { port?: string; - query?: any; + query?: string | null | ParsedUrlQuery; } export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; @@ -4867,25 +4953,19 @@ declare module "tls" { secureOptions?: number; } - export interface ConnectionOptions { + export interface ConnectionOptions extends SecureContextOptions { host?: string; port?: number; - socket?: net.Socket; - pfx?: string | Buffer; - key?: string | string[] | Buffer | Buffer[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | Buffer | Array; - rejectUnauthorized?: boolean; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true NPNProtocols?: Array; - servername?: string; - path?: string; ALPNProtocols?: Array; - checkServerIdentity?: (servername: string, cert: string | Buffer | Array) => any; - secureProtocol?: string; - secureContext?: Object; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension session?: Buffer; minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() lookup?: net.LookupFunction; } @@ -4970,20 +5050,33 @@ declare module "tls" { } export interface SecureContextOptions { - pfx?: string | Buffer; - key?: string | Buffer; + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer; - crl?: string | string[]; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; ciphers?: string; honorCipherOrder?: boolean; + ecdhCurve?: string; + crl?: string | Buffer | Array; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; } export interface SecureContext { context: any; } + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + export function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; @@ -5877,133 +5970,6 @@ declare module "console" { export = console; } -/** - * _debugger module is not documented. - * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js - */ -declare module "_debugger" { - export interface Packet { - raw: string; - headers: string[]; - body: Message; - } - - export interface Message { - seq: number; - type: string; - } - - export interface RequestInfo { - command: string; - arguments: any; - } - - export interface Request extends Message, RequestInfo { - } - - export interface Event extends Message { - event: string; - body?: any; - } - - export interface Response extends Message { - request_seq: number; - success: boolean; - /** Contains error message if success === false. */ - message?: string; - /** Contains message body if success === true. */ - body?: any; - } - - export interface BreakpointMessageBody { - type: string; - target: number; - line: number; - } - - export class Protocol { - res: Packet; - state: string; - execute(data: string): void; - serialize(rq: Request): string; - onResponse: (pkt: Packet) => void; - } - - export var NO_FRAME: number; - export var port: number; - - export interface ScriptDesc { - name: string; - id: number; - isNative?: boolean; - handle?: number; - type: string; - lineOffset?: number; - columnOffset?: number; - lineCount?: number; - } - - export interface Breakpoint { - id: number; - scriptId: number; - script: ScriptDesc; - line: number; - condition?: string; - scriptReq?: string; - } - - export interface RequestHandler { - (err: boolean, body: Message, res: Packet): void; - request_seq?: number; - } - - export interface ResponseBodyHandler { - (err: boolean, body?: any): void; - request_seq?: number; - } - - export interface ExceptionInfo { - text: string; - } - - export interface BreakResponse { - script?: ScriptDesc; - exception?: ExceptionInfo; - sourceLine: number; - sourceLineText: string; - sourceColumn: number; - } - - export function SourceInfo(body: BreakResponse): string; - - export interface ClientInstance extends NodeJS.EventEmitter { - protocol: Protocol; - scripts: ScriptDesc[]; - handles: ScriptDesc[]; - breakpoints: Breakpoint[]; - currentSourceLine: number; - currentSourceColumn: number; - currentSourceLineText: string; - currentFrame: number; - currentScript: string; - - connect(port: number, host: string): void; - req(req: any, cb: RequestHandler): void; - reqFrameEval(code: string, frame: number, cb: RequestHandler): void; - mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; - setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; - clearBreakpoint(rq: Request, cb: RequestHandler): void; - listbreakpoints(cb: RequestHandler): void; - reqSource(from: number, to: number, cb: RequestHandler): void; - reqScripts(cb: any): void; - reqContinue(cb: RequestHandler): void; - } - - export var Client: { - new(): ClientInstance - }; -} - /** * Async Hooks module: https://nodejs.org/api/async_hooks.html */ @@ -6712,216 +6678,216 @@ declare module "http2" { // Public API - export const constants: { - NGHTTP2_SESSION_SERVER: number; - NGHTTP2_SESSION_CLIENT: number; - NGHTTP2_STREAM_STATE_IDLE: number; - NGHTTP2_STREAM_STATE_OPEN: number; - NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; - NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; - NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; - NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; - NGHTTP2_STREAM_STATE_CLOSED: number; - NGHTTP2_NO_ERROR: number; - NGHTTP2_PROTOCOL_ERROR: number; - NGHTTP2_INTERNAL_ERROR: number; - NGHTTP2_FLOW_CONTROL_ERROR: number; - NGHTTP2_SETTINGS_TIMEOUT: number; - NGHTTP2_STREAM_CLOSED: number; - NGHTTP2_FRAME_SIZE_ERROR: number; - NGHTTP2_REFUSED_STREAM: number; - NGHTTP2_CANCEL: number; - NGHTTP2_COMPRESSION_ERROR: number; - NGHTTP2_CONNECT_ERROR: number; - NGHTTP2_ENHANCE_YOUR_CALM: number; - NGHTTP2_INADEQUATE_SECURITY: number; - NGHTTP2_HTTP_1_1_REQUIRED: number; - NGHTTP2_ERR_FRAME_SIZE_ERROR: number; - NGHTTP2_FLAG_NONE: number; - NGHTTP2_FLAG_END_STREAM: number; - NGHTTP2_FLAG_END_HEADERS: number; - NGHTTP2_FLAG_ACK: number; - NGHTTP2_FLAG_PADDED: number; - NGHTTP2_FLAG_PRIORITY: number; - DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; - DEFAULT_SETTINGS_ENABLE_PUSH: number; - DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; - DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; - MAX_MAX_FRAME_SIZE: number; - MIN_MAX_FRAME_SIZE: number; - MAX_INITIAL_WINDOW_SIZE: number; - NGHTTP2_DEFAULT_WEIGHT: number; - NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; - NGHTTP2_SETTINGS_ENABLE_PUSH: number; - NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; - NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; - NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; - NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; - PADDING_STRATEGY_NONE: number; - PADDING_STRATEGY_MAX: number; - PADDING_STRATEGY_CALLBACK: number; - HTTP2_HEADER_STATUS: string; - HTTP2_HEADER_METHOD: string; - HTTP2_HEADER_AUTHORITY: string; - HTTP2_HEADER_SCHEME: string; - HTTP2_HEADER_PATH: string; - HTTP2_HEADER_ACCEPT_CHARSET: string; - HTTP2_HEADER_ACCEPT_ENCODING: string; - HTTP2_HEADER_ACCEPT_LANGUAGE: string; - HTTP2_HEADER_ACCEPT_RANGES: string; - HTTP2_HEADER_ACCEPT: string; - HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; - HTTP2_HEADER_AGE: string; - HTTP2_HEADER_ALLOW: string; - HTTP2_HEADER_AUTHORIZATION: string; - HTTP2_HEADER_CACHE_CONTROL: string; - HTTP2_HEADER_CONNECTION: string; - HTTP2_HEADER_CONTENT_DISPOSITION: string; - HTTP2_HEADER_CONTENT_ENCODING: string; - HTTP2_HEADER_CONTENT_LANGUAGE: string; - HTTP2_HEADER_CONTENT_LENGTH: string; - HTTP2_HEADER_CONTENT_LOCATION: string; - HTTP2_HEADER_CONTENT_MD5: string; - HTTP2_HEADER_CONTENT_RANGE: string; - HTTP2_HEADER_CONTENT_TYPE: string; - HTTP2_HEADER_COOKIE: string; - HTTP2_HEADER_DATE: string; - HTTP2_HEADER_ETAG: string; - HTTP2_HEADER_EXPECT: string; - HTTP2_HEADER_EXPIRES: string; - HTTP2_HEADER_FROM: string; - HTTP2_HEADER_HOST: string; - HTTP2_HEADER_IF_MATCH: string; - HTTP2_HEADER_IF_MODIFIED_SINCE: string; - HTTP2_HEADER_IF_NONE_MATCH: string; - HTTP2_HEADER_IF_RANGE: string; - HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; - HTTP2_HEADER_LAST_MODIFIED: string; - HTTP2_HEADER_LINK: string; - HTTP2_HEADER_LOCATION: string; - HTTP2_HEADER_MAX_FORWARDS: string; - HTTP2_HEADER_PREFER: string; - HTTP2_HEADER_PROXY_AUTHENTICATE: string; - HTTP2_HEADER_PROXY_AUTHORIZATION: string; - HTTP2_HEADER_RANGE: string; - HTTP2_HEADER_REFERER: string; - HTTP2_HEADER_REFRESH: string; - HTTP2_HEADER_RETRY_AFTER: string; - HTTP2_HEADER_SERVER: string; - HTTP2_HEADER_SET_COOKIE: string; - HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; - HTTP2_HEADER_TRANSFER_ENCODING: string; - HTTP2_HEADER_TE: string; - HTTP2_HEADER_UPGRADE: string; - HTTP2_HEADER_USER_AGENT: string; - HTTP2_HEADER_VARY: string; - HTTP2_HEADER_VIA: string; - HTTP2_HEADER_WWW_AUTHENTICATE: string; - HTTP2_HEADER_HTTP2_SETTINGS: string; - HTTP2_HEADER_KEEP_ALIVE: string; - HTTP2_HEADER_PROXY_CONNECTION: string; - HTTP2_METHOD_ACL: string; - HTTP2_METHOD_BASELINE_CONTROL: string; - HTTP2_METHOD_BIND: string; - HTTP2_METHOD_CHECKIN: string; - HTTP2_METHOD_CHECKOUT: string; - HTTP2_METHOD_CONNECT: string; - HTTP2_METHOD_COPY: string; - HTTP2_METHOD_DELETE: string; - HTTP2_METHOD_GET: string; - HTTP2_METHOD_HEAD: string; - HTTP2_METHOD_LABEL: string; - HTTP2_METHOD_LINK: string; - HTTP2_METHOD_LOCK: string; - HTTP2_METHOD_MERGE: string; - HTTP2_METHOD_MKACTIVITY: string; - HTTP2_METHOD_MKCALENDAR: string; - HTTP2_METHOD_MKCOL: string; - HTTP2_METHOD_MKREDIRECTREF: string; - HTTP2_METHOD_MKWORKSPACE: string; - HTTP2_METHOD_MOVE: string; - HTTP2_METHOD_OPTIONS: string; - HTTP2_METHOD_ORDERPATCH: string; - HTTP2_METHOD_PATCH: string; - HTTP2_METHOD_POST: string; - HTTP2_METHOD_PRI: string; - HTTP2_METHOD_PROPFIND: string; - HTTP2_METHOD_PROPPATCH: string; - HTTP2_METHOD_PUT: string; - HTTP2_METHOD_REBIND: string; - HTTP2_METHOD_REPORT: string; - HTTP2_METHOD_SEARCH: string; - HTTP2_METHOD_TRACE: string; - HTTP2_METHOD_UNBIND: string; - HTTP2_METHOD_UNCHECKOUT: string; - HTTP2_METHOD_UNLINK: string; - HTTP2_METHOD_UNLOCK: string; - HTTP2_METHOD_UPDATE: string; - HTTP2_METHOD_UPDATEREDIRECTREF: string; - HTTP2_METHOD_VERSION_CONTROL: string; - HTTP_STATUS_CONTINUE: number; - HTTP_STATUS_SWITCHING_PROTOCOLS: number; - HTTP_STATUS_PROCESSING: number; - HTTP_STATUS_OK: number; - HTTP_STATUS_CREATED: number; - HTTP_STATUS_ACCEPTED: number; - HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; - HTTP_STATUS_NO_CONTENT: number; - HTTP_STATUS_RESET_CONTENT: number; - HTTP_STATUS_PARTIAL_CONTENT: number; - HTTP_STATUS_MULTI_STATUS: number; - HTTP_STATUS_ALREADY_REPORTED: number; - HTTP_STATUS_IM_USED: number; - HTTP_STATUS_MULTIPLE_CHOICES: number; - HTTP_STATUS_MOVED_PERMANENTLY: number; - HTTP_STATUS_FOUND: number; - HTTP_STATUS_SEE_OTHER: number; - HTTP_STATUS_NOT_MODIFIED: number; - HTTP_STATUS_USE_PROXY: number; - HTTP_STATUS_TEMPORARY_REDIRECT: number; - HTTP_STATUS_PERMANENT_REDIRECT: number; - HTTP_STATUS_BAD_REQUEST: number; - HTTP_STATUS_UNAUTHORIZED: number; - HTTP_STATUS_PAYMENT_REQUIRED: number; - HTTP_STATUS_FORBIDDEN: number; - HTTP_STATUS_NOT_FOUND: number; - HTTP_STATUS_METHOD_NOT_ALLOWED: number; - HTTP_STATUS_NOT_ACCEPTABLE: number; - HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; - HTTP_STATUS_REQUEST_TIMEOUT: number; - HTTP_STATUS_CONFLICT: number; - HTTP_STATUS_GONE: number; - HTTP_STATUS_LENGTH_REQUIRED: number; - HTTP_STATUS_PRECONDITION_FAILED: number; - HTTP_STATUS_PAYLOAD_TOO_LARGE: number; - HTTP_STATUS_URI_TOO_LONG: number; - HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; - HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; - HTTP_STATUS_EXPECTATION_FAILED: number; - HTTP_STATUS_TEAPOT: number; - HTTP_STATUS_MISDIRECTED_REQUEST: number; - HTTP_STATUS_UNPROCESSABLE_ENTITY: number; - HTTP_STATUS_LOCKED: number; - HTTP_STATUS_FAILED_DEPENDENCY: number; - HTTP_STATUS_UNORDERED_COLLECTION: number; - HTTP_STATUS_UPGRADE_REQUIRED: number; - HTTP_STATUS_PRECONDITION_REQUIRED: number; - HTTP_STATUS_TOO_MANY_REQUESTS: number; - HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; - HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; - HTTP_STATUS_INTERNAL_SERVER_ERROR: number; - HTTP_STATUS_NOT_IMPLEMENTED: number; - HTTP_STATUS_BAD_GATEWAY: number; - HTTP_STATUS_SERVICE_UNAVAILABLE: number; - HTTP_STATUS_GATEWAY_TIMEOUT: number; - HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; - HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; - HTTP_STATUS_INSUFFICIENT_STORAGE: number; - HTTP_STATUS_LOOP_DETECTED: number; - HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; - HTTP_STATUS_NOT_EXTENDED: number; - HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; - }; + export namespace constants { + export const NGHTTP2_SESSION_SERVER: number; + export const NGHTTP2_SESSION_CLIENT: number; + export const NGHTTP2_STREAM_STATE_IDLE: number; + export const NGHTTP2_STREAM_STATE_OPEN: number; + export const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + export const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + export const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + export const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + export const NGHTTP2_STREAM_STATE_CLOSED: number; + export const NGHTTP2_NO_ERROR: number; + export const NGHTTP2_PROTOCOL_ERROR: number; + export const NGHTTP2_INTERNAL_ERROR: number; + export const NGHTTP2_FLOW_CONTROL_ERROR: number; + export const NGHTTP2_SETTINGS_TIMEOUT: number; + export const NGHTTP2_STREAM_CLOSED: number; + export const NGHTTP2_FRAME_SIZE_ERROR: number; + export const NGHTTP2_REFUSED_STREAM: number; + export const NGHTTP2_CANCEL: number; + export const NGHTTP2_COMPRESSION_ERROR: number; + export const NGHTTP2_CONNECT_ERROR: number; + export const NGHTTP2_ENHANCE_YOUR_CALM: number; + export const NGHTTP2_INADEQUATE_SECURITY: number; + export const NGHTTP2_HTTP_1_1_REQUIRED: number; + export const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + export const NGHTTP2_FLAG_NONE: number; + export const NGHTTP2_FLAG_END_STREAM: number; + export const NGHTTP2_FLAG_END_HEADERS: number; + export const NGHTTP2_FLAG_ACK: number; + export const NGHTTP2_FLAG_PADDED: number; + export const NGHTTP2_FLAG_PRIORITY: number; + export const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + export const DEFAULT_SETTINGS_ENABLE_PUSH: number; + export const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + export const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + export const MAX_MAX_FRAME_SIZE: number; + export const MIN_MAX_FRAME_SIZE: number; + export const MAX_INITIAL_WINDOW_SIZE: number; + export const NGHTTP2_DEFAULT_WEIGHT: number; + export const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + export const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + export const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + export const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + export const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + export const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + export const PADDING_STRATEGY_NONE: number; + export const PADDING_STRATEGY_MAX: number; + export const PADDING_STRATEGY_CALLBACK: number; + export const HTTP2_HEADER_STATUS: string; + export const HTTP2_HEADER_METHOD: string; + export const HTTP2_HEADER_AUTHORITY: string; + export const HTTP2_HEADER_SCHEME: string; + export const HTTP2_HEADER_PATH: string; + export const HTTP2_HEADER_ACCEPT_CHARSET: string; + export const HTTP2_HEADER_ACCEPT_ENCODING: string; + export const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + export const HTTP2_HEADER_ACCEPT_RANGES: string; + export const HTTP2_HEADER_ACCEPT: string; + export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + export const HTTP2_HEADER_AGE: string; + export const HTTP2_HEADER_ALLOW: string; + export const HTTP2_HEADER_AUTHORIZATION: string; + export const HTTP2_HEADER_CACHE_CONTROL: string; + export const HTTP2_HEADER_CONNECTION: string; + export const HTTP2_HEADER_CONTENT_DISPOSITION: string; + export const HTTP2_HEADER_CONTENT_ENCODING: string; + export const HTTP2_HEADER_CONTENT_LANGUAGE: string; + export const HTTP2_HEADER_CONTENT_LENGTH: string; + export const HTTP2_HEADER_CONTENT_LOCATION: string; + export const HTTP2_HEADER_CONTENT_MD5: string; + export const HTTP2_HEADER_CONTENT_RANGE: string; + export const HTTP2_HEADER_CONTENT_TYPE: string; + export const HTTP2_HEADER_COOKIE: string; + export const HTTP2_HEADER_DATE: string; + export const HTTP2_HEADER_ETAG: string; + export const HTTP2_HEADER_EXPECT: string; + export const HTTP2_HEADER_EXPIRES: string; + export const HTTP2_HEADER_FROM: string; + export const HTTP2_HEADER_HOST: string; + export const HTTP2_HEADER_IF_MATCH: string; + export const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + export const HTTP2_HEADER_IF_NONE_MATCH: string; + export const HTTP2_HEADER_IF_RANGE: string; + export const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + export const HTTP2_HEADER_LAST_MODIFIED: string; + export const HTTP2_HEADER_LINK: string; + export const HTTP2_HEADER_LOCATION: string; + export const HTTP2_HEADER_MAX_FORWARDS: string; + export const HTTP2_HEADER_PREFER: string; + export const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + export const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + export const HTTP2_HEADER_RANGE: string; + export const HTTP2_HEADER_REFERER: string; + export const HTTP2_HEADER_REFRESH: string; + export const HTTP2_HEADER_RETRY_AFTER: string; + export const HTTP2_HEADER_SERVER: string; + export const HTTP2_HEADER_SET_COOKIE: string; + export const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + export const HTTP2_HEADER_TRANSFER_ENCODING: string; + export const HTTP2_HEADER_TE: string; + export const HTTP2_HEADER_UPGRADE: string; + export const HTTP2_HEADER_USER_AGENT: string; + export const HTTP2_HEADER_VARY: string; + export const HTTP2_HEADER_VIA: string; + export const HTTP2_HEADER_WWW_AUTHENTICATE: string; + export const HTTP2_HEADER_HTTP2_SETTINGS: string; + export const HTTP2_HEADER_KEEP_ALIVE: string; + export const HTTP2_HEADER_PROXY_CONNECTION: string; + export const HTTP2_METHOD_ACL: string; + export const HTTP2_METHOD_BASELINE_CONTROL: string; + export const HTTP2_METHOD_BIND: string; + export const HTTP2_METHOD_CHECKIN: string; + export const HTTP2_METHOD_CHECKOUT: string; + export const HTTP2_METHOD_CONNECT: string; + export const HTTP2_METHOD_COPY: string; + export const HTTP2_METHOD_DELETE: string; + export const HTTP2_METHOD_GET: string; + export const HTTP2_METHOD_HEAD: string; + export const HTTP2_METHOD_LABEL: string; + export const HTTP2_METHOD_LINK: string; + export const HTTP2_METHOD_LOCK: string; + export const HTTP2_METHOD_MERGE: string; + export const HTTP2_METHOD_MKACTIVITY: string; + export const HTTP2_METHOD_MKCALENDAR: string; + export const HTTP2_METHOD_MKCOL: string; + export const HTTP2_METHOD_MKREDIRECTREF: string; + export const HTTP2_METHOD_MKWORKSPACE: string; + export const HTTP2_METHOD_MOVE: string; + export const HTTP2_METHOD_OPTIONS: string; + export const HTTP2_METHOD_ORDERPATCH: string; + export const HTTP2_METHOD_PATCH: string; + export const HTTP2_METHOD_POST: string; + export const HTTP2_METHOD_PRI: string; + export const HTTP2_METHOD_PROPFIND: string; + export const HTTP2_METHOD_PROPPATCH: string; + export const HTTP2_METHOD_PUT: string; + export const HTTP2_METHOD_REBIND: string; + export const HTTP2_METHOD_REPORT: string; + export const HTTP2_METHOD_SEARCH: string; + export const HTTP2_METHOD_TRACE: string; + export const HTTP2_METHOD_UNBIND: string; + export const HTTP2_METHOD_UNCHECKOUT: string; + export const HTTP2_METHOD_UNLINK: string; + export const HTTP2_METHOD_UNLOCK: string; + export const HTTP2_METHOD_UPDATE: string; + export const HTTP2_METHOD_UPDATEREDIRECTREF: string; + export const HTTP2_METHOD_VERSION_CONTROL: string; + export const HTTP_STATUS_CONTINUE: number; + export const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + export const HTTP_STATUS_PROCESSING: number; + export const HTTP_STATUS_OK: number; + export const HTTP_STATUS_CREATED: number; + export const HTTP_STATUS_ACCEPTED: number; + export const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + export const HTTP_STATUS_NO_CONTENT: number; + export const HTTP_STATUS_RESET_CONTENT: number; + export const HTTP_STATUS_PARTIAL_CONTENT: number; + export const HTTP_STATUS_MULTI_STATUS: number; + export const HTTP_STATUS_ALREADY_REPORTED: number; + export const HTTP_STATUS_IM_USED: number; + export const HTTP_STATUS_MULTIPLE_CHOICES: number; + export const HTTP_STATUS_MOVED_PERMANENTLY: number; + export const HTTP_STATUS_FOUND: number; + export const HTTP_STATUS_SEE_OTHER: number; + export const HTTP_STATUS_NOT_MODIFIED: number; + export const HTTP_STATUS_USE_PROXY: number; + export const HTTP_STATUS_TEMPORARY_REDIRECT: number; + export const HTTP_STATUS_PERMANENT_REDIRECT: number; + export const HTTP_STATUS_BAD_REQUEST: number; + export const HTTP_STATUS_UNAUTHORIZED: number; + export const HTTP_STATUS_PAYMENT_REQUIRED: number; + export const HTTP_STATUS_FORBIDDEN: number; + export const HTTP_STATUS_NOT_FOUND: number; + export const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + export const HTTP_STATUS_NOT_ACCEPTABLE: number; + export const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + export const HTTP_STATUS_REQUEST_TIMEOUT: number; + export const HTTP_STATUS_CONFLICT: number; + export const HTTP_STATUS_GONE: number; + export const HTTP_STATUS_LENGTH_REQUIRED: number; + export const HTTP_STATUS_PRECONDITION_FAILED: number; + export const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + export const HTTP_STATUS_URI_TOO_LONG: number; + export const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + export const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + export const HTTP_STATUS_EXPECTATION_FAILED: number; + export const HTTP_STATUS_TEAPOT: number; + export const HTTP_STATUS_MISDIRECTED_REQUEST: number; + export const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + export const HTTP_STATUS_LOCKED: number; + export const HTTP_STATUS_FAILED_DEPENDENCY: number; + export const HTTP_STATUS_UNORDERED_COLLECTION: number; + export const HTTP_STATUS_UPGRADE_REQUIRED: number; + export const HTTP_STATUS_PRECONDITION_REQUIRED: number; + export const HTTP_STATUS_TOO_MANY_REQUESTS: number; + export const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + export const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + export const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + export const HTTP_STATUS_NOT_IMPLEMENTED: number; + export const HTTP_STATUS_BAD_GATEWAY: number; + export const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + export const HTTP_STATUS_GATEWAY_TIMEOUT: number; + export const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + export const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + export const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + export const HTTP_STATUS_LOOP_DETECTED: number; + export const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + export const HTTP_STATUS_NOT_EXTENDED: number; + export const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } export function getDefaultSettings(): Settings; export function getPackedSettings(settings: Settings): Settings; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index d85a2574db..8742a476c5 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -405,6 +405,20 @@ function bufferTests() { const buf1: Buffer = Buffer.from('this is a tést'); const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Class Method byteLenght { @@ -558,7 +572,7 @@ namespace url_tests { { var helloUrl = url.parse('http://example.com/?hello=world', true); if (typeof helloUrl.query !== 'string') { - assert.equal(helloUrl.query.hello, 'world'); + assert.equal(helloUrl.query['hello'], 'world'); } } @@ -2425,6 +2439,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// @@ -3072,17 +3106,6 @@ namespace v8_tests { v8.setFlagsFromString('--collect_maps'); } -/////////////////////////////////////////////////////////// -/// Debugger Tests /// -/////////////////////////////////////////////////////////// - -import { Client } from "_debugger"; - -var client = new Client(); - -client.connect(8888, 'localhost'); -client.listbreakpoints((err, body, packet) => { }); - //////////////////////////////////////////////////// /// AsyncHooks tests : https://nodejs.org/api/async_hooks.html //////////////////////////////////////////////////// diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 797bc455b8..19fc7b5e5f 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 4.2 +// Type definitions for Node.js 4.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -34,8 +34,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -214,6 +224,29 @@ declare var Buffer: { * The same as buf1.compare(buf2). */ compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; }; /************************************************ @@ -229,6 +262,80 @@ declare namespace NodeJS { customInspect?: boolean; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 8f005da455..431dfb0520 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -268,6 +268,21 @@ function bufferTests() { const buf1: Buffer = Buffer.from('this is a tést'); const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. @@ -1008,6 +1023,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index e8931e43cf..bad3de25ad 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -31,8 +31,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -258,6 +268,80 @@ declare namespace NodeJS { new(stdout: WritableStream, stderr?: WritableStream): Console; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 1a6b87db05..171b92ba1a 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -330,6 +330,20 @@ function bufferTests() { const buf1: Buffer = Buffer.from('this is a tést'); const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. @@ -1829,6 +1843,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index cc87fadd7c..44013f2e6e 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -32,8 +32,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -270,6 +280,80 @@ declare namespace NodeJS { new(stdout: WritableStream, stderr?: WritableStream): Console; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 9bbf6a9300..f0878cc6fc 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -319,6 +319,20 @@ function bufferTests() { buf = Buffer.from(arr.buffer, 1); buf = Buffer.from(arr.buffer, 0, 1); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Class Method: Buffer.from(buffer) { @@ -1931,6 +1945,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index 89dda72b9c..88dde55025 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -361,13 +361,13 @@ declare namespace p2 { export class ContactMaterialOptions { - friction: number; - restitution: number; - stiffness: number; - relaxation: number; - frictionStiffness: number; - frictionRelaxation: number; - surfaceVelocity: number; + friction?: number; + restitution?: number; + stiffness?: number; + relaxation?: number; + frictionStiffness?: number; + frictionRelaxation?: number; + surfaceVelocity?: number; } @@ -624,8 +624,8 @@ declare namespace p2 { export interface ConvexOptions extends SharedShapeOptions { - length?: number; - radius?: number; + vertices?: ArrayLike[]; + axes?: ArrayLike[]; } @@ -636,7 +636,7 @@ declare namespace p2 { constructor(options?: ConvexOptions); vertices: number[][]; - axes: number[]; + axes: number[][]; centerOfMass: number[]; triangles: number[]; boundingRadius: number; diff --git a/types/p2/p2-tests.ts b/types/p2/p2-tests.ts index 0579a880b2..c796cf8f79 100644 --- a/types/p2/p2-tests.ts +++ b/types/p2/p2-tests.ts @@ -4,6 +4,12 @@ var world = new p2.World({ gravity:[0, -9.82] }); +// Set default contact material +world.defaultContactMaterial = new p2.ContactMaterial( + new p2.Material(1), new p2.Material(2), + { friction: 1, restitution: 0 } +) + // Create an empty dynamic body var circleBody = new p2.Body({ mass: 5, @@ -26,6 +32,20 @@ var groundShape = new p2.Plane(); groundBody.addShape(groundShape); world.addBody(groundBody); +// Create a convex shape. Can use various array types. +const convex = new p2.Convex({ + vertices: [ + new Float32Array([-1, 1]), + new Uint32Array([0, -1]), + [1, 1] + ], + axes: [ + new Float32Array([-1, 1]), + new Int32Array([0, -1]), + [1, 1] + ] +}) + // To get the trajectories of the bodies, // we must step the world forward in time. // This is done using a fixed time step size. diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index f75661377a..46d5f58786 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1305,7 +1305,12 @@ declare module 'paper' { * The function to be called when the mouse button is pushed down on the item. The function receives a MouseEvent object which contains information about the mouse event. */ onMouseDown: (event: MouseEvent) => void; - + + /** + * The function to be called when the mouse position changes while the mouse is being dragged. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseDrag: (event: MouseEvent) => void; + /** * The function to be called when the mouse button is released over the item. * The function receives a MouseEvent object which contains information about the mouse event. diff --git a/types/parse-ms/index.d.ts b/types/parse-ms/index.d.ts new file mode 100644 index 0000000000..1a8a63d4a2 --- /dev/null +++ b/types/parse-ms/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for parse-ms 1.0 +// Project: https://github.com/sindresorhus/parse-ms#readme +// Definitions by: Giles Roadnight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function parseMs(ms: number): { + days: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; +}; diff --git a/types/parse-ms/parse-ms-tests.ts b/types/parse-ms/parse-ms-tests.ts new file mode 100644 index 0000000000..2b747ad5a8 --- /dev/null +++ b/types/parse-ms/parse-ms-tests.ts @@ -0,0 +1,3 @@ +import parseMs from "parse-ms"; + +const { days, hours, milliseconds, minutes, seconds } = parseMs(3000); diff --git a/types/parse-ms/tsconfig.json b/types/parse-ms/tsconfig.json new file mode 100644 index 0000000000..3fecf7615f --- /dev/null +++ b/types/parse-ms/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parse-ms-tests.ts" + ] +} diff --git a/types/parse-ms/tslint.json b/types/parse-ms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parse-ms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/parsimmon/index.d.ts b/types/parsimmon/index.d.ts index 26ed383daf..c25ab020de 100644 --- a/types/parsimmon/index.d.ts +++ b/types/parsimmon/index.d.ts @@ -6,7 +6,7 @@ // Benny van Reeven // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 /** * **NOTE:** You probably will never need to use this function. Most parsing @@ -75,13 +75,21 @@ declare namespace Parsimmon { } interface Rule { - [key: string]: (r?: Language) => Parser; + [key: string]: (r: Language) => Parser; } interface Language { [key: string]: Parser; } + type TypedRule = { + [P in keyof TLanguageSpec]: (r: TypedLanguage) => Parser; + }; + + type TypedLanguage = { + [P in keyof TLanguageSpec]: Parser; + }; + interface Parser { /** * parse the string @@ -189,9 +197,51 @@ declare namespace Parsimmon { function Parser(fn: (input: string, i: number) => Parsimmon.Reply): Parser; /** - * Starting point for building a language parser in Parsimmon + * Starting point for building a language parser in Parsimmon. + * + * For having the resulting language rules return typed parsers, e.g. `Parser` instead of + * `Parser`, pass a language specification as type parameter to this function. The language + * specification should be of the following form: + * + * ```javascript + * { + * rule1: type; + * rule2: type; + * } + * ``` + * + * For example: + * + * ```javascript + * const language = Parsimmon.createLanguage<{ + * expr: Expr; + * numberLiteral: number; + * stringLiteral: string; + * }>({ + * expr: r => (some expression that yields Parser), + * numberLiteral: r => (some expression that yields Parser), + * stringLiteral: r => (some expression that yields Parser) + * }); + * ``` + * + * Now both `language` and the parameter `r` that is passed into every parser rule will be of the + * following type: + * + * ```javascript + * { + * expr: Parser; + * numberLiteral: Parser; + * stringLiteral: Parser; + * } + * ``` + * + * Another benefit is that both the `rules` parameter and the resulting `language` should match the + * properties defined in the language specification type, which means that the compiler checks that + * there are no missing or superfluous rules in the language definition, and that the rules you access + * on the resulting language do actually exist. */ function createLanguage(rules: Rule): Language; + function createLanguage(rules: TypedRule): TypedLanguage; /** * To be used inside of Parsimmon(fn). Generates an object describing how diff --git a/types/parsimmon/parsimmon-tests.ts b/types/parsimmon/parsimmon-tests.ts index f89d2fda2f..c6dbaec22c 100644 --- a/types/parsimmon/parsimmon-tests.ts +++ b/types/parsimmon/parsimmon-tests.ts @@ -1,5 +1,5 @@ import P = require('parsimmon'); -import { Parser, Mark, Result, Index, Reply } from "parsimmon"; +import { Parser, Mark, Result, Index, Reply, Language, TypedLanguage } from "parsimmon"; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -13,27 +13,27 @@ class Bar { // -- -- -- -- -- -- -- -- -- -- -- -- -- -let str: string; +let str: string = null!; let strArr: string[]; let bool: boolean; -let num: number; +let num: number = null!; let index: Index; -let foo: Foo; +let foo: Foo = null!; declare const bar: Bar; // -- -- -- -- -- -- -- -- -- -- -- -- -- let strPar: Parser; -let numPar: Parser; +let numPar: Parser = null!; let voidPar: Parser; let anyPar: Parser; let nullPar: Parser; let emptyStrPar: Parser<''>; let indexPar: Parser; -let fooPar: Parser; -let barPar: Parser; +let fooPar: Parser = null!; +let barPar: Parser = null!; let fooOrBarPar: Parser; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -43,7 +43,7 @@ let fooArrPar: Parser; // -- -- -- -- -- -- -- -- -- -- -- -- -- -let fooMarkPar: Parser>; +let fooMarkPar: Parser> = null!; const result = fooMarkPar.parse(str); if (result.status) { @@ -54,7 +54,7 @@ if (result.status) { // -- -- -- -- -- -- -- -- -- -- -- -- -- -let fooResult: Result; +let fooResult: Result = fooPar.parse(""); // https://github.com/Microsoft/TypeScript/issues/12882 if (fooResult.status === true) { @@ -191,3 +191,55 @@ strArrPar = P.sepBy1(P.string('foo'), P.string('bar')); strPar = P.test((a: string) => false); strPar = P.takeWhile((a: string) => true); + +// -- -- -- -- -- -- -- -- -- -- -- -- -- + +let language: Language; + +language = P.createLanguage({ + SomeRule: r => P.alt(P.string(""), r.AnotherRule), + AnotherRule: () => P.string(""), +}); + +// $ExpectType Parser +language.SomeRule; +// $ExpectType Parser +language.AnotherRule; +// $ExpectType Parser +language.UndefinedRule; + +interface MyLanguageSpec { + FooRule: Foo; + BarRule: Bar; + StringRule: string; +} + +let myLanguage: TypedLanguage; + +myLanguage = P.createLanguage({ + FooRule: r => { + fooPar = r.FooRule; + barPar = r.BarRule; + strPar = r.StringRule; + return fooPar; + }, + BarRule: r => barPar, + StringRule: () => strPar, +}); + +// $ExpectType Parser +myLanguage.FooRule; +// $ExpectType Parser +myLanguage.BarRule; +// $ExpectType Parser +myLanguage.StringRule; + +const noRules = P.createLanguage<{}>({}); + +// $ExpectError +P.createLanguage<{MissingRule: string}>({}); + +P.createLanguage<{SomeRule: string}>({ + SomeRule: r => strPar, + AnotherRule: (r: any) => strPar // $ExpectError +}); diff --git a/types/parsimmon/tsconfig.json b/types/parsimmon/tsconfig.json index 34d78a5d0a..676b349a37 100644 --- a/types/parsimmon/tsconfig.json +++ b/types/parsimmon/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "parsimmon-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/passport-google-oauth/index.d.ts b/types/passport-google-oauth/index.d.ts index 720f6449d7..a56c91e73f 100644 --- a/types/passport-google-oauth/index.d.ts +++ b/types/passport-google-oauth/index.d.ts @@ -1,19 +1,16 @@ -// Type definitions for passport-facebook 1.0.3 -// Project: https://github.com/jaredhanson/passport-facebook +// Type definitions for passport-google-oauth 1.0.3 +// Project: https://github.com/jaredhanson/passport-google-oauth // Definitions by: James Roland Cabresos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// - - import passport = require('passport'); import express = require('express'); interface Profile extends passport.Profile { gender: string; - _raw: string; _json: any; } @@ -22,7 +19,6 @@ interface IOAuthStrategyOption { consumerKey: string; consumerSecret: string; callbackURL: string; - requestTokenURL?: string; accessTokenURL?: string; userAuthorizationURL?: string; @@ -38,8 +34,15 @@ interface VerifyFunction { } declare class OAuthStrategy implements passport.Strategy { - constructor(options: IOAuthStrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: VerifyFunction) => void); + constructor( + options: IOAuthStrategyOption, + verify: ( + accessToken: string, + refreshToken: string, + profile: Profile, + done: VerifyFunction + ) => void + ); name: string; authenticate: (req: express.Request, options?: Object) => void; } @@ -48,10 +51,8 @@ interface IOAuth2StrategyOption { clientID: string; clientSecret: string; callbackURL: string; - authorizationURL?: string; tokenURL?: string; - accessType?: string; approval_prompt?: string; prompt?: string; @@ -64,14 +65,29 @@ interface IOAuth2StrategyOption { } interface IOAuth2StrategyOptionWithRequest extends IOAuth2StrategyOption { - passReqToCallback: true; + passReqToCallback: boolean; } declare class OAuth2Strategy implements passport.Strategy { - constructor(options: IOAuth2StrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => void); - constructor(options: IOAuth2StrategyOptionWithRequest, - verify: (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => void); + constructor( + options: IOAuth2StrategyOption, + verify: ( + accessToken: string, + refreshToken: string, + profile: Profile, + done: (error: any, user?: any) => void + ) => void + ); + constructor( + options: IOAuth2StrategyOptionWithRequest, + verify: ( + req: express.Request, + accessToken: string, + refreshToken: string, + profile: Profile, + done: (error: any, user?: any) => void + ) => void + ); name: string; authenticate: (req: express.Request, options?: Object) => void; diff --git a/types/passport-google-oauth/passport-google-oauth-tests.ts b/types/passport-google-oauth/passport-google-oauth-tests.ts index ad0ed185a3..2e9a4bb9c2 100644 --- a/types/passport-google-oauth/passport-google-oauth-tests.ts +++ b/types/passport-google-oauth/passport-google-oauth-tests.ts @@ -1,55 +1,98 @@ - /** * Created by jcabresos on 4/19/2014. */ -import express = require("express"); +import express = require('express'); import passport = require('passport'); import google = require('passport-google-oauth'); // just some test model var User = { - findOrCreate(id:string, provider:string, callback:(err:any, user:any) => void): void { - callback(null, {username:'james'}); + findOrCreate( + id: string, + provider: string, + callback: (err: any, user: any) => void + ): void { + callback(null, { username: 'james' }); } -} +}; -passport.use(new google.OAuthStrategy({ +passport.use( + new google.OAuthStrategy( + { consumerKey: process.env.GOOGLE_CONSUMER_KEY, consumerSecret: process.env.GOOGLE_CONSUMER_SECRET, callbackURL: process.env.PASSPORT_GOOGLE_CALLBACK_URL - }, - function(accessToken:string, refreshToken:string, profile:google.Profile, done:(error:any, user?:any, msg?: google.VerifyOptions) => void) { - User.findOrCreate(profile.id, profile.provider, function(err, user) { - if (err) { return done(err); } - else if(!user) return done(null, false, {message: 'not found user'}); - return done(null, user); - }); - }) + }, + function( + accessToken: string, + refreshToken: string, + profile: google.Profile, + done: (error: any, user?: any, msg?: google.VerifyOptions) => void + ) { + User.findOrCreate(profile.id, profile.provider, function( + err, + user + ) { + if (err) { + return done(err); + } else if (!user) + return done(null, false, { message: 'not found user' }); + return done(null, user); + }); + } + ) ); -passport.use(new google.OAuth2Strategy({ +passport.use( + new google.OAuth2Strategy( + { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: process.env.PASSPORT_GOOGLE_CALLBACK_URL - }, - function(accessToken:string, refreshToken:string, profile:google.Profile, done:(error:any, user?:any) => void) { - User.findOrCreate(profile.id, profile.provider, function(err, user) { - if (err) { return done(err); } - done(null, user); - }); - }) + }, + function( + accessToken: string, + refreshToken: string, + profile: google.Profile, + done: (error: any, user?: any) => void + ) { + User.findOrCreate(profile.id, profile.provider, function( + err, + user + ) { + if (err) { + return done(err); + } + done(null, user); + }); + } + ) ); -passport.use(new google.OAuth2Strategy({ +passport.use( + new google.OAuth2Strategy( + { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: process.env.PASSPORT_GOOGLE_CALLBACK_URL, passReqToCallback: true - }, - function(req: express.Request, accessToken:string, refreshToken:string, profile:google.Profile, done:(error:any, user?:any) => void) { - User.findOrCreate(profile.id, profile.provider, function(err, user) { - if (err) { return done(err); } - done(null, user); - }); - }) + }, + function( + req: express.Request, + accessToken: string, + refreshToken: string, + profile: google.Profile, + done: (error: any, user?: any) => void + ) { + User.findOrCreate(profile.id, profile.provider, function( + err, + user + ) { + if (err) { + return done(err); + } + done(null, user); + }); + } + ) ); diff --git a/types/passport-google-oauth/tsconfig.json b/types/passport-google-oauth/tsconfig.json index adde576621..7f3b315c07 100644 --- a/types/passport-google-oauth/tsconfig.json +++ b/types/passport-google-oauth/tsconfig.json @@ -1,23 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "passport-google-oauth-tests.ts" - ] -} \ No newline at end of file + "files": ["index.d.ts", "passport-google-oauth-tests.ts"] +} diff --git a/types/pathwatcher/index.d.ts b/types/pathwatcher/index.d.ts index 0ff5427913..4e5476bd80 100644 --- a/types/pathwatcher/index.d.ts +++ b/types/pathwatcher/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/node-pathwatcher // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 48b9583c0b..1875746d6e 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -834,7 +834,7 @@ declare namespace PIXI { protected _lastObjectRendered: DisplayObject; resize(screenWidth: number, screenHeight: number): void; - generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; + generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number, region?: Rectangle): RenderTexture; render(...args: any[]): void; destroy(removeView?: boolean): void; } @@ -948,7 +948,6 @@ declare namespace PIXI { extract: extract.WebGLExtract; protected drawModes: any; protected _activeShader: Shader; - protected _activeVao: glCore.VertexArrayObject; _activeRenderTarget: RenderTarget; protected _initContext(): void; @@ -1032,7 +1031,7 @@ declare namespace PIXI { update(): void; run(): void; - unload(): void; + unload(displayObject: DisplayObject): void; } abstract class ObjectRenderer extends WebGLManager { constructor(renderer: WebGLRenderer); @@ -2124,7 +2123,7 @@ declare namespace PIXI { protected _tempPoint: Point; resolution: number; hitTest(globalPoint: Point, root?: Container): DisplayObject; - protected setTargetElement(element: HTMLCanvasElement, resolution?: number): void; + setTargetElement(element: HTMLCanvasElement, resolution?: number): void; protected addEvents(): void; protected removeEvents(): void; update(deltaTime?: number): void; @@ -2661,7 +2660,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// /////////////////////////////pixi-gl-core///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - // pixi-gl-core 1.1.2 https://github.com/pixijs/pixi-gl-core + // pixi-gl-core 1.1.4 https://github.com/pixijs/pixi-gl-core // sharedArrayBuffer as a type is not available yet. // need to fully define what an `Attrib` is. namespace glCore { @@ -2813,13 +2812,13 @@ declare namespace PIXI { indexBuffer: GLBuffer; dirty: boolean; - bind(): VertexArrayObject; - unbind(): VertexArrayObject; - activate(): VertexArrayObject; - addAttribute(buffer: GLBuffer, attribute: Attrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; - addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; - clear(): VertexArrayObject; - draw(type: number, size: number, start: number): VertexArrayObject; + bind(): this; + unbind(): this; + activate(): this; + addAttribute(buffer: GLBuffer, attribute: Attrib, type?: number, normalized?: boolean, stride?: number, start?: number): this; + addIndex(buffer: GLBuffer, options?: any): this; + clear(): this; + draw(type: number, size: number, start: number): this; destroy(): void; } } diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index a24bf6ce18..32c541fda6 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prettier 1.8 +// Type definitions for prettier 1.9 // Project: https://github.com/prettier/prettier // Definitions by: Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -85,12 +85,18 @@ export interface Options { */ insertPragma?: boolean; /** - * By default, Prettier will wrap markdown text at the specified print width. - * In some cases you may want to rely on editor/viewer soft wrapping instead, - * so this option allows you to opt out. When prose wrapping is disabled, - * each paragraph will be printed on its own line. + * By default, Prettier will wrap markdown text as-is since some services use a linebreak-sensitive renderer. + * In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out. */ - proseWrap?: boolean; + proseWrap?: + | boolean // deprecated + | 'always' + | 'never' + | 'preserve'; + /** + * Include parentheses around a sole arrow function parameter. + */ + arrowParens?: 'avoid' | 'always'; } export interface CursorOptions extends Options { @@ -135,6 +141,16 @@ export interface ResolveConfigOptions { * Pass directly the path of the config file if you don't wish to search for it. */ config?: string; + /** + * If set to `true` and an `.editorconfig` file is in your project, + * Prettier will parse it and convert its properties to the corresponding prettier configuration. + * This configuration will be overridden by `.prettierrc`, etc. Currently, + * the following EditorConfig properties are supported: + * - indent_style + * - indent_size/tab_width + * - max_line_length + */ + editorconfig?: boolean; } /** diff --git a/types/prismjs/index.d.ts b/types/prismjs/index.d.ts index 06775720af..86f2c55d95 100644 --- a/types/prismjs/index.d.ts +++ b/types/prismjs/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for prism 1.6 +// Type definitions for prism 1.9 // Project: http://prismjs.com/ -// Definitions by: Erik Lieben , Andre Wiggins +// Definitions by: Erik Lieben +// Andre Wiggins +// Michał Miszczyszyn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace Prism; @@ -11,15 +13,27 @@ export const plugins: any; export const hooks: Hooks; /** - * This is the most high-level function in Prism’s API. It fetches all the elements that have a .language-xxxx class and - * then calls Prism.highlightElement() on each one of them. + * Used to highlight all elements on current website. Calls Prism.highlightAllUnder on `document`. * + * @see highlightAllUnder * @param async Whether to use Web Workers to improve performance and avoid blocking the UI when highlighting * very large chunks of code. False by default. * @param callback An optional callback to be invoked after the highlighting is done. Mostly useful when async * is true, since in that case, the highlighting is done asynchronously. */ -export function highlightAll(async: boolean, callback?: (element: Element) => void): void; +export function highlightAll(async?: boolean, callback?: (element: Element) => void): void; + +/** + * This is the most high-level function in Prism’s API. It fetches all the elements inside `container` that + * have a .language-xxxx class and then calls Prism.highlightElement() on each one of them. + * + * @param container The element which contains elements containing code. + * @param async Whether to use Web Workers to improve performance and avoid blocking the UI when highlighting + * very large chunks of code. False by default. + * @param callback An optional callback to be invoked after the highlighting is done. Mostly useful when async + * is true, since in that case, the highlighting is done asynchronously. + */ +export function highlightAllUnder(container: Element, async?: boolean, callback?: (element: Element) => void): void; /** * Highlights the code inside a single element. @@ -31,18 +45,18 @@ export function highlightAll(async: boolean, callback?: (element: Element) => vo * @param callback An optional callback to be invoked after the highlighting is done. * Mostly useful when async is true, since in that case, the highlighting is done asynchronously. */ -export function highlightElement(element: Element, async: boolean, callback?: (element: Element) => void): void; +export function highlightElement(element: Element, async?: boolean, callback?: (element: Element) => void): void; /** * Low-level function, only use if you know what you’re doing. It accepts a string of text as input and the language * definitions to use, and returns a string with the HTML produced. * * @param text A string with the code to be highlighted. - * @param grammer - An object containing the tokens to use. Usually a language definition like + * @param grammar - An object containing the tokens to use. Usually a language definition like * Prism.languages.markup * @returns The highlighted HTML */ -export function highlight(text: string, grammer: LanguageDefinition, language?: LanguageDefinition): string; +export function highlight(text: string, grammar: LanguageDefinition, language?: LanguageDefinition): string; /** * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input and the @@ -50,8 +64,8 @@ export function highlight(text: string, grammer: LanguageDefinition, language?: * nested tokens, the function is called recursively on each of these tokens. This method could be useful in other * contexts as well, as a very crude parser. * - * @param text A string with the code to be highlighted. - * @param grammar An object containing the tokens to use. Usually a language definition like + * @param text A string with the code to be highlighted. + * @param grammar An object containing the tokens to use. Usually a language definition like * Prism.languages.markup * @returns An array of strings, tokens (class Prism.Token) and other arrays. */ diff --git a/types/prismjs/prismjs-tests.ts b/types/prismjs/prismjs-tests.ts index bf1bdc859a..fea94ac713 100644 --- a/types/prismjs/prismjs-tests.ts +++ b/types/prismjs/prismjs-tests.ts @@ -1,10 +1,16 @@ const element = document.createElement("code"); +const container = document.querySelector("div"); const callback = (element: Element) => console.log(element); Prism.highlightElement(element, false, callback); Prism.highlightElement(element, false); +Prism.highlightElement(element); Prism.highlightAll(true, callback); Prism.highlightAll(true); +Prism.highlightAll(); +if (container) { + Prism.highlightAllUnder(container); +} const hookCallback: Prism.HookCallback = env => null; Prism.hooks.add("before-highlightall", hookCallback); diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index ee88557e15..b89d41bbba 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -200,6 +200,8 @@ export interface SetCookie { name: string; /** The cookie value. */ value: string; + /** The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. */ + url?: string; /** The cookie domain. */ domain?: string; /** The cookie path. */ @@ -551,19 +553,19 @@ export type HttpMethod = | "OPTIONS"; export type ResourceType = - | "Document" - | "Stylesheet" - | "Image" - | "Media" - | "Font" - | "Script" - | "TextTrack" - | "XHR" - | "Fetch" - | "EventSource" - | "WebSocket" - | "Manifest" - | "Other"; + | "document" + | "stylesheet" + | "image" + | "media" + | "font" + | "script" + | "texttrack" + | "xhr" + | "fetch" + | "eventsource" + | "websocket" + | "manifest" + | "other"; export interface Overrides { url?: string; diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 7347b17bf0..309a30f2b0 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for qlik-engineapi 12.34 -// Project: http://help.qlik.com/en-US/sense-developer/September2017/Subsystems/EngineAPI/Content/introducing-engine-API.htm +// Type definitions for qlik-engineapi 12.67 +// Project: http://help.qlik.com/en-US/sense-developer/November2017/Subsystems/EngineAPI/Content/introducing-engine-API.htm // Definitions by: Konrad Mattheis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -2402,7 +2402,7 @@ declare namespace EngineAPI { * This class describes all the methods that apply at app level. * The handle member in the JSON request for all methods listed in this section is the handle of the app. */ - interface IApp { + interface IApp extends enigmaJS.IGeneratedAPI { global: IGlobal; /** @@ -2984,6 +2984,13 @@ declare namespace EngineAPI { */ getFieldDescription(qFieldName: string): Promise; + /** + * Fetches the Expression behind a Field that is declared with DECLARE FIELD DEFINITIO + * @param qReadableName: name of a Field that is declared with DECLARE FIELD DEFINITION + * @returns qname wich contains the expression + */ + getFieldOnTheFlyByName(qReadableName: string): Promise<{qName: string}>; + /** * Retrieves the description of a field. * @param qFieldName - Name of the field. >> This parameter is mandatory. @@ -7150,6 +7157,21 @@ declare namespace EngineAPI { */ getBaseBNFHash(qBnfType: BnfType): Promise<{ qBnfHash: string }>; + /** + * Gets the current Backus-Naur Form (BNF) grammar of the Qlik engine scripting language, + * as well as a string hash calculated from that grammar. The BNF rules define the syntax + * for the script statements and the script or chart functions. If the hash changes between + * subsequent calls to this method, this indicates that the BNF has changed. + * + * In the Qlik engine grammars, a token is a string of one or more characters that is significant as a group. + * For example, a token could be a function name, a number, a letter, a parenthesis, and so on. + * @param qBnfType The type of grammar to return: + * S: returns the script statements and the script functions. + * E: returns the chart functions. + * @returns qBnfDefs and qBnfHash + */ + getBaseBNFString(qBnfType: BnfType): Promise<{qBnfDefs: IBNFDef, qBnfHash: string}>; + /** * Get a Config Object * @returns A Promise qConfig @@ -9108,8 +9130,7 @@ declare namespace EngineAPI { /** * SelectionListObject width extend GenericObject */ - interface ISelectionListObject extends IGenericObject { - getLayout(): Promise; + interface ISelectionListObject extends IGenericObjectPrototype { } interface IApp { @@ -9171,8 +9192,7 @@ declare namespace EngineAPI { /** * BookmarkListObject width extend GenericObject */ - interface IBookmarkListObject extends IGenericObject { - getLayout(): Promise; + interface IBookmarkListObject extends IGenericObjectPrototype { } interface IApp { @@ -9234,8 +9254,7 @@ declare namespace EngineAPI { /** * IMeassureListObject */ - interface IMeassureListObject extends IGenericObject { - getLayout(): Promise; + interface IMeassureListObject extends IGenericObjectPrototype { } interface IApp { @@ -9302,8 +9321,7 @@ declare namespace EngineAPI { qData: any; } - interface IDimensionListObject extends IGenericObject { - getLayout(): Promise; + interface IDimensionListObject extends IGenericObjectPrototype { } interface IApp { @@ -9380,15 +9398,15 @@ declare namespace EngineAPI { /** * VariableListObject... */ - interface IVariableListObject { + interface IVariableList { qItems: INxVariableListItem[]; } /** * GenericVariableLayout width extend GenericObjectLayout */ - interface IGenericVariableLayout extends IGenericObjectLayout { - qVariableListObject: IVariableListObject; + interface IGenericVariableListLayout extends IGenericBaseLayout { + qVariableListObject: IVariableList; } /** @@ -9426,8 +9444,7 @@ declare namespace EngineAPI { /** * VariableListObject width extend GenericObject */ - interface IVariableListObject extends IGenericObject { - getLayout(): Promise; + interface IVariableListObject extends IGenericObjectPrototype { } interface IApp { @@ -9442,23 +9459,13 @@ declare namespace EngineAPI { /** * FieldListObject... */ - interface IFieldListObject { + interface IFieldList { /** * NxFieldDescription[] */ qItems: INxFieldDescription[]; } - /** - * GenericFieldLayout width extend GenericObjectLayout - */ - interface IGenericFieldLayout extends IGenericObjectLayout { - /** - * FieldListObject... - */ - qFieldListObject: IFieldListObject; - } - /** * GenericFieldListProperties width extend GenericProperties */ @@ -9673,6 +9680,22 @@ declare namespace EngineAPI { qShowImplicit?: boolean; } + /** + * GenericFieldLayout width extend GenericObjectLayout + */ + interface IGenericFieldLayout extends IGenericBaseLayout { + /** + * FieldListObject... + */ + qFieldListObject: IFieldList; + } + + /** + * FieldListObject width extend GenericObject + */ + interface IFieldListObject extends IGenericObjectPrototype { + } + interface IApp { createObject(qProp: IGenericFieldListProperties): Promise; createSessionObject(qProp: IGenericFieldListProperties): Promise; diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 6325913519..a996babf30 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -2,8 +2,11 @@ // Project: https://github.com/quilljs/quill/ // Definitions by: Sumit // Guillaume +// James Garbutt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { Blot } from 'parchment/dist/src/blot/abstract/blot'; + /** * A stricter type definition would be: * @@ -56,7 +59,9 @@ export interface QuillOptionsStatic { } export interface BoundsStatic { + bottom: number; left: number; + right: number; top: number; height: number; width: number; @@ -136,6 +141,7 @@ export class Quill implements EventEmitter { */ root: HTMLDivElement; clipboard: ClipboardStatic; + scroll: Blot; constructor(container: string | Element, options?: QuillOptionsStatic); deleteText(index: number, length: number, source?: Sources): DeltaStatic; disable(): void; diff --git a/types/quill/package.json b/types/quill/package.json new file mode 100644 index 0000000000..85d0ed05d1 --- /dev/null +++ b/types/quill/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "parchment": "^1.1.2" + } +} diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index 142c821ffa..f907092ed1 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -1,4 +1,5 @@ import { Quill, Delta, DeltaStatic, RangeStatic, StringMap } from 'quill'; +import { Blot } from 'parchment/src/blot/abstract/blot'; function test_quill() { const quillEditor = new Quill('#editor', { @@ -10,6 +11,11 @@ function test_quill() { }); } +function test_scroll() { + const quillEditor = new Quill('#editor'); + const blot: Blot = quillEditor.scroll; +} + function test_deleteText() { const quillEditor = new Quill('#editor'); quillEditor.deleteText(0, 10); diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9d1683fbbc..be97f3ee32 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -740,8 +740,8 @@ declare namespace R { * Given a function that generates a key, turns a list of objects into an object indexing the objects * by the given key. */ - indexBy(fn: (a: T) => string, list: T[]): U; - indexBy(fn: (a: T) => string): (list: T[]) => U; + indexBy(fn: (a: T) => string, list: T[]): { [key: string]: T }; + indexBy(fn: (a: T) => string): (list: T[]) => { [key: string]: T }; /** * Returns the position of the first occurrence of an item in an array @@ -1454,9 +1454,8 @@ declare namespace R { /** * Returns a function that when supplied an object returns the indicated property of that object, if it exists. - * Note: TS1.9 # replace any by dictionary */ - prop

(p: P, obj: Record): T; + prop

(p: P, obj: T): T[P]; prop

(p: P): (obj: Record) => T; /** diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 426bb63471..1315ced585 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -678,10 +678,19 @@ interface Obj { }; (() => { - const list = [{id: "xyz", title: "A"}, {id: "abc", title: "B"}]; - const a1 = R.indexBy(R.prop("id"), list); - const a2 = R.indexBy(R.prop("id"))(list); + interface Book { + id: string; + title: string; + } + const list: Book[] = [{id: "xyz", title: "A"}, {id: "abc", title: "B"}]; + const a1 = R.indexBy(R.prop("id"), list); + const a2 = R.indexBy(R.prop("id"))(list); const a3 = R.indexBy<{ id: string }>(R.prop("id"))(list); + + const titlesIndexedByTitles: { [k: string]: string } = R.pipe( + R.map((x: Book) => x.title), + R.indexBy(x => x), + )(list); }); () => { @@ -1535,6 +1544,16 @@ class Rectangle { () => { const x: number = R.prop("x", {x: 100}); // => 100 + const obj = { + str: 'string', + num: 5, + }; + + const strVal: string = R.prop('str', obj); // => 'string' + const numVal: number = R.prop('num', obj); // => 5 + + const strValCur: string = R.prop('str')(obj); // => 'string' + const numValCur: number = R.prop('num')(obj); // => 5 }; () => { diff --git a/types/random-seed/index.d.ts b/types/random-seed/index.d.ts index d90016b83d..6ac278b467 100644 --- a/types/random-seed/index.d.ts +++ b/types/random-seed/index.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface RandomSeed { + (range: number): number; range(range: number): number; random(): number; floatBetween(min: number, max: number): number; diff --git a/types/random-seed/random-seed-tests.ts b/types/random-seed/random-seed-tests.ts index 9975608d8b..4c6f07dc28 100644 --- a/types/random-seed/random-seed-tests.ts +++ b/types/random-seed/random-seed-tests.ts @@ -9,9 +9,18 @@ const seed = 'My Secret String Value'; const rand2 = create(seed); // API +rand1(50); rand1.addEntropy(); rand1.random(); rand1.range(100); rand1.intBetween(0, 10); rand1.floatBetween(0, 1); rand1.seed("new seed"); + +rand2(50); +rand2.addEntropy(); +rand2.random(); +rand2.range(100); +rand2.intBetween(0, 10); +rand2.floatBetween(0, 1); +rand2.seed("new seed"); diff --git a/types/rangy/index.d.ts b/types/rangy/index.d.ts index f140895cf6..e28a4d7b1c 100644 --- a/types/rangy/index.d.ts +++ b/types/rangy/index.d.ts @@ -60,7 +60,7 @@ interface RangyStatic { createRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; createRangyRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; getNativeSelection(win?:Window):Selection; - getSelection():RangySelection; + getSelection(doc?:Document|Window|HTMLIFrameElement):RangySelection; addInitListener(listener:(rangy:RangyStatic) => void):any; shim():any; createMissingNativeApi():any; diff --git a/types/raspi-board/index.d.ts b/types/raspi-board/index.d.ts new file mode 100644 index 0000000000..a244577c2b --- /dev/null +++ b/types/raspi-board/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for raspi-board 5.0 +// Project: https://github.com/nebrius/raspi-board +// Definitions by: Bryan Hughes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export const VERSION_1_MODEL_A = "rpi1_a"; +export const VERSION_1_MODEL_B_REV_1 = "rpi1_b1"; +export const VERSION_1_MODEL_B_REV_2 = "rpi1_b2"; +export const VERSION_1_MODEL_B_PLUS = "rpi1_bplus"; +export const VERSION_1_MODEL_A_PLUS = "rpi1_aplus"; +export const VERSION_1_MODEL_ZERO = "rpi1_zero"; +export const VERSION_1_MODEL_ZERO_W = "rpi1_zerow"; +export const VERSION_2_MODEL_B = "rpi2_b"; +export const VERSION_3_MODEL_B = "rpi3_b"; +export const VERSION_UNKNOWN = "unknown"; +export interface PinInfo { + pins: string[]; + peripherals: string[]; + gpio: number; +} +export function getBoardRevision(): string; +export function getPins(): { + [wiringpi: number]: PinInfo; +}; +export function getPinNumber(alias: string | number): number | null; +export function getGpioNumber(alias: string | number): number | null; diff --git a/types/raspi-board/raspi-board-tests.ts b/types/raspi-board/raspi-board-tests.ts new file mode 100644 index 0000000000..23195168cf --- /dev/null +++ b/types/raspi-board/raspi-board-tests.ts @@ -0,0 +1,6 @@ +import { getBoardRevision, getPins, getPinNumber, getGpioNumber } from 'raspi-board'; + +getBoardRevision(); +getPins(); +getPinNumber('GPIO18'); +getGpioNumber('GPIO18'); diff --git a/types/raspi-board/tsconfig.json b/types/raspi-board/tsconfig.json new file mode 100644 index 0000000000..a55a514726 --- /dev/null +++ b/types/raspi-board/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "raspi-board-tests.ts" + ] +} \ No newline at end of file diff --git a/types/raspi-board/tslint.json b/types/raspi-board/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/raspi-board/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/raspi-peripheral/index.d.ts b/types/raspi-peripheral/index.d.ts new file mode 100644 index 0000000000..d52ed3ec6c --- /dev/null +++ b/types/raspi-peripheral/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for raspi-peripheral 2.0 +// Project: https://github.com/nebrius/raspi-peripheral +// Definitions by: Bryan Hughes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// +import { EventEmitter } from 'events'; +export class Peripheral extends EventEmitter { + private _alive; + readonly alive: boolean; + private _pins; + readonly pins: number[]; + constructor(pins: string | number | Array); + destroy(): void; + validateAlive(): void; +} diff --git a/types/raspi-peripheral/raspi-peripheral-tests.ts b/types/raspi-peripheral/raspi-peripheral-tests.ts new file mode 100644 index 0000000000..dc16f863a2 --- /dev/null +++ b/types/raspi-peripheral/raspi-peripheral-tests.ts @@ -0,0 +1,5 @@ +import { Peripheral } from 'raspi-peripheral'; + +const myPeripheral = new Peripheral('GPIO2'); +myPeripheral.alive; +myPeripheral.pins.filter((pin) => true); diff --git a/types/raspi-peripheral/tsconfig.json b/types/raspi-peripheral/tsconfig.json new file mode 100644 index 0000000000..4b24a67971 --- /dev/null +++ b/types/raspi-peripheral/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "raspi-peripheral-tests.ts" + ] +} \ No newline at end of file diff --git a/types/raspi-peripheral/tslint.json b/types/raspi-peripheral/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/raspi-peripheral/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/raspi/index.d.ts b/types/raspi/index.d.ts new file mode 100644 index 0000000000..9df97fe3cc --- /dev/null +++ b/types/raspi/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for raspi 5.0 +// Project: https://github.com/nebrius/raspi +// Definitions by: Bryan Hughes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export function init(cb: () => void): void; diff --git a/types/raspi/raspi-tests.ts b/types/raspi/raspi-tests.ts new file mode 100644 index 0000000000..705aeacc31 --- /dev/null +++ b/types/raspi/raspi-tests.ts @@ -0,0 +1,3 @@ +import { init } from 'raspi'; + +init(() => {}); diff --git a/types/raspi/tsconfig.json b/types/raspi/tsconfig.json new file mode 100644 index 0000000000..6906d607cf --- /dev/null +++ b/types/raspi/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "raspi-tests.ts" + ] +} \ No newline at end of file diff --git a/types/raspi/tslint.json b/types/raspi/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/raspi/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/rbac-a/index.d.ts b/types/rbac-a/index.d.ts new file mode 100644 index 0000000000..822a3f7cee --- /dev/null +++ b/types/rbac-a/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for rbac-a 0.2 +// Project: https://github.com/yanickrochon/rbac-a#readme +// Definitions by: Tomek Łaziuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { + EventEmitter, +} from "events"; + +export interface Roles { + [_: string]: number | Roles; +} + +export class Provider { + /** + * Return all the roles available for the given user. The return value + * must be an object, recursively defining the associated roles for the + * specified user. Return an empty object if user has no roles. + * Ex: { + * "role1": { + * "role1.1": null, + * "role1.2": { ... }, + * ... + * }, + * "secondary": ..., + * ... + * } + * The method mey return a promise resolving with the + * expected return value. + */ + getRoles(user: any): Roles | Promise; + /** + * Return all permissions for the specified role. The return value + * must be an array. Return an empty array if role is missing or + * no permission for the specified role. + * Ex: ['permission1', 'permission2', ... ] + * The method mey return a promise resolving with the + * expected return value. + */ + getPermission(role: string): string[] | Promise; + /** + * Return all attributes for the specified role. The return value must + * be an array. Return an empty array if role is missing or if no + * attributes for the specified role. + * Ex: ['attribute1', 'attribute2', ... ] + * The method mey return a promise resolving with the + * expected return value. + */ + getAttributes(role: string): string[] | Promise; +} + +export type AttributeFunction = (user: any, role: string, params: object) => any; + +/** + * Attributes Manager + * This class encapsulate attributes definition and validation. + * Usage + * var roleValid = attributesManager.validate(attribute, user, role, params); + */ +export class AttributesManager { + protected _attributes: { [_: string]: AttributeFunction }; + /** Define an attribute. The returned value is self for chaining. */ + set(attribute: AttributeFunction): this; + /** + * Undefine an attribute, by name or function and return removed + * attribute function if one was found. + */ + remove(attribute: string | AttributeFunction): AttributeFunction; + /** + * Validate the attribute with the specified user, role and parameters. + * The method will return a truthy value if the attribute valid, or a + * falsy otherwise. + * The method may also return a promise resolivng to the expected returne + * value, or reject. A rejected promise should be considered falsy. + * If the specified attribute does not exist, false is returned. + */ + validate(attribute: string, user: any, role: string, params: object): any; +} + +export class RBAC

extends EventEmitter { + readonly provider: P; + readonly attributes: AM; + constructor(opts: { provider: P, attributes?: AM }); + /** + * Check the user for the given permissions. The method will return + * a Promise resolving with a number. If the user has sufficient + * access to the specified permissions, the promise should resolve + * with a positive, non-zero value, or with NaN otherwise. If the + * Promise is rejected, it should be considered as if the user has + * insufficient access to the specified ressources. + */ + check(user: any, permission: string | string[], params?: object): Promise; +} + +export const Providers: { + /** Basic JSON permissions provider */ + JsonProvider: { new(roles: object): Provider }; +}; diff --git a/types/rbac-a/lib/attributes-manager.d.ts b/types/rbac-a/lib/attributes-manager.d.ts new file mode 100644 index 0000000000..619370c6a1 --- /dev/null +++ b/types/rbac-a/lib/attributes-manager.d.ts @@ -0,0 +1,2 @@ +import { AttributesManager } from ".."; +export = AttributesManager; diff --git a/types/rbac-a/lib/provider.d.ts b/types/rbac-a/lib/provider.d.ts new file mode 100644 index 0000000000..9c94f32f1d --- /dev/null +++ b/types/rbac-a/lib/provider.d.ts @@ -0,0 +1,2 @@ +import { Provider } from ".."; +export = Provider; diff --git a/types/rbac-a/lib/rbac.d.ts b/types/rbac-a/lib/rbac.d.ts new file mode 100644 index 0000000000..fae3c7321b --- /dev/null +++ b/types/rbac-a/lib/rbac.d.ts @@ -0,0 +1,2 @@ +import { RBAC } from ".."; +export = RBAC; diff --git a/types/rbac-a/rbac-a-tests.ts b/types/rbac-a/rbac-a-tests.ts new file mode 100644 index 0000000000..da783a2617 --- /dev/null +++ b/types/rbac-a/rbac-a-tests.ts @@ -0,0 +1,40 @@ +import { + Provider, + RBAC, +} from "rbac-a"; + +class CustomProvider extends Provider { } + +const rbac = new RBAC({ + provider: new CustomProvider() +}); + +const user = "ExampleUser"; + +rbac.on('error', (err) => { + console.error('Error while checking $s/%s', err.role, err.user); + console.error(err.stack); +}); + +rbac.check(user, 'create').then((allowed) => { + if (allowed) { + console.log('User can create!'); + } else { + console.log('User cannot create.'); + console.info('Please contact your system admin for more information'); + } +}).catch((err) => { + console.error(err && err.stack || err || 'ERROR'); +}); + +// specify attributes arguments +rbac.check(user, 'edit', { time: Date.now() }).then((allowed) => { + if (allowed) { + console.log('User can edit!'); + } else { + console.log('User cannot edit.'); + console.info('Please contact your system admin for more information'); + } +}).catch((err) => { + console.error(err && err.stack || err || 'ERROR'); +}); diff --git a/types/rbac-a/tsconfig.json b/types/rbac-a/tsconfig.json new file mode 100644 index 0000000000..be60bf248e --- /dev/null +++ b/types/rbac-a/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/attributes-manager.d.ts", + "lib/provider.d.ts", + "lib/rbac.d.ts", + "rbac-a-tests.ts" + ] +} diff --git a/types/rbac-a/tslint.json b/types/rbac-a/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rbac-a/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-autosuggest/README.md b/types/react-autosuggest/README.md new file mode 100644 index 0000000000..44ff83ecc5 --- /dev/null +++ b/types/react-autosuggest/README.md @@ -0,0 +1,28 @@ +# react-autosuggest usage notes + +The definition uses generics for stronger typing. Read the [TypeScript deep dive on JSX Generic components](https://basarat.gitbooks.io/typescript/docs/jsx/tsx.html#react-jsx-tip-generic-components) for details on consuming these type definitions. + +## Example + +```jsx +import * as Autosuggest from 'react-autosuggest' +interface Language { + name: string + year: number +} + +const LanguageAutosuggest = Autosuggest as { new (): Autosuggest } + + +``` + +Find multiple full examples in `react-autosuggest-tests.tsx` diff --git a/types/react-autosuggest/index.d.ts b/types/react-autosuggest/index.d.ts index b1f080efe5..444753bd54 100644 --- a/types/react-autosuggest/index.d.ts +++ b/types/react-autosuggest/index.d.ts @@ -5,84 +5,200 @@ // Robert Essig // Terry Bayne // Christopher Deutsch +// Kevin Ross // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from 'react'; -declare class Autosuggest extends React.Component {} +declare class Autosuggest extends React.Component> {} export = Autosuggest; declare namespace Autosuggest { - interface SuggestionsFetchRequest { - value: string; - reason: 'input-changed' | 'input-focused' | 'escape-pressed' | 'suggestions-revealed' | 'suggestion-selected'; - } + /** + * Utilies types based on: + * https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458 + */ - interface InputValues { - value: string; - valueBeforeUpDown?: string; - } + /** @internal */ + type Diff = ({ [P in T]: P } & + { [P in U]: never } & { [x: string]: never })[T]; - interface RenderSuggestionParams { - query: string; - isHighlighted: boolean; - } + /** @internal */ + type Omit = Pick>; - interface SuggestionHighlightedParams { - suggestion: any; - } + interface SuggestionsFetchRequestedParams { + value: string; + reason: + | 'input-changed' + | 'input-focused' + | 'escape-pressed' + | 'suggestions-revealed' + | 'suggestion-selected'; + } - interface ChangeEvent { - newValue: string; - method: 'down' | 'up' | 'escape' | 'enter' | 'click' | 'type'; - } + interface RenderSuggestionParams { + query: string; + isHighlighted: boolean; + } - interface BlurEvent { - highlightedSuggestion: any; - } + interface SuggestionHighlightedParams { + suggestion: any; + } - interface InputProps extends React.InputHTMLAttributes { - value: string; - onChange(event: React.FormEvent, params?: ChangeEvent): void; - onBlur?(event: React.FormEvent, params?: BlurEvent): void; - [key: string]: any; - } + interface ChangeEvent { + newValue: string; + method: 'down' | 'up' | 'escape' | 'enter' | 'click' | 'type'; + } - interface SuggestionSelectedEventData { - suggestion: TSuggestion; - suggestionValue: string; - suggestionIndex: number; - sectionIndex: number | null; - method: 'click' | 'enter'; - } + interface BlurEvent { + highlightedSuggestion: TSuggestion; + } - type ThemeKey = 'container' | 'containerOpen' | 'input' | 'inputOpen' | 'inputFocused' | 'suggestionsContainer' | - 'suggestionsContainerOpen' | 'suggestionsList' | 'suggestion' | 'suggestionFirst' | 'suggestionHighlighted' | - 'sectionContainer' | 'sectionContainerFirst' | 'sectionTitle'; + interface InputProps + extends Omit, 'onChange' | 'onBlur'> { + onChange(event: React.FormEvent, params?: ChangeEvent): void; + onBlur?(event: React.FormEvent, params?: BlurEvent): void; + value: string; + [key: string]: any; + } - type Theme = Record | Partial>; + interface SuggestionSelectedEventData { + suggestion: TSuggestion; + suggestionValue: string; + suggestionIndex: number; + sectionIndex: number | null; + method: 'click' | 'enter'; + } - interface AutosuggestProps extends React.Props { - suggestions: any[]; - onSuggestionsFetchRequested(request: SuggestionsFetchRequest): void; - onSuggestionsClearRequested?(): void; - getSuggestionValue(suggestion: any): any; - renderSuggestion(suggestion: any, params: RenderSuggestionParams): JSX.Element; - inputProps: InputProps; - onSuggestionSelected?(event: React.FormEvent, data: SuggestionSelectedEventData): void; - onSuggestionHighlighted?(params: SuggestionHighlightedParams): void; - shouldRenderSuggestions?(value: string): boolean; - alwaysRenderSuggestions?: boolean; - highlightFirstSuggestion?: boolean; - focusInputOnSuggestionClick?: boolean; - multiSection?: boolean; - renderSectionTitle?(section: any): JSX.Element; - getSectionSuggestions?(section: any): any[]; - renderInputComponent?(inputProps: InputProps): JSX.Element; - renderSuggestionsContainer?(containerProps: any, children: any, query: string): JSX.Element; - theme?: Theme; - id?: string; - } + type ThemeKey = + | 'container' + | 'containerOpen' + | 'input' + | 'inputOpen' + | 'inputFocused' + | 'suggestionsContainer' + | 'suggestionsContainerOpen' + | 'suggestionsList' + | 'suggestion' + | 'suggestionFirst' + | 'suggestionHighlighted' + | 'sectionContainer' + | 'sectionContainerFirst' + | 'sectionTitle'; + + type Theme = + | Record + | Partial>; + + interface RenderSuggestionsContainerParams { + containerProps: { + id: string; + key: string; + ref: any; + style: any; + }; + children: React.ReactNode; + query: string; + } + + // types for functions - allowing reuse externally - e.g. as props and bound in the constructor + type GetSectionSuggestions = (section: any) => TSuggestion[]; + type GetSuggestionValue = (suggestion: TSuggestion) => string; + type OnSuggestionHighlighted = (params: SuggestionHighlightedParams) => void; + type SuggestionsFetchRequested = (request: SuggestionsFetchRequestedParams) => void; + type OnSuggestionsClearRequested = () => void; + type OnSuggestionSelected = ( + event: React.FormEvent, + data: SuggestionSelectedEventData, + ) => void; + type RenderInputComponent = (inputProps: InputProps) => React.ReactNode; + type RenderSuggestionsContainer = (params: RenderSuggestionsContainerParams) => React.ReactNode; + type RenderSectionTitle = (section: any) => React.ReactNode; + type RenderSuggestion = ( + suggestion: TSuggestion, + params: RenderSuggestionParams, + ) => React.ReactNode; + type ShouldRenderSuggestions = (value: string) => boolean; + + interface AutosuggestProps { + /** + * Set it to true if you'd like to render suggestions even when the input is not focused. + */ + alwaysRenderSuggestions?: boolean; + /** + * Set it to false if you don't want Autosuggest to keep the input focused when suggestions are clicked/tapped. + */ + focusInputOnSuggestionClick?: boolean; + /** + * Implement it to teach Autosuggest where to find the suggestions for every section. + */ + getSectionSuggestions?: GetSectionSuggestions; + /** + * Implement it to teach Autosuggest what should be the input value when suggestion is clicked. + */ + getSuggestionValue: GetSuggestionValue; + /** + * Set it to true if you'd like Autosuggest to automatically highlight the first suggestion. + */ + highlightFirstSuggestion?: boolean; + /** + * Use it only if you have multiple Autosuggest components on a page. + */ + id?: string; + /** + * Pass through arbitrary props to the input. It must contain at least value and onChange. + */ + inputProps: InputProps; + /** + * Set it to true if you'd like to display suggestions in multiple sections (with optional titles). + */ + multiSection?: boolean; + /** + * Will be called every time the highlighted suggestion changes. + */ + onSuggestionHighlighted?: OnSuggestionHighlighted; + /** + * Will be called every time you need to recalculate suggestions. + */ + onSuggestionsFetchRequested: SuggestionsFetchRequested; + /** + * Will be called every time you need to set suggestions to []. + */ + onSuggestionsClearRequested?: OnSuggestionsClearRequested; + /** + * Will be called every time suggestion is selected via mouse or keyboard. + */ + onSuggestionSelected?: OnSuggestionSelected; + /** + * Use it only if you need to customize the rendering of the input. + */ + renderInputComponent?: RenderInputComponent; + /** + * Use it if you want to customize things inside the suggestions container beyond rendering the suggestions themselves. + */ + renderSuggestionsContainer?: RenderSuggestionsContainer; + /** + * Use your imagination to define how section titles are rendered. + */ + renderSectionTitle?: RenderSectionTitle; + /** + * Use your imagination to define how suggestions are rendered. + */ + renderSuggestion: RenderSuggestion; + /** + * When the input is focused, Autosuggest will consult this function when to render suggestions. + * Use it, for example, if you want to display suggestions when input value is at least 2 characters long. + */ + shouldRenderSuggestions?: ShouldRenderSuggestions; + /** + * These are the suggestions that will be displayed. Items can take an arbitrary shape. + */ + suggestions: TSuggestion[]; + /** + * Use your imagination to style the Autosuggest. + */ + theme?: Theme; + } } diff --git a/types/react-autosuggest/react-autosuggest-tests.tsx b/types/react-autosuggest/react-autosuggest-tests.tsx index 23841519e4..3747e8457b 100644 --- a/types/react-autosuggest/react-autosuggest-tests.tsx +++ b/types/react-autosuggest/react-autosuggest-tests.tsx @@ -90,6 +90,132 @@ export class ReactAutosuggestBasicTest extends React.Component { }; return ; + } + + protected onSuggestionsSelected(event: React.FormEvent, data: Autosuggest.SuggestionSelectedEventData): void { + alert(`Selected language is ${data.suggestion.name} (${data.suggestion.year}).`); + } + + protected renderSuggestion(suggestion: Language, params: Autosuggest.RenderSuggestionParams): JSX.Element { + const className = params.isHighlighted ? "highlighted" : undefined; + return {suggestion.name}; + } + // endregion region Event handlers + protected onChange(event: React.FormEvent, {newValue, method}: any): void { + this.setState({value: newValue}); + } + + protected onSuggestionsFetchRequested({value}: any): void { + this.setState({ + suggestions: this.getSuggestions(value) + }); + } + // endregion region Helper methods + protected getSuggestions(value: string): Language[] { + const escapedValue = escapeRegexCharacters(value.trim()); + + if (escapedValue === '') { + return []; + } + + const regex = new RegExp('^' + escapedValue, 'i'); + + return ReactAutosuggestBasicTest + .languages + .filter(language => regex.test(language.name)); + } + + protected getSuggestionValue(suggestion: Language): string { return suggestion.name; } + // endregion +} + +const LanguageAutosuggest = Autosuggest as { new (): Autosuggest }; + +export class ReactAutosuggestTypedTest extends React.Component { + // region Fields + static languages: Language[] = [ + { + name: 'C', + year: 1972 + }, { + name: 'C#', + year: 2000 + }, { + name: 'C++', + year: 1983 + }, { + name: 'Clojure', + year: 2007 + }, { + name: 'Elm', + year: 2012 + }, { + name: 'Go', + year: 2009 + }, { + name: 'Haskell', + year: 1990 + }, { + name: 'Java', + year: 1995 + }, { + name: 'Javascript', + year: 1995 + }, { + name: 'Perl', + year: 1987 + }, { + name: 'PHP', + year: 1995 + }, { + name: 'Python', + year: 1991 + }, { + name: 'Ruby', + year: 1995 + }, { + name: 'Scala', + year: 2003 + } + ]; + // endregion region Constructor + constructor(props: any) { + super(props); + + this.state = { + value: '', + suggestions: this.getSuggestions('') + }; + } + // endregion region Rendering methods + render(): JSX.Element { + const {value, suggestions} = this.state; + const inputProps = { + placeholder: `Type 'c'`, + value, + onChange: this + .onChange + .bind(this) + }; + + const theme = { + input: 'themed-input-class', + container: 'themed-container-class', + suggestionFocused: 'active', + sectionTitle: { color: 'blue' } + }; + + return { .bind(this) }; - return { return {section.title}; } - protected renderInputComponent(inputProps: Autosuggest.InputProps): JSX.Element { + protected renderInputComponent(inputProps: Autosuggest.InputProps): JSX.Element { return (

@@ -280,7 +406,7 @@ export class ReactAutosuggestMultipleTest extends React.Component { ); } - protected renderSuggestionsContainer(containerProps: any, children: any, query: string): JSX.Element { + protected renderSuggestionsContainer({containerProps, children, query}: Autosuggest.RenderSuggestionsContainerParams): JSX.Element { return (
{children} @@ -345,6 +471,8 @@ interface Person { twitter: string; } +const PersonAutosuggest = Autosuggest as { new (): Autosuggest }; + export class ReactAutosuggestCustomTest extends React.Component { // region Fields static people: Person[] = [ @@ -386,7 +514,7 @@ export class ReactAutosuggestCustomTest extends React.Component { .bind(this) }; - return +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export namespace Subscriber { + interface DefaultProps { + quiet: boolean; + } + interface Props extends Partial { + channel: string; + children?: ((state: T) => React.ReactNode); + } +} + +export namespace Broadcast { + interface DefaultProps { + compareValues: (prevValue: T, nextValue: T) => boolean; + } + interface Props extends Partial> { + channel: string; + children: React.ReactNode; + value: T; + } +} + +export class Broadcast extends React.Component, any> { } +export class Subscriber extends React.Component, any> { } diff --git a/types/react-broadcast/react-broadcast-tests.tsx b/types/react-broadcast/react-broadcast-tests.tsx new file mode 100644 index 0000000000..6f3466e729 --- /dev/null +++ b/types/react-broadcast/react-broadcast-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import { Broadcast, Subscriber } from 'react-broadcast'; + +class ExampleOfUsingReactBroadcast extends React.Component { + render() { + const value = 42; + return ( + +
+ + {state =>
{state}
} +
+
+
+ ); + } +} diff --git a/types/react-broadcast/tsconfig.json b/types/react-broadcast/tsconfig.json new file mode 100644 index 0000000000..270151cc33 --- /dev/null +++ b/types/react-broadcast/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "jsx": "react", + "strictNullChecks": true, + "strictFunctionTypes": false, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": ["index.d.ts", "react-broadcast-tests.tsx"] +} diff --git a/types/react-broadcast/tslint.json b/types/react-broadcast/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/react-broadcast/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-native-elements/README.md b/types/react-native-elements/README.md deleted file mode 100644 index 9e3975ecdf..0000000000 --- a/types/react-native-elements/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# [React Native Elements](https://github.com/react-native-training/react-native-elements) - -### Component Checklist - -- [x] Buttons -- [x] Badge -- [x] Social Icons / Social Icon Buttons -- [x] Icons -- [x] Side Menu -- [x] Form Elements -- [x] SearchBar -- [x] ButtonGroup -- [x] CheckBoxes -- [x] List Element -- [x] Tab Bar Component -- [x] HTML style headings -- [x] Card component -- [x] Pricing Component -- [x] Grid Component -- [x] Slider Component -- [x] Tile Component -- [x] Avatar Component -- [x] Rating Component -- [x] SwipeDeck Component -- [x] Header Component -- [x] Divider diff --git a/types/react-native-elements/index.d.ts b/types/react-native-elements/index.d.ts deleted file mode 100644 index 821e9b65e7..0000000000 --- a/types/react-native-elements/index.d.ts +++ /dev/null @@ -1,2265 +0,0 @@ -// Type definitions for react-native-elements 0.16 -// Project: https://github.com/react-native-training/react-native-elements#readme -// Definitions by: Kyle Roach -// Ifiok Jr. -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import * as React from 'react'; -import { - ViewStyle, - TextStyle, - Image, - ImageStyle, - ImageURISource, - TouchableWithoutFeedbackProps, - TouchableHighlightProperties, - TouchableOpacityProperties, - ViewProperties, - TextInputProperties, - TextInput, - StatusBarProperties, - KeyboardType, - KeyboardTypeIOS, - StyleProp, - GestureResponderEvent, - Animated, - TransformsStyle -} from 'react-native'; -import TabNavigator from 'react-native-tab-navigator'; - -/** - * Supports auto complete for most used types as well as any other string type. - */ -export type IconType = - | 'material' - | 'material-community' - | 'simple-line-icon' - | 'zocial' - | 'font-awesome' - | 'octicon' - | 'ionicon' - | 'foundation' - | 'evilicon' - | 'entypo' - | string; - -export interface IconObject { - name?: string; - color?: string; - size?: number; - type?: IconType; - style?: StyleProp; -} - -export interface AvatarIcon extends IconObject { - iconStyle?: StyleProp; -} - -export interface TextProps { - /** - * font size 40 - */ - h1?: boolean; - - /** - * font size 34 - */ - h2?: boolean; - - /** - * font size 28 - */ - h3?: boolean; - - /** - * font size 22 - */ - h4?: boolean; - - /** - * font family name - */ - fontFamily?: string; - - /** - * Additional styling for Text - */ - style?: StyleProp; -} - -/** - * HTML Style Headings - * - * @see https://react-native-training.github.io/react-native-elements/API/HTML_style_headings/ - */ -export class Text extends React.Component {} - -export interface AvatarProps { - /** - * Component for enclosing element (eg: TouchableHighlight, View, etc) - * - * @default TouchableOpacity - */ - component?: React.ComponentClass; - - /** - * Width for the Avatar - * - * @default 34 - */ - width?: number; - - /** - * Height for the Avatar - * - * @default 34 - */ - height?: number; - - /** - * Callback function when pressing component - */ - onPress?(): void; - - /** - * Callback function when long pressing component - */ - onLongPress?(): void; - - /** - * Styling for outer container - */ - containerStyle?: StyleProp; - - /** - * Image source - */ - source?: ImageURISource; - - /** - * Style for avatar image - */ - avatarStyle?: ImageStyle; - - /** - * Determines the shape of avatar - * - * @default false - */ - rounded?: boolean; - - /** - * Renders title in the avatar - */ - title?: string; - - /** - * Style for the title - */ - titleStyle?: StyleProp; - - /** - * Style for the view outside image or icon - */ - overlayContainerStyle?: StyleProp; - - /** - * Opacity when pressed - * - * @default 0.2 - */ - activeOpacity?: number; - - /** - * Icon for the avatar - */ - icon?: AvatarIcon; - - /** - * extra styling for icon component - */ - iconStyle?: StyleProp; - - /** - * Small sized icon - */ - small?: boolean; - - /** - * Medium sized icon - */ - medium?: boolean; - - /** - * Large sized icon - */ - large?: boolean; - - /** - * Extra-large sized icon - */ - xlarge?: boolean; -} - -/** - * Avatar Component - * - * @see https://react-native-training.github.io/react-native-elements/API/avatar/ - */ -export class Avatar extends React.Component {} - -export interface ButtonIcon extends IconObject { - buttonStyle?: StyleProp; -} - -export interface ButtonProps extends TouchableWithoutFeedbackProps { - /** - * Specify other component such as TouchableOpacity or other - * - * @default TouchableHighlight (iOS), TouchableNativeFeedback (android) - */ - component?: React.ComponentClass; - - /** - * Additional styling for button component - * - * @default null - */ - buttonStyle?: StyleProp; - - /** - * Button title - */ - title: string; - - /** - * Makes button large - * - * @default false - */ - large?: boolean; - - /** - * Specify different font family - * - * @default System font (iOS), Sans Serif (android) - */ - fontFamily?: string; - - /** - * Specify font weight for title - * - * @default null - */ - fontWeight?: string; - - /** - * Icon configuration for icon on right side of title - */ - iconRight?: ButtonIcon; - - /** - * onPress method - */ - onPress(): void; - - /** - * onLongPress method - */ - onLongPress?(): void; - - /** - * Icon configuration - */ - icon?: ButtonIcon; - - /** - * Specify other icon component instead of default. The component will have all values from the icon prop - * - * @default MaterialIcon - * @see https://github.com/oblador/react-native-vector-icons#icon-component - */ - iconComponent?: JSX.Element; - - /** - * Background color of button - * - * @default #397af8 - */ - backgroundColor?: string; - - /** - * Adds border radius to button - * (Note: if you set this, don't forget to also set borderRadius to containerViewStyle prop, otherwise unexpected behaviour might occur) - * - * @default 0 - */ - borderRadius?: number; - - /** - * Font color - * - * @default #fff - */ - color?: string; - - /** - * Text styling - * - * @default null - */ - textStyle?: StyleProp; - - /** - * Font size - * - * @default 18 - */ - fontSize?: number; - - /** - * Underlay color for button press - * - * @default transparent - */ - underlayColor?: string; - - /** - * Flag to add raised button styling - * - * @default false - */ - raised?: boolean; - - /** - * Indicates button is disabled - * - * @default false - */ - disabled?: boolean; - - /** - * Disabled button styling - * - * @default null - */ - disabledStyle?: StyleProp; - - /** - * Styling for Component container - * - * @default null - */ - containerViewStyle?: StyleProp; - - /** - * Styling for loading spinner - * - * @default null - */ - activityIndicatorStyle?: StyleProp; - - /** - * Display a loading spinner - * - * @default false - */ - loading?: boolean; - - /** - * Display the spinner to the right - * - * @default false - */ - loadingRight?: boolean; -} - -/** - * Button component - * - * @see https://react-native-training.github.io/react-native-elements/API/buttons/ - */ -export class Button extends React.Component {} - -export interface BadgeProps { - /** - * Text value to be displayed by badge - * - * @default null - */ - value?: string | number; - - /** - * Style for the outer badge component - */ - containerStyle?: StyleProp; - - /** - * Style for the outer-most badge component - */ - wrapperStyle?: StyleProp; - - /** - * Style for the text in the badge - */ - textStyle?: StyleProp; - - /** - * Override the default badge contents, mutually exclusive with 'value' property - */ - children?: JSX.Element; - - /** - * Custom component to replace the badge outer component - * - * @default View (if onPress then TouchableOpacity) - */ - component?: React.ComponentClass; - - /** - * Function called when pressed on the badge - */ - onPress?(): void; -} - -/** - * Badge component - * - * @see https://react-native-training.github.io/react-native-elements/API/badge/ - */ -export class Badge extends React.Component {} - -export interface CardProps { - /** - * Flex direction (row or column) - * - * @default 'column' - */ - flexDirection?: 'column' | 'row'; - - /** - * Outer container style - */ - containerStyle?: StyleProp; - - /** - * Inner container style - */ - wrapperStyle?: StyleProp; - - /** - * Card title - */ - title?: string; - - /** - * Additional title styling (if title provided) - */ - titleStyle?: StyleProp; - - /** - * Title rendered over the image - * (only works if image prop is present) - */ - featuredTitle?: string; - - /** - * Styling for featured title - */ - featuredTitleStyle?: StyleProp; - - /** - * Subtitle rendered over the image - * (only works if image prop is present) - */ - featuredSubtitle?: string; - - /** - * Styling for featured subtitle - */ - featuredSubtitleStyle?: StyleProp; - - /** - * Additional divider styling - * (if title provided) - */ - dividerStyle?: StyleProp; - - /** - * Specify different font family - * - * @default System font bold (iOS), Sans Serif Bold (android) - */ - fontFamily?: string; - - /** - * Specify image styling if image is provided - */ - imageStyle?: ImageStyle; - - /** - * Specify styling for view surrounding image - */ - imageWrapperStyle?: StyleProp; - - /** - * Add an image as the heading with the image prop - */ - image?: ImageURISource; -} - -/** - * Card component - * - * @see https://react-native-training.github.io/react-native-elements/API/card/ - */ -export class Card extends React.Component {} - -/** - * Set the buttons within a Group. - */ -export interface ElementObject { - element: JSX.Element | React.ReactType; -} - -/** - * Set the border styles for a component. - */ -export interface InnerBorderStyleProperty { - color?: string; - width?: number; -} - -export interface ButtonGroupProps { - /** - * Current selected index of array of buttons - */ - selectedIndex: number; - - /** - * Method to update Button Group Index - */ - onPress(selectedIndex: number): void; - - /** - * Array of buttons for component, if returning a component, must be an object with { element: componentName } - */ - buttons: string[] | ElementObject[]; - - /** - * Choose other button component such as TouchableOpacity - * - * @default TouchableHighlight - */ - component?: React.ComponentClass; - - /** - * Specify styling for main button container - */ - containerStyle?: StyleProp; - - /** - * inherited styling specify styling for button - */ - buttonStyle?: StyleProp; - - /** - * Specify color for selected state of button - * - * @default 'white' - */ - selectedBackgroundColor?: string; - - /** - * Specify specific styling for text - */ - textStyle?: StyleProp; - - /** - * Specify specific styling for text in the selected state - */ - selectedTextStyle?: StyleProp; - - /** - * inherited styling object { width, color } update the styling of the interior border of the list of buttons - */ - innerBorderStyle?: InnerBorderStyleProperty; - - /** - * Specify underlayColor for TouchableHighlight - * - * @default 'white' - */ - underlayColor?: string; - - /** - * Disables the currently selected button if true - * - * @default false - */ - disableSelected?: boolean; - - /** - * Determines what the opacity of the wrapped view should be when touch is active. - */ - activeOpacity?: number; - - /** - * Border radius for the container - */ - containerBorderRadius?: number; - - /** - * Styling for the final border edge - */ - lastBorderStyle?: StyleProp; - - /** - * - * Called immediately after the underlay is hidden - */ - onHideUnderlay?(): void; - - /** - * Called immediately after the underlay is shown - */ - onShowUnderlay?(): void; - - /** - * Animate the touchable to a new opacity. - */ - setOpacityTo?(value: number): void; -} - -export class ButtonGroup extends React.Component {} - -export interface CheckBoxProps { - /** - * Icon family, can be one of the following - * (required only if specifying an icon that is not from font-awesome) - */ - iconType?: IconType; - - /** - * Specify React Native component for main button - */ - component?: React.ComponentClass; - - /** - * Flag for checking the icon - * - * @default false - */ - checked: boolean; - - /** - * Moves icon to right of text. - * - * @default false - */ - iconRight?: boolean; - - /** - * Aligns checkbox to right - * - * @default false - */ - right?: boolean; - - /** - * Aligns checkbox to center - * - * @default false - */ - center?: boolean; - - /** - * Title of checkbox - */ - title?: string | JSX.Element; - - /** - * Style of main container - */ - containerStyle?: StyleProp; - - /** - * style of text - */ - textStyle?: StyleProp; - - /** - * onLongPress function for checkbox - */ - onLongPress?(): void; - - /** - * onLongPress function for checkbox - */ - onLongIconPress?(): void; - - /** - * onPress function for container - */ - onPress?(): void; - - /** - * onPress function for checkbox - */ - onIconPress?(): void; - - /** - * Default checked icon (Font Awesome Icon) - * - * @default 'check-square-o' - */ - checkedIcon?: string; - - /** - * Default checked icon (Font Awesome Icon) - * - * @default 'square-o' - */ - uncheckedIcon?: string; - - /** - * Default checked color - * - * @default 'green' - */ - checkedColor?: string; - - /** - * Default unchecked color - * @default '#bfbfbf' - */ - uncheckedColor?: string; - - /** - * Specify a custom checked message - */ - checkedTitle?: string; - - /** - * Specify different font family - * @default 'System font bold (iOS)' - * @default 'Sans Serif Bold (android)' - */ - fontFamily?: string; -} -export class CheckBox extends React.Component {} - -export interface DividerProps { - /** - * Style the divider - * - * @default {height: 1, backgroundColor: #e1e8ee} - */ - style?: StyleProp; -} - -export class Divider extends React.Component {} - -export interface FormValidationMessageProps extends ViewProperties { - /** - * Style of the container - */ - containerStyle?: StyleProp; - - /** - * Style of the text within the label message - */ - labelStyle?: StyleProp; - - /** - * Font family for the message - */ - fontFamily?: string; -} -export class FormValidationMessage extends React.Component< - FormValidationMessageProps, - any -> {} - -export interface FormInputProps extends TextInputProperties { - /** - * TextInput container styling - */ - containerStyle?: StyleProp; - - /** - * TextInput styling - */ - inputStyle?: StyleProp; - - /** - * @deprecated - * Get ref of TextInput - */ - textInputRef?(ref: TextInput): void; - - /** - * @deprecated - * Get ref of TextInput container - */ - containerRef?(ref: any): void; - - /** - * Shake the TextInput if not a falsy value and different from the previous value - */ - shake?: any; -} - -export class FormInput extends React.Component { - /** - * Holds reference to the stored input. - */ - input: TextInput; - - /** - * Shake the TextInput - * - * eg `this.formInputRef.shake()` - */ - shake(): void; - - /** - * Call focus on the TextInput - */ - focus(): void; - - /** - * Call blur on the TextInput - */ - blur(): void; - - /** - * Call clear on the TextInput - */ - clearText(): void; -} - -export interface FormLabelProps extends ViewProperties { - /** - * Additional label container style - */ - containerStyle?: StyleProp; - - /** - * Additional label styling - */ - labelStyle?: StyleProp; - - /** - * Specify different font family - * - * @default System font bold (iOS), Sans Serif Bold (android) - */ - fontFamily?: string; -} - -export class FormLabel extends React.Component {} - -export interface GridProps extends ViewProperties { - /** - * Outer grid styling - */ - containerStyle?: StyleProp; - - /** - * Opacity on pressing - * - */ - activeOpacity?: number; - - /** - * onPress method - */ - onPress?(): void; - - children: React.ReactNode; -} - -/** - * @deprecated - * Warning: Grid has been deprecated and will be removed in a future version of React Native Elements - * - * @see https://react-native-training.github.io/react-native-elements/API/grid - */ -export class Grid extends React.Component {} - -export interface SubGridProps extends ViewProperties { - /** - * Size for column or row - */ - size?: number; - - /** - * Opacity on pressing - * - * @default 1 - */ - activeOpacity?: number; - - /** - * Styling for the outer column or row - */ - containerStyle?: StyleProp; - - /** - * onPress method - */ - onPress?(): void; -} - -/** - * @deprecated - * Warning: Row has been deprecated and will be removed in a future version of React Native Elements - * @see https://react-native-training.github.io/react-native-elements/API/grid/#row - */ -export class Row extends React.Component {} - -/** - * @deprecated - * Warning: Col has been deprecated and will be removed in a future version of React Native Elements - * - * @see https://react-native-training.github.io/react-native-elements/API/grid/#column - * - */ -export class Col extends React.Component {} - -export interface HeaderIcon extends IconObject { - icon?: string; -} - -/** - * Defines the types that can be used in a header sub component - */ -export type HeaderSubComponent = JSX.Element | TextProps | HeaderIcon; - -export interface HeaderProps extends ViewProperties { - /** - * Accepts all props for StatusBar - */ - statusBarProps?: StatusBarProperties; - - /** - * Configuration object for default component (icon: string, ...props for React Native Elements Icon) or a valid React Element define your left component here - */ - leftComponent?: HeaderSubComponent; - - /** - * Configuration object for default component (text: string, ...props for React Native Text component) valid React Element define your center component here - */ - centerComponent?: HeaderSubComponent; - - /** - * Configuration object for default component (icon: string, ...props for React Native Elements Icon component) or a valid React Element define your right component here - */ - rightComponent?: HeaderSubComponent; - - /** - * Sets backgroundColor of the parent component - */ - backgroundColor?: string; - - /** - * Styling for outer container - */ - outerContainerStyles?: StyleProp; - - /** - * Styling for inner container - */ - innerContainerStyles?: StyleProp; -} - -/** - * Header component - * @see https://react-native-training.github.io/react-native-elements/API/header/ - */ -export class Header extends React.Component {} - -export interface IconProps { - /** - * Name of icon - */ - name: string; - - /** - * Type (defaults to material, options are material-community, zocial, font-awesome, octicon, ionicon, foundation, evilicon, simple-line-icon, or entypo) - * @default 'material' - */ - type?: IconType; - - /** - * Size of icon - * @default 26 - */ - size?: number; - - /** - * Color of icon - * - * @default 'black' - */ - color?: string; - - /** - * Additional styling to icon - */ - iconStyle?: StyleProp; - - /** - * View if no onPress method is defined, TouchableHighlight if onPress method is defined React Native component update React Native Component - */ - component?: React.ComponentClass; - - /** - * onPress method for button - */ - onPress?(): void; - - /** - * onLongPress method for button - */ - onLongPress?(): void; - - /** - * UnderlayColor for press event - */ - underlayColor?: string; - - /** - * Reverses color scheme - * - * @default false - */ - reverse?: boolean; - - /** - * Adds box shadow to button - * - * @default false - */ - raised?: boolean; - - /** - * Add styling to container holding icon - */ - containerStyle?: StyleProp; - - /** - * Specify reverse icon color - * - * @default 'white' - */ - reverseColor?: string; -} - -/** - * Icon component - * @see https://react-native-training.github.io/react-native-elements/API/icons/ - */ -export class Icon extends React.Component {} - -export interface ListProps extends ViewProperties { - /** - * Style the list container - * @default '{marginTop: 20, borderTopWidth: 1, borderBottomWidth: 1, borderBottomColor: #cbd2d9}' - */ - containerStyle?: StyleProp; -} - -/** - * List component - * @see https://react-native-training.github.io/react-native-elements/API/lists/ - */ -export class List extends React.Component {} - -export interface ListItemProps { - /** - * Left avatar. This is the React Native Image source prop. Avatar can be used in parallel to leftIcon if needed. - */ - avatar?: string | ImageURISource; - - /** - * Avatar styling. This is the React Native Image style prop - */ - avatarStyle?: ImageStyle; - - /** - * Avatar outer container styling - */ - avatarContainerStyle?: StyleProp; - - /** - * Avatar overlay container styling - */ - avatarOverlayContainerStyle?: StyleProp; - - /** - * Set chevron color - * - * @default '#bdc6cf' - */ - chevronColor?: string; - - /** - * View or TouchableHighlight if onPress method is added as prop - * Replace element with custom element - */ - component?: React.ComponentClass; - - /** - * Additional main container styling - */ - containerStyle?: StyleProp; - - /** - * Additional wrapper styling - */ - wrapperStyle?: StyleProp; - - /** - * Define underlay color for TouchableHighlight - * - * @default 'white' - */ - underlayColor?: string; - - /** - * Specify different font family - * - * @default 'HelevticaNeue' (iOS) - * @default 'Sans Serif' (android) - */ - fontFamily?: string; - - /** - * Set if you do not want a chevron - * - * @default false - */ - hideChevron?: boolean; - - /** - * onPress method for link - */ - onPress?(): void; - - /** - * onLongPress method for link - */ - onLongPress?(): void; - - /** - * Make left avatar round - * - * @default false - */ - roundAvatar?: boolean; - - /** - * Main title for list item, can be text or custom view - */ - title?: string; - - /** - * Number of lines for title - * - * @default 1 - */ - titleNumberOfLines?: number; - - /** - * Additional title styling - */ - titleStyle?: StyleProp; - - /** - * Provide styling for title container - */ - titleContainerStyle?: StyleProp; - - /** - * Subtitle text or custom view - */ - subtitle?: string | JSX.Element; - - /** - * Number of lines for Subtitle - * - * @default 1 - */ - subtitleNumberOfLines?: number; - - /** - * Provide styling for subtitle container - */ - subtitleContainerStyle?: StyleProp; - - /** - * Additional subtitle styling - */ - subtitleStyle?: StyleProp; - - /** - * Provide a rightTitle to have a title show up on the right side of the button - */ - rightTitle?: string; - - /** - * Number of lines for Right Title - * - * @default 1 - */ - rightTitleNumberOfLines?: number; - - /** - * Style the outer container of the rightTitle text - * - * @default "{flex: 1, alignItems: 'flex-end', justifyContent: 'center'}"" - */ - rightTitleContainerStyle?: StyleProp; - - /** - * Style the text of the rightTitle text - * - * @default "{marginRight: 5, color: '#bdc6cf'}" - */ - rightTitleStyle?: StyleProp; - - /** - * Add a label with your own styling by providing a label={} prop to ListItem - */ - label?: JSX.Element; - - /** - * Icon configuration for left icon, either a name from the icon library (like material) or a React Native element like Image. - * leftIcon can be used in parallel to avatar if needed. - * {name, color, style, type} - * (type defaults to material icons) OR React Native element - */ - leftIcon?: IconObject | JSX.Element; - - /** - * Attaches an onPress on left Icon - */ - leftIconOnPress?(): void; - - /** - * Attaches an onLongPress on left Icon - */ - leftIconOnLongPress?(): void; - - /** - * Underlay color for left Icon - * - * @default 'white' - */ - leftIconUnderlayColor?: string; - - /** - * {name: 'chevron-right'} object {name, color, style, type} (type defaults to material icons) OR - * React Native element icon configuration for right icon, either a name from the icon library (like material) or a React Native element like Image. - * Shows up unless hideChevron is set - */ - rightIcon?: IconObject | JSX.Element; - - /** - * Attaches an onPress on right Icon - */ - onPressRightIcon?(): void; - - /** - * Add a switch to the right side of your component - * - * @default false - */ - switchButton?: boolean; - - /** - * Add a callback function when the switch is toggled - */ - onSwitch?(value: boolean): void; - - /** - * If true the user won't be able to toggle the switch. Default value is false. - * @default false - */ - switchDisabled?: boolean; - - /** - * Background color when the switch is turned on. - */ - switchOnTintColor?: string; - - /** - * Color of the foreground switch grip. - */ - switchThumbTintColor?: string; - - /** - * Border color on iOS and background color on Android when the switch is turned off. - */ - switchTintColor?: string; - - /** - * The value of the switch. If true the switch will be turned on. Default value is false. - * - * @default false - */ - switched?: boolean; - - /** - * Whether to have the right title area be an input text component. - * - * @default false - */ - textInput?: boolean; - - /** - * Can tell TextInput to automatically capitalize certain characters. - */ - textInputAutoCapitalize?: boolean; - - /** - * Can tell TextInput to automatically capitalize certain characters. - */ - textInputAutoCorrect?: boolean; - - /** - * If true, focuses the input on componentDidMount. The default value is false. - */ - textInputAutoFocus?: boolean; - - /** - * If false, text is not editable. The default value is true. - */ - textInputEditable?: boolean; - - /** - * Can be one of the following: - * 'default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search' - */ - textInputKeyboardType?: KeyboardType | KeyboardTypeIOS; - - /** - * Limits the maximum number of characters that can be entered. - */ - textInputMaxLength?: number; - - /** - * If true, the text input can be multiple lines. The default value is false. - */ - textInputMultiline?: boolean; - - /** - * Callback that is called when the text input's text changes. Changed text is passed as an argument to the callback handler. - */ - textInputOnChangeText?(text: string): void; - - /** - * Callback that is called when the text input is focused. - */ - textInputOnFocus?(): void; - - /** - * Manually set value of the input - */ - textInputValue?: string; - - /** - * If true, obscures the text entered so that sensitive text like passwords stay secure. - */ - textInputSecure?: boolean; - - /** - * Style for the input text - */ - textInputStyle?: StyleProp; - - /** - * Style for the container surrounding the input text - */ - textInputContainerStyle?: StyleProp; - - /** - * Placeholder for the text input - */ - textInputPlaceholder?: string; - - /** - * Callback that is called when the text input is blurred. - */ - textInputOnBlur?(): void; - - /** - * If true, all text will automatically be selected on focus. - */ - textInputSelectTextOnFocus?: boolean; - - /** - * Determines how the return key should look. For more info see the React Native docs - */ - textInputReturnKeyType?: string; - - /** - * Add a badge to the ListItem by using this prop - * - */ - badge?: BadgeProps | ElementObject; -} - -/** - * ListItem component - * @see https://react-native-training.github.io/react-native-elements/API/lists/ - */ -export class ListItem extends React.Component {} - -export interface ButtonInformation { - title: string; - icon: string; - buttonStyle?: StyleProp; -} - -export interface PricingCardProps { - /** - * Title - */ - title?: string; - - /** - * Price - */ - price: string; - - /** - * Color scheme for button & title - */ - color: string; - - /** - * Pricing information - */ - info?: string[]; - - /** - * {title, icon, buttonStyle} - * Button information - */ - button: ButtonInformation; - - /** - * Function to be run when button is pressed - */ - onButtonPress?(): void; - - /** - * Outer component styling - */ - containerStyle?: StyleProp; - - /** - * Inner wrapper component styling - */ - wrapperStyle?: StyleProp; - - /** - * Specify title font family - * - * System font (font weight 800) (iOS) - * Sans Serif Black (android) - */ - titleFont?: string; - - /** - * Specify pricing font family - * - * System font (font weight 700) (iOS) - * Sans Serif Bold (android) - */ - pricingFont?: string; - - /** - * Specify pricing information font family - * - * System font bold (iOS) - * Sans Serif Bold (android) - */ - infoFont?: string; - - /** - * Specify button font family - * - * System font (iOS) - * Sans Serif (android) - */ - buttonFont?: string; -} - -/** - * PricingCard component - * @see https://react-native-training.github.io/react-native-elements/API/pricing/ - */ -export class PricingCard extends React.Component {} - -export interface RatingProps { - /** - * Callback method when the user finishes rating. Gives you the final rating value as a whole number - */ - onFinishRating(rating: number): void; - - /** - * Choose one of the built-in types: star, rocket, bell, heart or use type custom to render a custom image - */ - type?: 'star' | 'rocket' | 'bell' | 'heart' | 'custom'; - - /** - * Pass in a custom image source; use this along with type='custom' prop above - */ - ratingImage?: ImageURISource | string | number; - - /** - * Pass in a custom fill-color for the rating icon; use this along with type='custom' prop above - * - * @default '#f1c40f' - */ - ratingColor?: string; - - /** - * Pass in a custom background-fill-color for the rating icon; use this along with type='custom' prop above - * - * @default 'white' - */ - ratingBackgroundColor?: string; - - /** - * Number of rating images to display - * - * @default 5 - */ - ratingCount?: number; - - /** - * The size of each rating image - * - * @default 50 - */ - imageSize?: number; - - /** - * Displays the Built-in Rating UI to show the rating value in real-time - */ - showRating?: boolean; - - /** - * Whether the rating can be modiefied by the user - * - * @default false - */ - readonly?: boolean; - - /** - * The initial rating to render - * - * @default ratingCount/2 - */ - startingValue?: number; - - /** - * The number of decimal places for the rating value; must be between 0 and 20 - * - * @default undefined - */ - fractions?: number; - - /** - * Exposes style prop to add additonal styling to the container view - */ - style?: StyleProp; -} - -/** - * Rating component - * @see https://react-native-training.github.io/react-native-elements/API/rating/ - */ -export class Rating extends React.Component {} - -export interface SearchBarProps extends TextInputProperties { - /** - * TextInput container styling - */ - containerStyle?: StyleProp; - - /** - * TextInput styling - */ - inputStyle?: StyleProp; - - /** - * @deprecated - * Get ref of TextInput - */ - textInputRef?(ref: TextInput): void; - - /** - * @deprecated - * Get ref of TextInput container - */ - containerRef?(ref: any): void; - - /** - * Specify color, styling, or another Material Icon Name - */ - icon?: IconObject; - - /** - * Remove icon from textinput - * - * @default false - */ - noIcon?: boolean; - - /** - * @default false change theme to light theme - */ - lightTheme?: boolean; - - /** - * Change TextInput styling to rounded corners - * - * @default false - */ - round?: boolean; - - /** - * Specify other than the default transparent underline color - * - * @default 'transparent' - */ - underlineColorAndroid?: string; - - /** - * Specify color, styling of the loading ActivityIndicator effect - * - * @default "{ color: '#86939e' }" - */ - loadingIcon?: IconObject; - - /** - * Show the loading ActivityIndicator effect - * - * @default false - */ - showLoadingIcon?: boolean; - - /** - * Set the placeholder text - * - * @default '' - */ - placeholder?: string; - - /** - * Set the color of the placeholder text - * - * @default '#86939e' - */ - placeholderTextColor?: string; - - /** - * Method to fire when text is changed - */ - onChangeText?(text: string): void; - - /** - * Specify color, styling, or another Material Icon Name - * (Note: pressing on this icon clears text inside the searchbar) - * - * @default "{ color: '#86939e', name: 'search' }" - */ - clearIcon?: IconObject; -} - -/** - * SearchBar component - * @see https://react-native-training.github.io/react-native-elements/API/searchbar/ - */ -export class SearchBar extends React.Component { - /** - * Holds reference to the stored input. - */ - input: TextInput; - - /** - * Call focus on the TextInput - */ - focus(): void; - - /** - * Call blur on the TextInput - */ - blur(): void; - - /** - * Call clear on the TextInput - */ - clearText(): void; -} - -export interface SideMenuProps { - /** - * Menu component - */ - menu: JSX.Element; - - /** - * Props driven control over menu open state - * - * @default false - */ - isOpen?: boolean; - - /** - * Content view left margin if menu is opened - * - * @default ⅔ of device screen width - */ - openMenuOffset?: number; - - /** - * Content view left margin if menu is hidden - */ - hiddenMenuOffset?: number; - - /** - * Edge distance on content view to open side menu - * - * @default 60 - */ - edgeHitWidth?: number; - - /** - * X axis tolerance - */ - toleranceX?: number; - - /** - * Y axis tolerance - */ - toleranceY?: number; - - /** - * Disable whether the menu can be opened with gestures or not - * - * @default false - */ - disableGestures?: boolean; - - /** - * Function that accepts event as an argument and specify if side-menu should react on the touch or not. - * Check https://facebook.github.io/react-native/docs/gesture-responder-system.html for more details - */ - onStartShouldSetResponderCapture?(event: GestureResponderEvent): boolean; - - /** - * Callback on menu open/close. Is passed isOpen as an argument. - */ - onChange?(isOpen: boolean): void; - - /** - * Callback on menu move. Is passed left as an argument - */ - onMove?(left: number): void; - - /** - * Either 'left' or 'right'. - * - * @default 'left' - */ - menuPosition?: string; - - /** - * Function that accept 2 arguments (prop, value) and return an object: - * - animation you should use at the place you specify parameter to animate - * - newOffset you should use to specify the final value of prop - */ - animationFunction?( - animation: Animated.Value, - newOffset: number - ): Animated.CompositeAnimation; - - /** - * Function that accept 1 argument (value) and return an object - * - leftOffset you should use at the place you need current value of animated parameter (left offset of content view) - */ - animationStyle?(leftOffset: number): StyleProp; - - /** - * When true, content view will bounce back to openMenuOffset when dragged further - * - * @default true - */ - bounceBackOnOverdraw?: boolean; -} - -/** - * @deprecated - * Warning: SideMenu has been deprecated and will be removed in a future version of React Native Elements. For a complete navigation solution that includes SideMenu(Drawer) as well as many other - * features, be sure to check out react-navigation (https://reactnavigation.org) and it's DrawerNavigator. - * - * SideMenu component - * @see https://react-native-training.github.io/react-native-elements/API/side_menu/ - */ -export class SideMenu extends React.Component {} - -export interface SliderProps { - /** - * Initial value of the slider - * - * @default 0 - */ - value?: number; - - /** - * If true the user won't be able to move the slider - * - * @default false - */ - disabled?: boolean; - - /** - * Initial minimum value of the slider - * - * @default 0 - */ - minimumValue?: number; - - /** - * Initial maximum value of the slider - * - * @default 1 - */ - maximumValue?: number; - - /** - * Step value of the slider. The value should be between 0 and maximumValue - minimumValue) - * - * @default 0 - */ - step?: number; - - /** - * The color used for the track to the left of the button - * - * @default '#3f3f3f' - */ - minimumTrackTintColor?: string; - - /** - * The color used for the track to the right of the button - * - * @default '#b3b3b3' - */ - maximumTrackTintColor?: string; - - /** - * The color used for the thumb - * - * @default '#343434' - */ - thumbTintColor?: string; - - /** - * The size of the touch area that allows moving the thumb. The touch area has the same center as the visible thumb. - * This allows to have a visually small thumb while still allowing the user to move it easily. - * - * @default "{width: 40, height: 40}" - */ - thumbTouchSize?: { - width?: number; - height?: number; - }; - - /** - * Callback continuously called while the user is dragging the slider - */ - onValueChange?(value: number): void; - - /** - * Callback called when the user starts changing the value (e.g. when the slider is pressed) - */ - onSlidingStart?(value: number): void; - - /** - * Callback called when the user finishes changing the value (e.g. when the slider is released) - */ - onSlidingComplete?(value: number): void; - - /** - * The style applied to the slider container - */ - style?: StyleProp; - - /** - * The style applied to the track - */ - trackStyle?: StyleProp; - - /** - * The style applied to the thumb - */ - thumbStyle?: StyleProp; - - /** - * Set this to true to visually see the thumb touch rect in green. - * - * @default false - */ - debugTouchArea?: boolean; - - /** - * Set to true if you want to use the default 'spring' animation - * - * @default false - */ - animateTransitions?: boolean; - - /** - * Set to 'spring' or 'timing' to use one of those two types of animations with the default animation properties. - * - * @default 'timing' - */ - animationType?: 'spring' | 'timing'; - - /** - * Used to configure the animation parameters. These are the same parameters in the Animated library. - * - * @default undefined - */ - animationConfig?: - | Animated.TimingAnimationConfig - | Animated.SpringAnimationConfig; -} - -/** - * Slider component - * @see https://react-native-training.github.io/react-native-elements/API/slider/ - */ -export class Slider extends React.Component {} - -export type SocialMediaType = - | 'facebook' - | 'twitter' - | 'google-plus-official' - | 'pinterest' - | 'linkedin' - | 'youtube' - | 'vimeo' - | 'tumblr' - | 'instagram' - | 'quora' - | 'foursquare' - | 'wordpress' - | 'stumbleupon' - | 'github' - | 'github-alt' - | 'twitch' - | 'medium' - | 'soundcloud' - | 'gitlab' - | 'angellist' - | 'codepen'; - -export interface SocialIconProps { - /** - * Title if made into a button - */ - title?: string; - - /** - * Social media type - */ - type: SocialMediaType; - - /** - * Adds a drop shadow, set to false to remove - * - * @default true - */ - raised?: boolean; - - /** - * Creates button - * - * @default false - */ - button?: boolean; - - /** - * onPress method - */ - onPress?(): void; - - /** - * @default none function onLongPress method - */ - onLongPress?(): void; - - /** - * Reverses icon color scheme, setting background to white and icon to primary color - * - * @default false - */ - light?: boolean; - - /** - * Extra styling for icon component - */ - iconStyle?: StyleProp; - - /** - * Button styling - */ - style?: StyleProp; - - /** - * Icon color - */ - iconColor?: string; - - /** - * Icon size - * - * @default 24 - */ - iconSize?: number; - - /** - * Component Type of button - * - * @default TouchableHighlight - */ - component?: React.ComponentClass; - - /** - * Specify different font family - * - * @default System font bold (iOS), Sans Serif Black (android) - */ - fontFamily?: string; - - /** - * Specify font weight of title if set as a button with a title - * - * @default bold (ios), black(android) - */ - fontWeight?: string; - - /** - * Specify text styling - */ - fontStyle?: StyleProp; - - /** - * Disable button - * - * @default false - */ - disabled?: boolean; - - /** - * Shows loading indicator - * - * @default false - */ - loading?: boolean; -} - -/** - * SocialIcon component - * @see https://react-native-training.github.io/react-native-elements/API/social_icons/ - */ -export class SocialIcon extends React.Component {} - -export interface SwipeDeckProps { - /** - * An array of data object which contains each card details. - */ - data: ReadonlyArray; - - /** - * A function that takes a card as a prop and renders it with custom UI - */ - renderCard(card: D): JSX.Element; - - /** - * A function that renders custom UI when no more cards are present - */ - renderNoMoreCards?(): JSX.Element; - - /** - * function function A callback function that takes a card as a prop and take the approriate action when the user swipes the card right - */ - onSwipeRight?(card: D): void; - - /** - * function function A callback function that takes a card as a prop and take the approriate action when the user swipes the card left - */ - onSwipeLeft?(card: D): void; -} - -/** - * SwipeDeck component - * @see https://react-native-training.github.io/react-native-elements/API/swipedeck/ - */ -export class SwipeDeck extends React.Component< - SwipeDeckProps, - any -> {} - -/** - * @deprecated - * Warning: Tabs has been deprecated and will be removed in a future version of React Native Elements. - * For a complete navigation solution that includes Tabs as well as many other features, be sure to check out react-navigation (https://reactnavigation.org) and it's TabRouter. - */ -export class Tabs extends TabNavigator {} - -/** - * @deprecated - * Warning: Tab has been deprecated and will be removed in a future version of React Native Elements. - * For a complete navigation solution that includes Tabs as well as many other features, be sure to check out react-navigation (https://reactnavigation.org) and it's TabRouter. - */ -export class Tab extends TabNavigator.Item {} - -export interface TileProps { - /** - * Icon Component Props - */ - icon?: IconObject; - - /** - * Styling for the outer icon container - */ - iconContainerStyle?: StyleProp; - - /** - * Text inside the tile - */ - title?: string; - - /** - * Styling for the title - */ - titleStyle?: StyleProp; - - /** - * Text inside the tile when tile is featured - */ - caption?: string; - - /** - * Styling for the caption - */ - captionStyle?: StyleProp; - - /** - * Changes the look of the tile - */ - featured?: boolean; - - /** - * @default none object (style) Styling for the outer tile container - */ - containerStyle?: StyleProp; - - /** - * Source for the image - */ - imageSrc: ImageURISource | string | number; - - /** - * Styling for the image - */ - imageContainerStyle?: StyleProp; - - /** - * @default none function (event) Function to call when tile is pressed - */ - onPress?(): void; - - /** - * Number passed to control opacity on press - * - * @default 0.2 - */ - activeOpacity?: number; - - /** - * Styling for bottom container when not featured tile - */ - contentContainerStyle?: StyleProp; - - /** - * Width for the tile - * - * @default Device Width - */ - width?: number; - - /** - * Height for the tile - * - * @default Device Width * 0.8 - */ - height?: number; -} - -/** - * Tile component - * @see https://react-native-training.github.io/react-native-elements/API/tile/ - */ -export class Tile extends React.Component {} - -/** - * Colors - */ - -export interface Colors { - readonly primary: string; - readonly primary1: string; - readonly primary2: string; - readonly secondary: string; - readonly secondary2: string; - readonly secondary3: string; - readonly grey0: string; - readonly grey1: string; - readonly grey2: string; - readonly grey3: string; - readonly grey4: string; - readonly grey5: string; - readonly dkGreyBg: string; - readonly greyOutline: string; - readonly searchBg: string; - readonly disabled: string; - readonly white: string; - readonly error: string; - readonly [key: string]: string; -} - -export const colors: Colors; - -/* Utility Functions */ - -/** - * TODO make the Icon Type an export of the react-native-vector-icons type definitions. - */ -export function getIconType(type: IconType): any; - -/** - * Method to normalize size of fonts across devices - */ -export function normalize(size: number): number; diff --git a/types/react-native-elements/react-native-elements-tests.tsx b/types/react-native-elements/react-native-elements-tests.tsx deleted file mode 100644 index 29155829b2..0000000000 --- a/types/react-native-elements/react-native-elements-tests.tsx +++ /dev/null @@ -1,975 +0,0 @@ -import * as React from 'react'; -import { - ListView, - View, - StyleSheet, - TouchableNativeFeedback, - Image, - TextInput, - Animated, - Dimensions -} from 'react-native'; -import { - Button, - Text, - Badge, - Avatar, - Card, - ButtonGroup, - CheckBox, - Divider, - FormInput, - FormValidationMessage, - FormLabel, - Header, - Icon, - List, - ListItem, - PricingCard, - Rating, - SearchBar, - SideMenu, - Slider, - SocialIcon, - SwipeDeck, - Tabs, - Tab, - Tile, - colors, - getIconType, - normalize -} from 'react-native-elements'; - -const { width, height } = Dimensions.get('window'); - -class TextTest extends React.Component { - render() { - return ( - - Heading 1 - Heading 2 - Heading 3 - Heading 4 - - ); - } -} - -class AvatarTest extends React.Component { - render() { - return ( - - - Avatars - console.log('Works!')} - activeOpacity={0.7} - /> - console.log('Works!')} - activeOpacity={0.7} - /> - console.log('Works!')} - activeOpacity={0.7} - /> - console.log('Works!')} - activeOpacity={0.7} - /> - - - - Avatar with initials - console.log('Works!')} - activeOpacity={0.7} - /> - console.log('Works!')} - activeOpacity={0.7} - /> - console.log('Works!')} - activeOpacity={0.7} - /> - console.log('Works!')} - activeOpacity={0.7} - /> - - - - Avatar with icons - console.log('Works!')} - activeOpacity={0.7} - containerStyle={{ - flex: 2, - marginLeft: 20, - marginTop: 115 - }} - /> - console.log('Works!')} - activeOpacity={0.7} - containerStyle={{ flex: 3, marginTop: 100 }} - /> - console.log('Works!')} - activeOpacity={0.7} - containerStyle={{ flex: 4, marginTop: 75 }} - /> - console.log('Works!')} - activeOpacity={0.7} - containerStyle={{ flex: 5, marginRight: 60 }} - /> - - - ); - } -} - -const AvatarStyles = StyleSheet.create({ - title: { - fontSize: 30, - marginBottom: 10 - } -}); - -class BadgeTest extends React.Component { - render() { - return ( - - - - - User 1 - - - console.log('pressed')} value="5" /> - - - - ); - } -} - -class ButtonTest extends React.Component { - handleButtonPress() { - console.log('I got pressed'); - } - - render() { - return ( - -
Simple configuration with standard gradientCustom gradient configurationA single datapointmultiple datapoints