diff --git a/acorn/README.md b/acorn/README.md new file mode 100644 index 0000000000..c9c372a9ce --- /dev/null +++ b/acorn/README.md @@ -0,0 +1,9 @@ +This file exists for reminding contributors that this definition is **WIP**. + +### Note + +There are a **large** number of methods of class `Parser` and `LooseParser` haven't been declared. + +However, these methods may not be useful for common users. So, I hang the job util it worth continuing. + +Of course, volunteers are welcomed to spend time extracting these things. diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts index c51ba151f8..fb79d23718 100644 --- a/acorn/acorn-tests.ts +++ b/acorn/acorn-tests.ts @@ -14,7 +14,7 @@ var string: string; // acorn string = acorn.version; program = acorn.parse('code'); -program = acorn.parse('code', {ranges: true, onToken: tokens, onComment: comments}); +program = acorn.parse('code', { ranges: true, onToken: tokens, onComment: comments }); program = acorn.parse('code', { ranges: true, onToken: (token) => tokens.push(token), @@ -28,3 +28,42 @@ any = token.value; // Comment string = comment.value; + +const parser = new acorn.Parser({}, 'export default ""', 0); + +const node = new acorn.Node(parser, 1, 1); + +class LooseParser { + constructor(input: string, options = {}) { + + } + + // this means you can extend LooseParser + test() { + + } +} +acorn.addLooseExports(function () { + return { + type: 'Program', + sourceType: 'script', + body: [ + { + type: 'EmptyStatement' + } + ] + } +}, LooseParser, {}); + +acorn.parseExpressionAt('string', 2); + +acorn.isNewLine(56); + +acorn.isIdentifierStart(56); + +acorn.isIdentifierChar(56); + +acorn.getLineInfo('string', 56); + +acorn.plugins['test'] = function (p: acorn.Parser, config: any) { +} diff --git a/acorn/index.d.ts b/acorn/index.d.ts index 982abb4f54..1944abc257 100644 --- a/acorn/index.d.ts +++ b/acorn/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Acorn v1.0.1 +// Type definitions for Acorn v4.0.3 // Project: https://github.com/marijnh/acorn -// Definitions by: RReverser +// Definitions by: RReverser , e-cloud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -10,13 +10,89 @@ export = acorn; import * as ESTree from 'estree'; declare namespace acorn { - var version: string; - function parse(input: string, options?: Options): ESTree.Program; - function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression; - function getLineInfo(input: string, offset: number): ESTree.Position; - var defaultOptions: Options; + interface PlainObject { + [name: string]: any; + } - interface TokenType { + interface PluginsObject { + [name: string]: (p: Parser, config: any) => void; + } + + interface Options { + ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 2015 | 2016 | 2017; + sourceType?: 'script' | 'module'; + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => void; + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => void; + allowReserved?: boolean; + allowReturnOutsideFunction?: boolean; + allowImportExportEverywhere?: boolean; + allowHashBang?: boolean; + locations?: boolean; + onToken?: ((token: Token) => any) | Token[]; + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, + endLoc?: ESTree.Position + ) => void) | Comment[]; + ranges?: boolean; + program?: ESTree.Program; + sourceFile?: string; + directSourceFile?: string; + preserveParens?: boolean; + plugins?: PlainObject; + } + + class Parser { + constructor(options: Options, input: string, startPos?: number); + + parse(): ESTree.Program; + } + + const plugins: PluginsObject; + + const defaultOptions: Options; + + class Position implements ESTree.Position { + line: number; + column: number; + + constructor(line: number, col: number); + + offset(n: number): Position; + } + + class SourceLocation implements ESTree.SourceLocation { + start: Position; + end: Position; + source?: string; + + constructor(p: Parser, start: Position, end: Position); + } + + function getLineInfo(input: string, offset: number): ESTree.Position; + + class Node { + type: string; + start: number; + end: number; + loc?: ESTree.SourceLocation; + sourceFile?: string; + range?: [number, number]; + + constructor(parser: Parser, pos: number, loc: number); + } + + interface TokeTypeConfig { + keyword: string; + beforeExpr?: boolean; + startsExpr?: boolean; + isLoop?: boolean; + isAssign?: boolean; + prefix?: boolean; + postfix?: boolean; + binop?: number; + } + + class TokenType { label: string; keyword: string; beforeExpr: boolean; @@ -26,19 +102,110 @@ declare namespace acorn { prefix: boolean; postfix: boolean; binop: number; - updateContext: (prevType: TokenType) => any; + updateContext: (prevType: TokenType) => void; + + constructor(label: string, conf?: TokeTypeConfig); } + const tokTypes: { + num: TokenType; + regexp: TokenType; + string: TokenType; + name: TokenType; + eof: TokenType; + bracketL: TokenType; + bracketR: TokenType; + braceL: TokenType; + braceR: TokenType; + parenL: TokenType; + parenR: TokenType; + comma: TokenType; + semi: TokenType; + colon: TokenType; + dot: TokenType; + question: TokenType; + arrow: TokenType; + template: TokenType; + ellipsis: TokenType; + backQuote: TokenType; + dollarBraceL: TokenType; + eq: TokenType; + assign: TokenType; + incDec: TokenType; + prefix: TokenType; + logicalOR: TokenType; + logicalAND: TokenType; + bitwiseOR: TokenType; + bitwiseXOR: TokenType; + bitwiseAND: TokenType; + equality: TokenType; + relational: TokenType; + bitShift: TokenType; + plusMin: TokenType; + modulo: TokenType; + star: TokenType; + slash: TokenType; + starstar: TokenType; + _break: TokenType; + _case: TokenType; + _catch: TokenType; + _continue: TokenType; + _debugger: TokenType; + _default: TokenType; + _do: TokenType; + _else: TokenType; + _finally: TokenType; + _for: TokenType; + _function: TokenType; + _if: TokenType; + _return: TokenType; + _switch: TokenType; + _throw: TokenType; + _try: TokenType; + _var: TokenType; + _const: TokenType; + _while: TokenType; + _with: TokenType; + _new: TokenType; + _this: TokenType; + _super: TokenType; + _class: TokenType; + _extends: TokenType; + _export: TokenType; + _import: TokenType; + _null: TokenType; + _true: TokenType; + _false: TokenType; + _in: TokenType; + _instanceof: TokenType; + _typeof: TokenType; + _void: TokenType; + _delete: TokenType; + } + + class TokContext { + constructor(token: string, isExpr: boolean, preserveSpace: boolean, override: (p: Parser) => void); + } + + const tokContexts: { + b_stat: TokContext; + b_expr: TokContext; + b_tmpl: TokContext; + p_stat: TokContext; + p_expr: TokContext; + q_tmpl: TokContext; + f_expr: TokContext; + }; + + function isIdentifierStart(code: number, astral?: boolean): boolean; + + function isIdentifierChar(code: number, astral?: boolean): boolean; + interface AbstractToken { start: number; end: number; - loc: ESTree.SourceLocation; - range: [number, number]; - } - - interface Token extends AbstractToken { - type: TokenType; - value: any; + loc?: SourceLocation; + range?: [number, number]; } interface Comment extends AbstractToken { @@ -46,23 +213,46 @@ declare namespace acorn { value: string; } - interface Options { - ecmaVersion?: number; - sourceType?: string; - onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; - onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; - allowReserved?: boolean; - allowReturnOutsideFunction?: boolean; - allowImportExportEverywhere?: boolean; - allowHashBang?: boolean; - locations?: boolean; - onToken?: ((token: Token) => any) | Token[]; - onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[]; - ranges?: boolean; - program?: ESTree.Program; - sourceFile?: string; - directSourceFile?: string; - preserveParens?: boolean; - plugins?: { [name: string]: Function; }; + class Token { + constructor(p: Parser); } + + interface Token extends AbstractToken { + type: TokenType; + value: any; + } + + function isNewLine(code: number): boolean; + + const lineBreak: RegExp; + + const lineBreakG: RegExp; + + const version: string; + + interface IParse { + (input: string, options?: Options): ESTree.Program; + } + + const parse: IParse; + + function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression; + + // todo: here the tokenizer function returns a Parser instance, that is targeting the detail of + // Parser prototype. Someone need this please reade README.md first. + // function tokenizer(options: Options, input: string): Parser; + + let parse_dammit: IParse | undefined; + let LooseParser: ILooseParserClass | undefined; + let pluginsLoose: PluginsObject | undefined; + + interface ILooseParserClass { + new (input: string, options?: Options): ILooseParser + } + + interface ILooseParser { + + } + + function addLooseExports(parse: IParse, parser: ILooseParserClass, plugins: PluginsObject): void; } diff --git a/angular-ui-bootstrap/index.d.ts b/angular-ui-bootstrap/index.d.ts index 21677a911a..24f8405125 100644 --- a/angular-ui-bootstrap/index.d.ts +++ b/angular-ui-bootstrap/index.d.ts @@ -7,6 +7,29 @@ import * as angular from 'angular'; +export type IAccordionConfig = angular.ui.bootstrap.IAccordionConfig; +export type IButtonConfig = angular.ui.bootstrap.IButtonConfig; +export type IDatepickerConfig = angular.ui.bootstrap.IDatepickerConfig; +export type IDatepickerPopupConfig = angular.ui.bootstrap.IDatepickerPopupConfig; +export type IModalProvider = angular.ui.bootstrap.IModalProvider; +export type IModalService = angular.ui.bootstrap.IModalService; +export type IModalServiceInstance = angular.ui.bootstrap.IModalServiceInstance; +export type IModalScope = angular.ui.bootstrap.IModalScope; +export type IModalSettings = angular.ui.bootstrap.IModalSettings; +export type IModalStackService = angular.ui.bootstrap.IModalStackService; +export type IModalStackedMapKeyValuePair = angular.ui.bootstrap.IModalStackedMapKeyValuePair; +export type IPaginationConfig = angular.ui.bootstrap.IPaginationConfig; +export type IPagerConfig = angular.ui.bootstrap.IPagerConfig; +export type IPositionCoordinates = angular.ui.bootstrap.IPositionCoordinates; +export type IPositionService = angular.ui.bootstrap.IPositionService; +export type IProgressConfig = angular.ui.bootstrap.IProgressConfig; +export type IRatingConfig = angular.ui.bootstrap.IRatingConfig; +export type ITimepickerConfig = angular.ui.bootstrap.ITimepickerConfig; +export type ITooltipOptions = angular.ui.bootstrap.ITooltipOptions; +export type ITooltipProvider = angular.ui.bootstrap.ITooltipProvider; +export type ITransitionService = angular.ui.bootstrap.ITransitionService; +export type ITransitionServiceOptions = angular.ui.bootstrap.ITransitionServiceOptions; + declare module 'angular' { export namespace ui.bootstrap { diff --git a/async/async-tests.ts b/async/async-tests.ts index 2a21a6cabb..abc2653f60 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -648,7 +648,7 @@ async.mapValues({ }, 500); -}, function(err: Error, results: string[]): void { +}, function(err: Error, results: Dictionary): void { console.log("async.mapValues: done with results", results); @@ -668,7 +668,7 @@ async.mapValuesSeries({ }, 500); -}, function(err: Error, results: string[]): void { +}, function(err: Error, results: Dictionary): void { console.log("async.mapValuesSeries: done with results", results); diff --git a/async/index.d.ts b/async/index.d.ts index 45d39ea955..86aa17ea6b 100644 --- a/async/index.d.ts +++ b/async/index.d.ts @@ -111,8 +111,8 @@ interface Async { mapSeries: typeof async.map; mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; mapLimit(arr: Dictionary, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; - mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; - mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; + mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; mapValuesSeries: typeof async.mapValues; filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; filter(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; diff --git a/inert/index.d.ts b/inert/index.d.ts new file mode 100644 index 0000000000..fdd3d91bcd --- /dev/null +++ b/inert/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for inert 4.0 +// Project: https://github.com/hapijs/inert/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Note: this definition contains only enough to make TypeScript happy (hapi?) when +// importing inert. The functionality that importing inert adds to the reply +// object and its other features are implemented in the hapi definition on +// DefinitelyTyped. The inert object is never actually used in practice except to +// be passed as an extension to the server.register() method which already takes +// an `any` argument, so just using `any` here is fine. + +/// + +export var inert: any; \ No newline at end of file diff --git a/inert/inert-tests-es6.ts b/inert/inert-tests-es6.ts new file mode 100644 index 0000000000..ac50196d00 --- /dev/null +++ b/inert/inert-tests-es6.ts @@ -0,0 +1,7 @@ + +import * as HapiES6 from 'hapi'; +import * as InertES6 from 'inert'; + + +const server = new HapiES6.Server({}); +server.register(InertES6, () => {}); \ No newline at end of file diff --git a/inert/inert-tests.ts b/inert/inert-tests.ts new file mode 100644 index 0000000000..cd12de7780 --- /dev/null +++ b/inert/inert-tests.ts @@ -0,0 +1,9 @@ + +const Inert = require('inert'); +const Hapi = require('hapi'); + + +const server = new Hapi.Server({}); +server.register(Inert, () => {}); + +export var makeThisAModule: any; \ No newline at end of file diff --git a/inert/tsconfig.json b/inert/tsconfig.json new file mode 100644 index 0000000000..9c678b93ff --- /dev/null +++ b/inert/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "inert-tests.ts", + "inert-tests-es6.ts" + ] +} \ No newline at end of file diff --git a/inert/tslint.json b/inert/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/inert/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/jqueryui/index.d.ts b/jqueryui/index.d.ts index 808148cfbe..d74cc76c66 100644 --- a/jqueryui/index.d.ts +++ b/jqueryui/index.d.ts @@ -320,6 +320,14 @@ declare namespace JQueryUI { * Additional text to display after the year in the month headers. */ yearSuffix?: string; + /** + * Set to true to automatically hide the datepicker. + */ + autohide?: boolean; + /** + * Set to date to automatically enddate the datepicker. + */ + endDate?: Date; } interface DatepickerFormatDateOptions { @@ -1341,6 +1349,23 @@ interface JQuery { * @param optionName 'buttonText' */ datepicker(methodName: 'option', optionName: 'buttonText'): string; + + /** + * Get the autohide option, after initialization + * + * @param methodName 'option' + * @param optionName 'autohide' + */ + datepicker(methodName: 'option', optionName: 'autohide'): boolean; + + + /** + * Get the endDate after initialization + * + * @param methodName 'option' + * @param optionName 'endDate' + */ + datepicker(methodName: 'option', optionName: 'endDate'): Date; /** * Set the buttonText option, after initialization * diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index c3a53f60b3..c56e98e7f8 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.js 1.0.0 +// Type definitions for Leaflet.js 1.0.2 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,10 +9,38 @@ type NativeMouseEvent = MouseEvent; declare namespace L { export class Class { - static extend(props:any):any/* how to return constructor of self extended type ? */; - static include(props:any):any /* how to return self extended type ? */; - static mergeOptions(props:any): any /* how to return self extended type ? */; - static addInitHook(initHookFn: ()=> void): any/* how to return self extended type ? */; + static extend(props: any): any/* how to return constructor of self extended type ? */; + static include(props: any): any /* how to return self extended type ? */; + static mergeOptions(props: any): any /* how to return self extended type ? */; + static addInitHook(initHookFn: () => void): any/* how to return self extended type ? */; + } + + export class Transformation { + constructor(a: number, b: number, c: number, d: number); + + transform(point: Point, scale?: number): Point; + + untransform(point: Point, scale?: number): Point; + } + + export namespace LineUtil { + export function simplify(points: Array, tolerance: number): Array; + + export function simplify(points: Array, tolerance: number): Array; + + export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; + + export function pointToSegmentDistance(p: PointTuple, p1: PointTuple, p2: PointTuple): number; + + export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; + + export function closestPointOnSegment(p: PointTuple, p1: PointTuple, p2: PointTuple): Point; + } + + export namespace PolyUtil { + export function clipPolygon(points: Array, bounds: Bounds, round?: boolean): Array; + + export function clipPolygon(points: Array, bounds: BoundsLiteral, round?: boolean): Array; } export class DomUtil { @@ -33,13 +61,13 @@ declare namespace L { static testProp(props: String[]): String|boolean/*=false*/; static setTransform(el: HTMLElement, offset: Point, scale?: Number):void; static setPosition(el: HTMLElement, position: Point):void; - static getPosition(el: HTMLElement): Point - static disableTextSelection(): void - static enableTextSelection(): void - static disableImageDrag(): void - static enableImageDrag(): void - static preventOutline(el: HTMLElement): void - static restoreOutline(): void + static getPosition(el: HTMLElement): Point; + static disableTextSelection(): void; + static enableTextSelection(): void; + static disableImageDrag(): void; + static enableImageDrag(): void; + static preventOutline(el: HTMLElement): void; + static restoreOutline(): void; } export interface CRS { @@ -154,7 +182,7 @@ declare namespace L { round(): Point; floor(): Point; ceil(): Point; - distanceTo(otherPoint: PointExpression): Point; + distanceTo(otherPoint: PointExpression): number; equals(otherPoint: PointExpression): boolean; contains(otherPoint: PointExpression): boolean; toString(): string; @@ -203,14 +231,14 @@ declare namespace L { * with an object (e.g. the user clicks on the map, causing the map to fire * 'click' event). */ - export interface Evented extends Class { + export abstract class Evented extends Class { /** * Adds a listener function (fn) to a particular event type of the object. * You can optionally specify the context of the listener (object the this * keyword will point to). You can also pass several space-separated types * (e.g. 'click dblclick'). */ - on(type: string, fn: EventHandlerFn, context?: Object): this; + on(type: string, fn: EventHandlerFn, context?: any): this; /** * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} @@ -223,7 +251,7 @@ declare namespace L { * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ - off(type: string, fn?: EventHandlerFn, context?: Object): this; + off(type: string, fn?: EventHandlerFn, context?: any): this; /** * Removes a set of type/listener pairs. @@ -240,7 +268,7 @@ declare namespace L { * object — the first argument of the listener function will contain its properties. * The event might can optionally be propagated to event parents. */ - fire(type: string, data?: Object, propagate?: boolean): this; + fire(type: string, data?: any, propagate?: boolean): this; /** * Returns true if a particular event type has any listeners attached to it. @@ -250,7 +278,7 @@ declare namespace L { /** * Behaves as on(...), except the listener will only get fired once and then removed. */ - once(type: string, fn: EventHandlerFn, context?: Object): this; + once(type: string, fn: EventHandlerFn, context?: any): this; /** * Behaves as on(...), except the listener will only get fired once and then removed. @@ -275,7 +303,7 @@ declare namespace L { * keyword will point to). You can also pass several space-separated types * (e.g. 'click dblclick'). */ - addEventListener(type: string, fn: EventHandlerFn, context?: Object): this; + addEventListener(type: string, fn: EventHandlerFn, context?: any): this; /** * Alias for on(...) @@ -292,7 +320,7 @@ declare namespace L { * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ - removeEventListener(type: string, fn: EventHandlerFn, context?: Object): this; + removeEventListener(type: string, fn: EventHandlerFn, context?: any): this; /** * Alias for off(...) @@ -313,7 +341,7 @@ declare namespace L { * * Behaves as on(...), except the listener will only get fired once and then removed. */ - addOneTimeEventListener(type: string, fn: EventHandlerFn, context?: Object): this; + addOneTimeEventListener(type: string, fn: EventHandlerFn, context?: any): this; /** * Alias for once(...) @@ -329,7 +357,7 @@ declare namespace L { * object — the first argument of the listener function will contain its properties. * The event might can optionally be propagated to event parents. */ - fireEvent(type: string, data?: Object, propagate?: boolean): this; + fireEvent(type: string, data?: any, propagate?: boolean): this; /** * Alias for listens(...) @@ -339,6 +367,21 @@ declare namespace L { hasEventListeners(type: string): boolean; } + /** + * A class for making DOM elements draggable (including touch support). + * Used internally for map and marker dragging. Only works for elements + * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition). + */ + export class Draggable extends Evented { + constructor(element: HTMLElement, dragStartTarget?: HTMLElement, preventOutline?: boolean); + + enable(): void; + + disable(): void; + + finishDrag(): void; + } + interface LayerOptions { pane?: string; } @@ -455,7 +498,7 @@ declare namespace L { } export interface WMS extends TileLayer { - setParams(params: Object, noRedraw?: boolean): this; + setParams(params: any, noRedraw?: boolean): this; } export namespace tileLayer { @@ -475,6 +518,15 @@ declare namespace L { bringToFront(): this; bringToBack(): this; setUrl(url: string): this; + + /** Update the bounds that this ImageOverlay covers */ + setBounds(bounds: LatLngBounds): this; + + /** Get the bounds that this ImageOverlay covers */ + getBounds(): LatLngBounds; + + /** Get the img element that represents the ImageOverlay on the map */ + getElement(): HTMLImageElement; } export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; @@ -640,7 +692,7 @@ declare namespace L { * Iterates over the layers of the group, * optionally specifying context of the iterator function. */ - eachLayer(fn: (layer: Layer) => void, context?: Object): this; + eachLayer(fn: (layer: Layer) => void, context?: any): this; /** * Returns the layer with the given internal ID. @@ -1065,7 +1117,7 @@ declare namespace L { export interface Event { type: string; - target: any; // should this be Object and have users cast? + target: any; } export interface MouseEvent extends Event { @@ -1115,7 +1167,7 @@ declare namespace L { export interface GeoJSONEvent extends Event { layer: Layer; - properties: any; // any or Object? + properties: any; geometryType: string; id: string; } @@ -1133,13 +1185,13 @@ declare namespace L { } export namespace DomEvent { - export function on(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + export function on(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; - export function on(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + export function on(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; - export function off(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + export function off(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; - export function off(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + export function off(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; export function stopPropagation(ev: Event): typeof DomEvent; @@ -1155,13 +1207,13 @@ declare namespace L { export function getWheelDelta(ev: Event): number; - export function addListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + export function addListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; - export function addListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + export function addListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; - export function removeListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + export function removeListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; - export function removeListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + export function removeListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; } interface DefaultMapPanes { @@ -1183,7 +1235,7 @@ declare namespace L { addLayer(layer: Layer): this; removeLayer(layer: Layer): this; hasLayer(layer: Layer): boolean; - eachLayer(fn: (layer: Layer) => void, context?: Object): this; + eachLayer(fn: (layer: Layer) => void, context?: any): this; openPopup(popup: Popup): this; openPopup(content: string, latlng: LatLngExpression, options?: PopupOptions): this; openPopup(content: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): this; @@ -1222,7 +1274,7 @@ declare namespace L { getPane(pane: HTMLElement): HTMLElement; getPanes(): {[name: string]: HTMLElement} & DefaultMapPanes; getContainer(): HTMLElement; - whenReady(fn: () => void, context?: Object): this; + whenReady(fn: () => void, context?: any): this; // Methods for getting map state getCenter(): LatLng; @@ -1292,7 +1344,7 @@ declare namespace L { export interface IconDefault extends Icon { imagePath: string; } - + export namespace Icon { export const Default: IconDefault; } diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index 34a5fa245f..1d3f447ad4 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -1,5 +1,3 @@ - - import L = require('leaflet'); const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; @@ -28,6 +26,16 @@ point = L.point(12, 13, true); point = L.point(pointTuple); point = L.point({x: 12, y: 13}); +let distance: number; +point.distanceTo(point); +point.distanceTo(pointTuple); + +const transformation = new L.Transformation(1, 2, 3, 4); +point = transformation.transform(point); +point = transformation.transform(point, 2); +point = transformation.untransform(point); +point = transformation.untransform(point, 2); + const boundsLiteral: L.BoundsLiteral = [[1, 1], pointTuple]; let bounds: L.Bounds; @@ -36,11 +44,26 @@ bounds = L.bounds(pointTuple, pointTuple); bounds = L.bounds([point, point]); bounds = L.bounds(boundsLiteral); +let points: Array; +points = L.LineUtil.simplify([point, point], 1); +points = L.LineUtil.simplify([pointTuple, pointTuple], 2); + +distance = L.LineUtil.pointToSegmentDistance(point, point, point); +distance = L.LineUtil.pointToSegmentDistance(pointTuple, pointTuple, pointTuple); + +point = L.LineUtil.closestPointOnSegment(point, point, point); +point = L.LineUtil.closestPointOnSegment(pointTuple, pointTuple, pointTuple); + +points = L.PolyUtil.clipPolygon(points, bounds); +points = L.PolyUtil.clipPolygon(points, bounds, true); +points = L.PolyUtil.clipPolygon([pointTuple, pointTuple], boundsLiteral); +points = L.PolyUtil.clipPolygon([pointTuple, pointTuple], boundsLiteral, true); + let mapOptions: L.MapOptions = {}; mapOptions = { preferCanvas: true, attributionControl: false, - zoomControl: true, + zoomControl: true, closePopupOnClick: false, zoomSnap: 1, zoomDelta: 1, @@ -51,11 +74,11 @@ mapOptions = { zoom: 12, minZoom: 10, maxZoom: 14, - fadeAnimation: true, + fadeAnimation: true, markerZoomAnimation: false, transform3DLimit: 123, zoomAnimation: false, - zoomAnimationThreshold: 4, + zoomAnimationThreshold: 4, inertia: false, inertiaDeceleration: 2000, inertiaMaxSpeed: 1000, @@ -326,3 +349,9 @@ map = map .remove() .whenReady(() => {}) .whenReady(() => {}, {}); + +let elementToDrag = document.createElement('div'); +let draggable = new L.Draggable(elementToDrag); +draggable.enable(); +draggable.disable(); +draggable.on('drag', () => {}); \ No newline at end of file diff --git a/leaflet/package.json b/leaflet/package.json new file mode 100644 index 0000000000..9605e3e506 --- /dev/null +++ b/leaflet/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/geojson": "0.0.31" + } +} diff --git a/leaflet/tsconfig.json b/leaflet/tsconfig.json index b61ef91dfd..cc6a966883 100644 --- a/leaflet/tsconfig.json +++ b/leaflet/tsconfig.json @@ -6,6 +6,7 @@ "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ + "node_modules/@types", "../" ], "types": [], @@ -16,4 +17,4 @@ "index.d.ts", "leaflet-tests.ts" ] -} \ No newline at end of file +} diff --git a/navigation-react/index.d.ts b/navigation-react/index.d.ts new file mode 100644 index 0000000000..edd9e746f2 --- /dev/null +++ b/navigation-react/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for NavigationReact 2.0 +// Project: http://grahammendick.github.io/navigation/ +// Definitions by: Graham Mendick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { StateNavigator } from 'navigation'; +import { Component, HTMLProps } from 'react'; + +export = NavigationReact; + +declare namespace NavigationReact { + /** + * Defines the Link Props contract + */ + interface LinkProps extends HTMLProps { + /** + * Indicates whether Links listen for navigate events + */ + lazy?: boolean; + /** + * Determines the effect on browser history + */ + historyAction?: 'add' | 'replace' | 'none'; + /** + * Handles Link click events + */ + navigating?: (e: MouseEvent, domId: string, link: string) => boolean; + /** + * The State Navigator + */ + stateNavigator?: StateNavigator; + } + + /** + * Defines the Refresh Link Props contract + */ + interface RefreshLinkProps extends LinkProps { + /** + * The NavigationData to pass + */ + navigationData?: any; + /** + * Indicates whether to include all the current NavigationData + */ + includeCurrentData?: boolean; + /** + * The data to add from the current NavigationData + */ + currentDataKeys?: string; + /** + * The Css Class to display when the Link is active + */ + activeCssClass?: string; + /** + * Indicates whether the Link is disabled when active + */ + disableActive?: boolean; + } + + /** + * Hyperlink Component the navigates to the current State + */ + class RefreshLink extends Component { } + + /** + * Defines the Navigation Link Props contract + */ + interface NavigationLinkProps extends RefreshLinkProps { + /** + * The key of the State to navigate to + */ + stateKey: string; + } + + /** + * Hyperlink Component the navigates to a State + */ + class NavigationLink extends Component { } + + /** + * Defines the Navigation Back Link Props contract + */ + interface NavigationBackLinkProps extends RefreshLinkProps { + /** + * Starting at 1, The number of Crumb steps to go back + */ + distance: number; + } + + /** + * Hyperlink Component the navigates back along the crumb trail + */ + class NavigationBackLink extends Component { } +} diff --git a/navigation-react/navigation-react-tests.tsx b/navigation-react/navigation-react-tests.tsx new file mode 100644 index 0000000000..83a0c5f40a --- /dev/null +++ b/navigation-react/navigation-react-tests.tsx @@ -0,0 +1,78 @@ +import { StateNavigator } from 'navigation'; +import { NavigationBackLink, NavigationLink, RefreshLink } from 'navigation-react'; +import * as React from 'react'; + +var stateNavigator = new StateNavigator([ + { key: 'people', route: 'people/{page}' }, + { key: 'person', route: 'person/{id}', trackCrumbTrail: true } +]); + +// Refresh Link +var RefreshLinkTest = function() { + return People; +} + +RefreshLinkTest = function() { + return ( + true} + stateNavigator={stateNavigator} + target="_blank" + aria-label="Go to the second page of people"> + People + + ); +} + +// Navigation Link +var NavigationLinkTest = function() { + return Person; +} + +NavigationLinkTest = function() { + return ( + true} + stateNavigator={stateNavigator} + target="_blank" + aria-label="View the person's details"> + Person + + ); +} + +// Navigation Back Link +var NavigationBackLinkTest = function() { + return People; +} + +NavigationBackLinkTest = function() { + return ( + true} + stateNavigator={stateNavigator} + target="_blank" + aria-label="Go back to the list of people"> + People + + ); +} + diff --git a/navigation-react/tsconfig.json b/navigation-react/tsconfig.json new file mode 100644 index 0000000000..8c627de430 --- /dev/null +++ b/navigation-react/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "navigation-react-tests.tsx" + ] +} \ No newline at end of file diff --git a/navigation-react/tslint.json b/navigation-react/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/navigation-react/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/tether/index.d.ts b/tether/index.d.ts index ae00278d9b..302801f8aa 100644 --- a/tether/index.d.ts +++ b/tether/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Tether v1.1 +// Type definitions for Tether v1.4 // Project: http://github.hubspot.com/tether/ // Definitions by: Adi Dahiya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -22,6 +22,7 @@ declare class Tether { declare namespace Tether { interface ITetherOptions { attachment?: string; + bodyElement?: HTMLElement; classes?: {[className: string]: boolean}; classPrefix?: string; constraints?: ITetherConstraint[]; diff --git a/whatwg-fetch/index.d.ts b/whatwg-fetch/index.d.ts index f17d88a7df..67bde53016 100644 --- a/whatwg-fetch/index.d.ts +++ b/whatwg-fetch/index.d.ts @@ -6,9 +6,9 @@ /// interface Window { - fetch(url: RequestInfo, init?: RequestInit): Promise; + fetch(input: RequestInfo, init?: RequestInit): Promise; } -declare var fetch: typeof window.fetch; +declare let fetch: typeof window.fetch; declare type HeadersInit = Headers | string[][] | { [key: string]: string }; declare class Headers { @@ -16,7 +16,7 @@ declare class Headers { append(name: string, value: string): void; delete(name: string): void; - get(name: string): string; // | null; (TS 2.0 strict null check) + get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; @@ -29,32 +29,35 @@ declare class Headers { } declare type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; +declare type ResponseBodyInit = BodyInit | ReadableStream; interface Body { - bodyUsed: boolean; + readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; formData(): Promise; json(): Promise; + json(): Promise; text(): Promise; } declare type RequestInfo = Request | string; declare class Request { - constructor(input: RequestInfo, init?: RequestInit); - - method: string; - url: string; - headers: Headers; + constructor(input: RequestInfo, init?: RequestInit); - type: RequestType - destination: RequestDestination; - referrer: string; - referrerPolicy: ReferrerPolicy; - mode: RequestMode; - credentials: RequestCredentials; - cache: RequestCache; - redirect: RequestRedirect; - integrity: string; + readonly method: string; + readonly url: string; + readonly headers: Headers; + + readonly type: RequestType + readonly destination: RequestDestination; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly mode: RequestMode; + readonly credentials: RequestCredentials; + readonly cache: RequestCache; + readonly redirect: RequestRedirect; + readonly integrity: string; + readonly keepalive: boolean; clone(): Request; } @@ -70,7 +73,7 @@ interface RequestInit { cache?: RequestCache; redirect?: RequestRedirect; integrity?: string; - window?: any; + window?: null; // can only be set to null } type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; @@ -79,27 +82,30 @@ type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestCredentials = "omit" | "same-origin" | "include"; type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; type RequestRedirect = "follow" | "error" | "manual"; + type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; declare class Response { - constructor(body?: BodyInit, init?: ResponseInit); + constructor(body?: ResponseBodyInit, init?: ResponseInit); static error(): Response; static redirect(url: string, status?: number): Response; - type: ResponseType; - url: string; - redirected: boolean; - status: number; - ok: boolean; - statusText: string; - headers: Headers; - body: ReadableStream; // | null; - trailer: Promise; + readonly type: ResponseType; + + readonly url: string; + readonly redirected: boolean; + readonly status: number; + readonly ok: boolean; + readonly statusText: string; + readonly headers: Headers; + readonly body: ReadableStream | null; + readonly trailer: Promise; clone(): Response; } interface Response extends Body {} + interface ResponseInit { status?: number; statusText?: string; diff --git a/whatwg-fetch/tsconfig.json b/whatwg-fetch/tsconfig.json index 2333d8dfc0..4e8f7e915e 100644 --- a/whatwg-fetch/tsconfig.json +++ b/whatwg-fetch/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index aa6b90b8c8..39a4cf9d2b 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -68,4 +68,43 @@ function handlePromise(promise: Promise) { }).then((text) => { console.log(text); }); -} \ No newline at end of file +} + +function test_Body_json() { + interface FooBar { + foo: string; + bar: string; + } + + fetch('http://test.com') + .then(response => response.json()) + .then(fooBar => { + console.log(fooBar.foo); + console.log(fooBar.bar); + }); + + fetch('http://test.com') + .then(response => > response.json()) + .then(fooBar => { + console.log(fooBar.foo); + console.log(fooBar.bar); + }); + + fetch('http://test.com') + .then(response => response.json() as Promise) + .then(fooBar => { + console.log(fooBar.foo); + console.log(fooBar.bar); + }); + + fetch('http://test.com') + .then(response => response.json()) + .then(fooBar => { + // fooBar is of type any, not of type FooBar + + // FIXME Was behaving properly with TypeScript 2.0.10, not anymore with 2.1.4 + // See Wrong type with Promise chaining and 2.1.4 https://github.com/Microsoft/TypeScript/issues/12409 + //console.log(fooBar.foo); + //console.log(fooBar.bar); + }); +} diff --git a/whatwg-streams/index.d.ts b/whatwg-streams/index.d.ts index 757189b190..4f1e26ee7c 100644 --- a/whatwg-streams/index.d.ts +++ b/whatwg-streams/index.d.ts @@ -15,11 +15,18 @@ interface ReadableByteStreamSource { cancel?(reason: string): void | Promise; type: "bytes"; + autoAllocateChunkSize?: number; } interface QueuingStrategy { - highWaterMark?: number; size?(chunk: ArrayBufferView): number; + highWaterMark?: number; +} + +interface PipeOptions { + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; } declare class ReadableStream { @@ -31,8 +38,8 @@ declare class ReadableStream { cancel(reason: string): Promise; getReader(): ReadableStreamDefaultReader; getReader({ mode }: { mode: "byob" }): ReadableStreamBYOBReader; - pipeThrough({ writable, readable }: { writable: WritableStream, readable: T }): T; - pipeTo(dest: WritableStream, { preventClose, preventAbort, preventCancel }: { preventClose?: boolean, preventAbort?: boolean, preventCancel?: boolean }): Promise; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: T }, options?: PipeOptions): T; + pipeTo(dest: WritableStream, options?: PipeOptions): Promise; tee(): [ReadableStream, ReadableStream]; } @@ -49,7 +56,7 @@ declare class ReadableStreamDefaultReader { declare class ReadableStreamBYOBReader { constructor(stream: ReadableStream); - closed: Promise; + closed: Promise; cancel(reason: string): Promise; read(view: ArrayBufferView): Promise>; @@ -88,8 +95,8 @@ declare class ReadableStreamBYOBRequest { interface WritableStreamSink { start?(controller: WritableStreamDefaultController): void | Promise; - write?(chunk: any): void | Promise; - close?(): void | Promise; + write?(chunk: any, controller?: WritableStreamDefaultController): void | Promise; + close?(controller: WritableStreamDefaultController): void | Promise; abort?(reason: string): void | Promise; } @@ -106,7 +113,7 @@ declare class WritableStreamDefaultWriter { constructor(stream: WritableStream); closed: Promise; - desiredSize: number; + desiredSize: number | null; ready: Promise; abort(reason: string): Promise; @@ -124,11 +131,11 @@ declare class WritableStreamDefaultController { declare class ByteLengthQueuingStrategy { constructor({ highWaterMark }: { highWaterMark: number }); - size(chunk: ArrayBufferView): number; + size(chunk: ArrayBufferView): number | undefined; } declare class CountQueuingStrategy { constructor({ highWaterMark }: { highWaterMark: number }); - size(): number; // 1; -} \ No newline at end of file + size(): 1; +} diff --git a/whatwg-streams/tsconfig.json b/whatwg-streams/tsconfig.json index 9c6a6ad155..318d69cb04 100644 --- a/whatwg-streams/tsconfig.json +++ b/whatwg-streams/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/whatwg-streams/whatwg-streams-tests.ts b/whatwg-streams/whatwg-streams-tests.ts index ce5eb2b256..b1735b754f 100644 --- a/whatwg-streams/whatwg-streams-tests.ts +++ b/whatwg-streams/whatwg-streams-tests.ts @@ -1,20 +1,39 @@ -function makeReadableWebSocketStream(url: string, protocols: string[]) { - const ws = new WebSocket(url, protocols); - ws.binaryType = "arraybuffer"; +/// - return new ReadableStream({ - start(controller) { - ws.onmessage = event => controller.enqueue(event.data); - ws.onclose = () => controller.close(); - ws.onerror = () => controller.error(new Error("The WebSocket errored!")); - }, +// Examples taken from https://streams.spec.whatwg.org/#creating-examples - cancel() { - ws.close(); - } - }); +// 8.1. A readable stream with an underlying push source (no backpressure support) + +{ + function makeReadableWebSocketStream(url: string, protocols: string | string[]) { + const ws = new WebSocket(url, protocols); + ws.binaryType = "arraybuffer"; + + return new ReadableStream({ + start(controller) { + ws.onmessage = event => controller.enqueue(event.data); + ws.onclose = () => controller.close(); + ws.onerror = () => controller.error(new Error("The WebSocket errored!")); + }, + + cancel() { + ws.close(); + } + }); + } + + const writableStream = new WritableStream(); + + const webSocketStream = makeReadableWebSocketStream("wss://example.com:443/", "protocol"); + + webSocketStream.pipeTo(writableStream) + .then(() => console.log("All data successfully written!")) + .catch(e => console.error("Something went wrong!", e)); } + +// 8.2. A readable stream with an underlying push source and backpressure support + function makeReadableBackpressureSocketStream(host: string, port: number) { const socket = createBackpressureSocket(host, port); @@ -49,6 +68,9 @@ function makeReadableBackpressureSocketStream(host: string, port: number) { function createBackpressureSocket(host: string, port: number): any { }; } + +// 8.3. A readable byte stream with an underlying push source (no backpressure support) + const DEFAULT_CHUNK_SIZE = 65536; function makeUDPSocketStream(host: string, port: number) { @@ -93,7 +115,100 @@ function makeUDPSocketStream(host: string, port: number) { function createUDPSocket(host: string, port: number): any { }; } -function makeWritableWebSocketStream(url: string, protocols: string[]) { + +// 8.4. A readable stream with an underlying pull source + +//const fs = require("pr/fs"); // https://github.com/jden/pr +interface fs { + open(path: string | Buffer, flags: string | number): Promise; + read(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise; + write(fd: number, buffer: Buffer, offset: number, length: number): Promise; + close(fd: number): Promise; +} +let fs: fs; + +{ + const CHUNK_SIZE = 1024; + + function makeReadableFileStream(filename: string) { + let fd: number; + let position = 0; + + return new ReadableStream({ + start() { + return fs.open(filename, "r").then(result => { + fd = result; + }); + }, + + pull(controller) { + const buffer = new ArrayBuffer(CHUNK_SIZE); + + return fs.read(fd, buffer, 0, CHUNK_SIZE, position).then(bytesRead => { + if (bytesRead === 0) { + return fs.close(fd).then(() => controller.close()); + } else { + position += bytesRead; + controller.enqueue(new Uint8Array(buffer, 0, bytesRead)); + } + }); + }, + + cancel() { + return fs.close(fd); + } + }); + } +} + + +// 8.5. A readable byte stream with an underlying pull source + +{ + //const fs = require("pr/fs"); // https://github.com/jden/pr + const DEFAULT_CHUNK_SIZE = 1024; + + function makeReadableByteFileStream(filename: string) { + let fd: number; + let position = 0; + + return new ReadableStream({ + type: "bytes", + + start() { + return fs.open(filename, "r").then(result => { + fd = result; + }); + }, + + pull(controller) { + // Even when the consumer is using the default reader, the auto-allocation + // feature allocates a buffer and passes it to us via byobRequest. + const v = controller.byobRequest.view; + + return fs.read(fd, v.buffer, v.byteOffset, v.byteLength, position).then(bytesRead => { + if (bytesRead === 0) { + return fs.close(fd).then(() => controller.close()); + } else { + position += bytesRead; + controller.byobRequest.respond(bytesRead); + } + }); + }, + + cancel() { + return fs.close(fd); + }, + + autoAllocateChunkSize: DEFAULT_CHUNK_SIZE + }); + } +} + + +// 8.6. A writable stream with no backpressure or success signals + +function makeWritableWebSocketStream(url: string, protocols: string | string[]) { const ws = new WebSocket(url, protocols); return new WritableStream({ @@ -117,71 +232,123 @@ function makeWritableWebSocketStream(url: string, protocols: string[]) { }); } -function streamifyWebSocket(url: string, protocol: string) { - const ws = new WebSocket(url, protocol); - ws.binaryType = "arraybuffer"; +{ + const readableStream = new ReadableStream(); - return { - readable: new ReadableStream(new WebSocketSource(ws)), - writable: new WritableStream(new WebSocketSink(ws)) - }; + const webSocketStream = makeWritableWebSocketStream("wss://example.com:443/", "protocol"); + + readableStream.pipeTo(webSocketStream) + .then(() => console.log("All data successfully written!")) + .catch(e => console.error("Something went wrong!", e)); } -class WebSocketSource implements ReadableStreamSource { - private _ws: WebSocket - constructor(ws: WebSocket) { - this._ws = ws; - } +// 8.7. A writable stream with backpressure and success signals - start(controller: ReadableStreamDefaultController) { - this._ws.onmessage = event => controller.enqueue(event.data); - this._ws.onclose = () => controller.close(); +{ + //const fs = require("pr/fs"); // https://github.com/jden/pr - this._ws.addEventListener("error", () => { - controller.error(new Error("The WebSocket errored!")); + function makeWritableFileStream(filename: string) { + let fd: number; + + return new WritableStream({ + start() { + return fs.open(filename, "w").then(result => { + fd = result; + }); + }, + + write(chunk) { + return fs.write(fd, chunk, 0, chunk.length); + }, + + close() { + return fs.close(fd); + } }); } - cancel() { - this._ws.close(); - } + const fileStream = makeWritableFileStream("/example/path/on/fs.txt"); + const writer = fileStream.getWriter(); + + writer.write("To stream, or not to stream\n"); + writer.write("That is the question\n"); + + writer.close() + .then(() => console.log("chunks written and stream closed successfully!")) + .catch(e => console.error(e)); } -class WebSocketSink implements WritableStreamSink { - private _ws: WebSocket - constructor(ws: WebSocket) { - this._ws = ws; +// 8.8. A { readable, writable } stream pair wrapping the same underlying resource + +{ + function streamifyWebSocket(url: string, protocol: string) { + const ws = new WebSocket(url, protocol); + ws.binaryType = "arraybuffer"; + + return { + readable: new ReadableStream(new WebSocketSource(ws)), + writable: new WritableStream(new WebSocketSink(ws)) + }; } - start(controller: WritableStreamDefaultController) { - this._ws.addEventListener("error", () => { - controller.error(new Error("The WebSocket errored!")); - }); + class WebSocketSource implements ReadableStreamSource { + private _ws: WebSocket; - return new Promise(resolve => this._ws.onopen = () => resolve()); - } + constructor(ws: WebSocket) { + this._ws = ws; + } - write(chunk: any) { - this._ws.send(chunk); - } + start(controller: ReadableStreamDefaultController) { + this._ws.onmessage = event => controller.enqueue(event.data); + this._ws.onclose = () => controller.close(); - close() { - return new Promise((resolve, reject) => { - this._ws.onclose = () => resolve(); + this._ws.addEventListener("error", () => { + controller.error(new Error("The WebSocket errored!")); + }); + } + + cancel() { this._ws.close(); - }); + } } + + class WebSocketSink implements WritableStreamSink { + private _ws: WebSocket; + + constructor(ws: WebSocket) { + this._ws = ws; + } + + start(controller: WritableStreamDefaultController) { + this._ws.addEventListener("error", () => { + controller.error(new Error("The WebSocket errored!")); + }); + + return new Promise(resolve => this._ws.onopen = () => resolve()); + } + + write(chunk: any) { + this._ws.send(chunk); + } + + close() { + return new Promise((resolve, reject) => { + this._ws.onclose = () => resolve(); + this._ws.close(); + }); + } + } + + const streamyWS = streamifyWebSocket("wss://example.com:443/", "protocol"); + const writer = streamyWS.writable.getWriter(); + const reader = streamyWS.readable.getReader(); + + writer.write("Hello"); + writer.write("web socket!"); + + reader.read().then(({ value, done }) => { + console.log("The web socket says: ", value); + }); } - -const streamyWS = streamifyWebSocket("wss://example.com:443/", "protocol"); -const writer = streamyWS.writable.getWriter(); -const reader = streamyWS.readable.getReader(); - -writer.write("Hello"); -writer.write("web socket!"); - -reader.read().then(({ value, done }) => { - console.log("The web socket says: ", value); -}); \ No newline at end of file diff --git a/wordcloud/index.d.ts b/wordcloud/index.d.ts index cdc7e1678f..c7cd98aafb 100644 --- a/wordcloud/index.d.ts +++ b/wordcloud/index.d.ts @@ -47,7 +47,7 @@ declare namespace WordCloud { /** origin of the “cloud” in [x, y]. */ origin?: [number, number]; /** set to true to allow word being draw partly outside of the canvas. Allow word bigger than the size of the canvas to be drawn. */ - drawOutOfBounds?: boolean; + drawOutOfBound?: boolean; /** visualize the grid by draw squares to mask the drawn areas. */ drawMask?: boolean;