diff --git a/types/angular-ui-sortable/angular-ui-sortable-tests.ts b/types/angular-ui-sortable/angular-ui-sortable-tests.ts index a5db7903bf..9ecde2f92a 100644 --- a/types/angular-ui-sortable/angular-ui-sortable-tests.ts +++ b/types/angular-ui-sortable/angular-ui-sortable-tests.ts @@ -132,9 +132,8 @@ myApp.controller('sortableController', function ($scope: MySortableControllerSco $scope.sortableOptions.tolerance = 'pointer'; $scope.sortableOptions.zIndex = 9999; - $scope.sortableOptions['ui-floating'] = undefined; - $scope.sortableOptions['ui-floating'] = null; - $scope.sortableOptions['ui-floating'] = false; - $scope.sortableOptions['ui-floating'] = true; - $scope.sortableOptions['ui-floating'] = "auto"; + const sortableFloatingOption0: ng.ui.UISortableOptions = { 'ui-floating': undefined }; + const sortableFloatingOption1: ng.ui.UISortableOptions = { 'ui-floating': false }; + const sortableFloatingOption2: ng.ui.UISortableOptions = { 'ui-floating': true }; + const sortableFloatingOption3: ng.ui.UISortableOptions = { 'ui-floating': 'auto' }; }); diff --git a/types/angular-ui-sortable/index.d.ts b/types/angular-ui-sortable/index.d.ts index c364246dba..aa81038346 100644 --- a/types/angular-ui-sortable/index.d.ts +++ b/types/angular-ui-sortable/index.d.ts @@ -12,7 +12,7 @@ declare module 'angular' { export namespace ui { interface UISortableOptions extends SortableOptions { - 'ui-floating'?: string | boolean; + 'ui-floating'?: 'auto' | boolean; } interface UISortableProperties { diff --git a/types/chroma-js/index.d.ts b/types/chroma-js/index.d.ts index daf53a0e10..8fdae85b4d 100644 --- a/types/chroma-js/index.d.ts +++ b/types/chroma-js/index.d.ts @@ -124,7 +124,7 @@ declare namespace chroma { * Computes the eucledian distance between two colors in a given color space (default is 'lab'). * {@link https://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions} */ - distance(color1: string | Color, color2: string | Color, colorSpace?: keyof ColorSpaces): Color; + distance(color1: string | Color, color2: string | Color, colorSpace?: keyof ColorSpaces): number; /** * Computes color difference {@link https://en.wikipedia.org/wiki/Color_difference#CMC_l:c_.281984.29} as @@ -133,7 +133,7 @@ declare namespace chroma { * {@link https://web.archive.org/web/20160306044036/http://www.brucelindbloom.com/javascript/ColorDiff.js} * The parameters L (default 1) and C (default 1) are weighting factors for lightness and chromacity. */ - deltaE(color1: string | Color, color2: string | Color, L?: number, C?: number): Color; + deltaE(color1: string | Color, color2: string | Color, L?: number, C?: number): number; /** * chroma.brewer is an map of ColorBrewer scales that are included in chroma.js for convenience. diff --git a/types/dagre-d3/dagre-d3-tests.ts b/types/dagre-d3/dagre-d3-tests.ts index d3dc72b648..23872077dd 100644 --- a/types/dagre-d3/dagre-d3-tests.ts +++ b/types/dagre-d3/dagre-d3-tests.ts @@ -16,4 +16,5 @@ graph.transition = (selection: d3.Selection) => { const render = new dagreD3.render(); const svg = d3.select("svg"); render.arrows()["arrowType"] = (parent: d3.Selection, id: string, edge: dagre.Edge, type: string) => {}; +render.shapes()["shapeName"] = (parent: d3.Selection, bbox: any, node: dagre.Node) => {}; render(svg, graph); diff --git a/types/dagre-d3/index.d.ts b/types/dagre-d3/index.d.ts index dc0d8ad639..d402fec730 100644 --- a/types/dagre-d3/index.d.ts +++ b/types/dagre-d3/index.d.ts @@ -11,6 +11,7 @@ export as namespace dagreD3; export * from "dagre"; export const render: { new(): Render }; +export const intersect: { [shapeName: string]: (node: dagre.Node, points: Array<{}>, point: any) => void }; declare module "dagre" { namespace graphlib { @@ -32,4 +33,5 @@ export interface Render { // see http://cpettitt.github.io/project/dagre-d3/latest/demo/user-defined.html for example usage arrows(): { [arrowStyleName: string]: (parent: d3.Selection, id: string, edge: dagre.Edge, type: string) => void }; (selection: d3.Selection, g: dagre.graphlib.Graph): void; + shapes(): { [shapeStyleName: string]: (parent: d3.Selection, bbox: any, node: dagre.Node) => void }; } diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 5b059a0ee4..6119f625d4 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -13,7 +13,6 @@ // TypeScript Version: 2.8 /// -/// declare module 'ember' { import { @@ -25,7 +24,7 @@ declare module 'ember' { } from 'ember/-private-types/object/computed'; import { Objectify, Fix, KeysOfType, TypeLookup } from 'ember/-private-types/utils'; import { EmberClassArguments, EmberClassConstructor, EmberInstanceArguments } from 'ember/-private-types/object'; - + import * as HandlebarsNamespace from 'handlebars'; // Capitalization is intentional: this makes it much easier to re-export RSVP on // the Ember namespace. import Rsvp from 'rsvp'; @@ -34,6 +33,8 @@ declare module 'ember' { import { Registry as ServiceRegistry } from '@ember/service'; import { Registry as ControllerRegistry } from '@ember/controller'; import ModuleComputed from '@ember/object/computed'; + import * as EmberString from '@ember/string'; + import * as EmberPolyfills from '@ember/polyfills'; // Get an alias to the global Array type to use in inner scope below. type GlobalArray = T[]; @@ -1733,11 +1734,11 @@ declare module 'ember' { key: keyof this, target: Target, method: ObserverMethod - ): void; + ): this; addObserver( key: keyof this, method: ObserverMethod - ): void; + ): this; /** * Remove an observer you have previously registered on this object. Pass * the same key, target, and method you passed to `addObserver()` and your @@ -1747,11 +1748,11 @@ declare module 'ember' { key: keyof this, target: Target, method: ObserverMethod - ): any; + ): this; removeObserver( key: keyof this, method: ObserverMethod - ): any; + ): this; /** * Retrieves the value of a property, or a default value in the case that the * property returns `undefined`. @@ -2421,27 +2422,24 @@ declare module 'ember' { function K(): any; function createFrame(objec: any): any; function Exception(message: string): void; - class SafeString { - constructor(str: string); - toString(): string; - } + const SafeString: typeof HandlebarsNamespace.SafeString; function parse(string: string): any; function print(ast: any): void; const logger: typeof Ember.Logger; function log(level: string, str: string): void; } namespace String { - function camelize(str: string): string; - function capitalize(str: string): string; - function classify(str: string): string; - function dasherize(str: string): string; - function decamelize(str: string): string; + const camelize: typeof EmberString.camelize; + const capitalize: typeof EmberString.capitalize; + const classify: typeof EmberString.classify; + const dasherize: typeof EmberString.dasherize; + const decamelize: typeof EmberString.decamelize; function fmt(...args: string[]): string; - function htmlSafe(str: string): Handlebars.SafeString; - function isHTMLSafe(str: string): boolean; - function loc(template: string, args?: string[]): string; - function underscore(str: string): string; - function w(str: string): string[]; + const htmlSafe: typeof EmberString.htmlSafe; + const isHTMLSafe: typeof EmberString.isHTMLSafe; + const loc: typeof EmberString.loc; + const underscore: typeof EmberString.underscore; + const w: typeof EmberString.w; } const computed: { (cb: ComputedPropertyCallback): ComputedProperty; @@ -3138,11 +3136,7 @@ declare module 'ember' { * A value is present if it not `isBlank`. */ function isPresent(obj?: any): boolean; - /** - * Merge the contents of two objects together into the first object. - * @deprecated Use Object.assign - */ - function merge(original: T, updates: U): Mix; + const merge: typeof EmberPolyfills.merge; /** * Makes a method available via an additional name. */ @@ -3150,33 +3144,33 @@ declare module 'ember' { /** * Specify a method that observes property changes. */ - function observer(key1: string, func: (target: any, key: string) => void): void; - function observer( + function observer void>(key1: string, func: Fn): Fn; + function observer void>( key1: string, key2: string, - func: (target: any, key: string) => void - ): void; - function observer( + func: Fn + ): Fn; + function observer void>( key1: string, key2: string, key3: string, - func: (target: any, key: string) => void - ): void; - function observer( + func: Fn + ): Fn; + function observer void>( key1: string, key2: string, key3: string, key4: string, - func: (target: any, key: string) => void - ): void; - function observer( + func: Fn + ): Fn; + function observer void>( key1: string, key2: string, key3: string, key4: string, key5: string, - func: (target: any, key: string) => void - ): void; + func: Fn + ): Fn; /** * Adds an observer on a property. */ @@ -3233,6 +3227,11 @@ declare module 'ember' { key: K, value: UnwrapComputedPropertySetter ): UnwrapComputedPropertyGetter; + function set( + obj: T, + key: K, + value: T[K] + ): T[K]; /** * Error-tolerant form of `Ember.set`. Will not blow up if any part of the * chain is `undefined`, `null`, or destroyed. @@ -3247,6 +3246,11 @@ declare module 'ember' { obj: T, hash: Pick, K> ): Pick, K>; + // TODO: in TS2.9 - Pick | T, K> + function setProperties( + obj: T, + hash: Pick + ): Pick; /** * Detects when a specific package of Ember (e.g. 'Ember.Application') * has fully loaded and is available for extension. @@ -3289,14 +3293,12 @@ declare module 'ember' { function typeOf(value: T): KeysOfType; function typeOf(): 'undefined'; function typeOf(item: any): string; + // TODO: replace with an es6 reexport when declare module 'ember' is removed /** * Copy properties from a source object to a target object. * @deprecated Use Object.assign */ - function assign(target: T, source: U): Mix; - function assign(target: T, source1: U, source2: V): Mix3; - function assign(target: T, source1: U, source2: V, source3: W): Mix4; - + const assign: typeof EmberPolyfills.assign; /** * Polyfill for Object.create * @deprecated Use Object.create @@ -3331,12 +3333,6 @@ declare module 'ember' { : undefined; function tryInvoke(obj: T, methodName: FNAME): T[FNAME] extends (() => any) ? ReturnType : undefined; function tryInvoke(obj: object, methodName: string, args?: any[]): undefined; - /** - * Forces the passed object to be part of an array. If the object is already - * an array, it will return the object. Otherwise, it will add the object to - * an array. If obj is `null` or `undefined`, it will return an empty array. - */ - function makeArray(obj?: T[] | T | null): T[]; /** * Framework objects in an Ember application (components, services, routes, etc.) * are created via a factory and dependency injection system. Each of these @@ -3551,7 +3547,6 @@ declare module '@ember/array' { export default EmberArray; export const A: typeof Ember.A; export const isArray: typeof Ember.isArray; - export const makeArray: typeof Ember.makeArray; } declare module '@ember/array/mutable' { @@ -3647,37 +3642,12 @@ declare module '@ember/engine/instance' { export default class EngineInstance extends Ember.EngineInstance { } } -declare module '@ember/enumerable' { - import Ember from 'ember'; - type Enumerable = Ember.Enumerable; - const Enumerable: typeof Ember.Enumerable; - export default Enumerable; -} - declare module '@ember/error' { import Ember from 'ember'; const Error: typeof Ember.Error; export default Error; } -declare module '@ember/instrumentation' { - import Ember from 'ember'; - export const instrument: typeof Ember.instrument; - export const reset: typeof Ember.reset; - export const subscribe: typeof Ember.subscribe; - export const unsubscribe: typeof Ember.unsubscribe; -} - -declare module '@ember/map' { - import Ember from 'ember'; - export default class EmberMap extends Ember.Map { } -} - -declare module '@ember/map/with-default' { - import Ember from 'ember'; - export default class MapWithDefault extends Ember.MapWithDefault { } -} - declare module '@ember/object' { import Ember from 'ember'; export default class EmberObject extends Ember.Object { } @@ -3790,15 +3760,6 @@ declare module '@ember/object/proxy' { export default class ObjectProxy extends Ember.ObjectProxy { } } -declare module '@ember/polyfills' { - import Ember from 'ember'; - export const assign: typeof Ember.assign; - export const create: typeof Ember.create; - export const hasPropertyAccessors: typeof Ember.platform.hasPropertyAccessors; - export const keys: typeof Ember.keys; - export const merge: typeof Ember.merge; -} - declare module '@ember/routing/auto-location' { import Ember from 'ember'; export default class AutoLocation extends Ember.AutoLocation { } @@ -3872,20 +3833,6 @@ declare module '@ember/service' { interface Registry {} } -declare module '@ember/string' { - import Ember from 'ember'; - export const camelize: typeof Ember.String.camelize; - export const capitalize: typeof Ember.String.capitalize; - export const classify: typeof Ember.String.classify; - export const dasherize: typeof Ember.String.dasherize; - export const decamelize: typeof Ember.String.decamelize; - export const htmlSafe: typeof Ember.String.htmlSafe; - export const isHTMLSafe: typeof Ember.String.isHTMLSafe; - export const loc: typeof Ember.String.loc; - export const underscore: typeof Ember.String.underscore; - export const w: typeof Ember.String.w; -} - declare module '@ember/test' { import Ember from 'ember'; export const registerAsyncHelper: typeof Ember.Test.registerAsyncHelper; diff --git a/types/ember/test/object.ts b/types/ember/test/object.ts index 7446d5e3ef..4547bd40af 100755 --- a/types/ember/test/object.ts +++ b/types/ember/test/object.ts @@ -49,3 +49,20 @@ class Foo extends Ember.Object.extend({ }); } } + +export class Foo2 extends Ember.Object { + name!: string; + + changeName(name: string) { + let a: string = this.set('name', name); + let b: number = this.set('name', name); // $ExpectError + let x: string = Ember.set(this, 'name', name); + let y: number = Ember.set(this, 'name', name); // $ExpectError + this.setProperties({ + name + }); + Ember.setProperties(this, { + name + }); + } +} diff --git a/types/ember/test/private/observable-tests.ts b/types/ember/test/private/observable-tests.ts index be3d4bd69f..1a789cc114 100644 --- a/types/ember/test/private/observable-tests.ts +++ b/types/ember/test/private/observable-tests.ts @@ -69,13 +69,13 @@ class DemoObservable implements Observable { notifyPropertyChange(keyName: string): this { throw new Error("Method not implemented."); } - addObserver(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): void; - addObserver(key: K, method: keyof this | ((this: this, sender: this, key: K, value: this[K], rev: number) => void)): void; + addObserver(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): any; + addObserver(key: K, method: keyof this | ((this: this, sender: this, key: K, value: this[K], rev: number) => void)): any; addObserver(key: any, target: any, method?: any) { throw new Error("Method not implemented."); } - removeObserver(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): void; - removeObserver(key: keyof this, method: keyof this | ((this: this, sender: this, key: string, value: any, rev: number) => void)): void; + removeObserver(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): any; + removeObserver(key: keyof this, method: keyof this | ((this: this, sender: this, key: string, value: any, rev: number) => void)): any; removeObserver(key: any, target: any, method?: any): void { throw new Error("Method not implemented."); } diff --git a/types/ember/test/string.ts b/types/ember/test/string.ts index 0543bd60d0..4363b375f3 100644 --- a/types/ember/test/string.ts +++ b/types/ember/test/string.ts @@ -1,4 +1,5 @@ import Ember from 'ember'; +import { SafeString } from 'handlebars'; const { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } = Ember.String; @@ -34,3 +35,7 @@ loc(); // $ExpectError loc("_Hello World"); // $ExpectType string // TODO - fix this case upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/281 loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string + +const handlebarsSafeString: SafeString = Ember.String.htmlSafe('lorem ipsum...'); +Ember.String.htmlSafe('lorem ipsum...'); // $ExpectType SafeString +const regularString: string = Ember.String.htmlSafe('lorem ipsum...'); // $ExpectError diff --git a/types/ember/test/utils.ts b/types/ember/test/utils.ts index 77b52ca218..f9b1f198d2 100755 --- a/types/ember/test/utils.ts +++ b/types/ember/test/utils.ts @@ -62,14 +62,6 @@ function testOnError() { }; } -function testMakeArray() { - assertType(Ember.makeArray()); - assertType(Ember.makeArray(null)); - assertType(Ember.makeArray(undefined)); - assertType(Ember.makeArray('lindsay')); - assertType(Ember.makeArray([1, 2, 42])); -} - function testDeprecateFunc() { function newMethod(first: string, second: number): string { return ''; diff --git a/types/ember/tsconfig.json b/types/ember/tsconfig.json index a267c26dd5..83fbf03610 100755 --- a/types/ember/tsconfig.json +++ b/types/ember/tsconfig.json @@ -14,6 +14,10 @@ "typeRoots": [ "../" ], + "paths": { + "@ember/string": ["ember__string"], + "@ember/polyfills": ["ember__polyfills"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/ember__object/computed.d.ts b/types/ember__object/computed.d.ts new file mode 100644 index 0000000000..cbb68662cd --- /dev/null +++ b/types/ember__object/computed.d.ts @@ -0,0 +1,38 @@ +import Ember from 'ember'; + +type ComputedProperty = Ember.ComputedProperty; +declare const ComputedProperty: typeof Ember.ComputedProperty; +export default ComputedProperty; +export const alias: typeof Ember.computed.alias; +export const and: typeof Ember.computed.and; +export const bool: typeof Ember.computed.bool; +export const collect: typeof Ember.computed.collect; +export const deprecatingAlias: typeof Ember.computed.deprecatingAlias; +export const empty: typeof Ember.computed.empty; +export const equal: typeof Ember.computed.equal; +export const expandProperties: typeof Ember.expandProperties; +export const filter: typeof Ember.computed.filter; +export const filterBy: typeof Ember.computed.filterBy; +export const gt: typeof Ember.computed.gt; +export const gte: typeof Ember.computed.gte; +export const intersect: typeof Ember.computed.intersect; +export const lt: typeof Ember.computed.lt; +export const lte: typeof Ember.computed.lte; +export const map: typeof Ember.computed.map; +export const mapBy: typeof Ember.computed.mapBy; +export const match: typeof Ember.computed.match; +export const max: typeof Ember.computed.max; +export const min: typeof Ember.computed.min; +export const none: typeof Ember.computed.none; +export const not: typeof Ember.computed.not; +export const notEmpty: typeof Ember.computed.notEmpty; +export const oneWay: typeof Ember.computed.oneWay; +export const or: typeof Ember.computed.or; +export const readOnly: typeof Ember.computed.readOnly; +export const reads: typeof Ember.computed.reads; +export const setDiff: typeof Ember.computed.setDiff; +export const sort: typeof Ember.computed.sort; +export const sum: typeof Ember.computed.sum; +export const union: typeof Ember.computed.union; +export const uniq: typeof Ember.computed.uniq; +export const uniqBy: typeof Ember.computed.uniqBy; diff --git a/types/ember__object/core.d.ts b/types/ember__object/core.d.ts new file mode 100644 index 0000000000..9b2d396d6e --- /dev/null +++ b/types/ember__object/core.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class CoreObject extends Ember.CoreObject { } diff --git a/types/ember__object/evented.d.ts b/types/ember__object/evented.d.ts new file mode 100644 index 0000000000..865cab6fa8 --- /dev/null +++ b/types/ember__object/evented.d.ts @@ -0,0 +1,6 @@ +import Ember from 'ember'; + +type Evented = Ember.Evented; +declare const Evented: typeof Ember.Evented; +export default Evented; +export const on: typeof Ember.on; diff --git a/types/ember__object/events.d.ts b/types/ember__object/events.d.ts new file mode 100644 index 0000000000..d0413d5e4b --- /dev/null +++ b/types/ember__object/events.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; + +export const addListener: typeof Ember.addListener; +export const removeListener: typeof Ember.removeListener; +export const sendEvent: typeof Ember.sendEvent; diff --git a/types/ember__object/index.d.ts b/types/ember__object/index.d.ts new file mode 100644 index 0000000000..4633ff534b --- /dev/null +++ b/types/ember__object/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for @ember/object 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; +declare class EmberObject extends Ember.Object { } +export default EmberObject; +export const aliasMethod: typeof Ember.aliasMethod; +export const computed: typeof Ember.computed; +export const defineProperty: typeof Ember.defineProperty; +export const get: typeof Ember.get; +export const getProperties: typeof Ember.getProperties; +export const getWithDefault: typeof Ember.getWithDefault; +export const observer: typeof Ember.observer; +export const set: typeof Ember.set; +export const setProperties: typeof Ember.setProperties; +export const trySet: typeof Ember.trySet; diff --git a/types/ember__object/internals.d.ts b/types/ember__object/internals.d.ts new file mode 100644 index 0000000000..698b6e0b87 --- /dev/null +++ b/types/ember__object/internals.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; + +export const cacheFor: typeof Ember.cacheFor; +export const copy: typeof Ember.copy; +export const guidFor: typeof Ember.guidFor; diff --git a/types/ember__object/mixin.d.ts b/types/ember__object/mixin.d.ts new file mode 100644 index 0000000000..efb03d3994 --- /dev/null +++ b/types/ember__object/mixin.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class Mixin extends Ember.Mixin {} diff --git a/types/ember__object/observable.d.ts b/types/ember__object/observable.d.ts new file mode 100644 index 0000000000..af87192228 --- /dev/null +++ b/types/ember__object/observable.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; + +type Observable = Ember.Observable; +declare const Observable: typeof Ember.Observable; +export default Observable; diff --git a/types/ember__object/observers.d.ts b/types/ember__object/observers.d.ts new file mode 100644 index 0000000000..e084f2da29 --- /dev/null +++ b/types/ember__object/observers.d.ts @@ -0,0 +1,4 @@ +import Ember from 'ember'; + +export const addObserver: typeof Ember.addObserver; +export const removeObserver: typeof Ember.removeObserver; diff --git a/types/ember__object/promise-proxy-mixin.d.ts b/types/ember__object/promise-proxy-mixin.d.ts new file mode 100644 index 0000000000..9ac285aa11 --- /dev/null +++ b/types/ember__object/promise-proxy-mixin.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; + +type PromiseProxyMixin = Ember.PromiseProxyMixin; +declare const PromiseProxyMixin: typeof Ember.PromiseProxyMixin; +export default PromiseProxyMixin; diff --git a/types/ember__object/proxy.d.ts b/types/ember__object/proxy.d.ts new file mode 100644 index 0000000000..d7eeb28ca6 --- /dev/null +++ b/types/ember__object/proxy.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class ObjectProxy extends Ember.ObjectProxy { } diff --git a/types/ember__object/test/access-modifier.ts b/types/ember__object/test/access-modifier.ts new file mode 100644 index 0000000000..281d4e5624 --- /dev/null +++ b/types/ember__object/test/access-modifier.ts @@ -0,0 +1,21 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; + +class Foo extends EmberObject { + hello() { return 'world'; } + protected bar() { return 'bar'; } + private baz() { return 'baz'; } +} +const f = new Foo(); +assertType(f.hello()); +assertType(f.bar()); // $ExpectError +assertType(f.baz()); // $ExpectError + +// TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291 +// class Foo2 extends EmberObject.extend({ +// bar: '' +// }) { +// hello() { return 'world'; } +// protected bar() { return 'bar'; } // $ExpectError +// private baz() { return 'baz'; } +// } diff --git a/types/ember__object/test/computed.ts b/types/ember__object/test/computed.ts new file mode 100644 index 0000000000..481a513856 --- /dev/null +++ b/types/ember__object/test/computed.ts @@ -0,0 +1,198 @@ +import EmberObject, { computed } from '@ember/object'; +import ComputedProperty, { + alias, + or, + and, + filter, + equal, + empty, + filterBy, + notEmpty, + none, + not, + min, + max, + gt, + gte, + lt, + lte, + readOnly, + reads, + setDiff, + sort, + intersect, + mapBy, + match, + map, + oneWay, + sum, + union, + uniqBy, + uniq, + deprecatingAlias, + bool, + collect +} from '@ember/object/computed'; +import { assertType } from './lib/assert'; + +const Person = EmberObject.extend({ + firstName: '', + lastName: '', + age: 0, + + noArgs: computed(() => 'test'), + + fullName: computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }), + + fullNameReadonly: computed('fullName', function() { + return this.get('fullName'); + }).readOnly(), + + fullNameWritable: computed('firstName', 'lastName', { + get() { + return this.get('fullName'); + }, + set(key, value) { + const [first, last] = value.split(' '); + this.set('firstName', first); + this.set('lastName', last); + return value; + } + }), + + fullNameGetOnly: computed('fullName', { + get() { + return this.get('fullName'); + } + }), + + fullNameSetOnly: computed('firstName', 'lastName', { + set(key, value) { + const [first, last] = value.split(' '); + this.set('firstName', first); + this.set('lastName', last); + return value; + } + }), + + combinators: computed(function() { + return this.get('firstName'); + }).property('firstName') + .meta({ foo: 'bar' }) + .volatile() + .readOnly(), + + explicitlyDeclared: alias('fullName') as ComputedProperty, +}); + +const person = Person.create({ + firstName: 'Fred', + lastName: 'Smith', + age: 29, +}); + +assertType(person.firstName); +assertType(person.age); +assertType>(person.noArgs); +assertType>(person.fullName); +assertType>(person.fullNameReadonly); +assertType>(person.fullNameWritable); +assertType>(person.fullNameGetOnly); +assertType>(person.fullNameSetOnly); +assertType>(person.combinators); +assertType>(person.explicitlyDeclared); + +assertType(person.get('firstName')); +assertType(person.get('age')); +assertType(person.get('noArgs')); +assertType(person.get('fullName')); +assertType(person.get('fullNameReadonly')); +assertType(person.get('fullNameWritable')); +assertType(person.get('fullNameGetOnly')); +assertType(person.get('fullNameSetOnly')); +assertType(person.get('combinators')); +assertType(person.get('explicitlyDeclared')); + +assertType<{ firstName: string, fullName: string, age: number }>(person.getProperties('firstName', 'fullName', 'age')); + +const person2 = Person.create({ + fullName: 'Fred Smith' +}); + +assertType(person2.get('firstName')); +assertType(person2.get('fullName')); + +const person3 = Person.extend({ + firstName: 'Fred', + fullName: 'Fred Smith' +}).create(); + +assertType(person3.get('firstName')); +assertType(person3.get('fullName')); + +const person4 = Person.extend({ + firstName: computed(() => 'Fred'), + fullName: computed(() => 'Fred Smith') +}).create(); + +assertType(person4.get('firstName')); +assertType(person4.get('fullName')); + +// computed property macros +const objectWithComputedProperties = EmberObject.extend({ + alias: alias('foo'), + and: and('foo', 'bar', 'baz', 'qux'), + bool: bool('foo'), + collect: collect('foo', 'bar', 'baz', 'qux'), + deprecatingAlias: deprecatingAlias('foo', { + id: 'hamster.deprecate-banana', + until: '3.0.0' + }), + empty: empty('foo'), + equalNumber: equal('foo', 1), + equalString: equal('foo', 'bar'), + equalObject: equal('foo', {}), + filter: filter('foo', (item) => item === 'bar'), + filterBy1: filterBy('foo', 'bar'), + filterBy2: filterBy('foo', 'bar', false), + gt: gt('foo', 3), + gte: gte('foo', 3), + intersect: intersect('foo', 'bar', 'baz', 'qux'), + lt: lt('foo', 3), + lte: lte('foo', 3), + map: map('foo', (item, index) => item.bar), + mapBy: mapBy('foo', 'bar'), + match: match('foo', /^tom.ter$/), + max: max('foo'), + min: min('foo'), + none: none('foo'), + not: not('foo'), + notEmpty: notEmpty('foo'), + oneWay: oneWay('foo'), + or: or('foo', 'bar', 'baz', 'qux'), + readOnly: readOnly('foo'), + reads: reads('foo'), + setDiff: setDiff('foo', 'bar'), + sort1: sort('foo', 'bar'), + sort2: sort('foo', (itemA, itemB) => { + if (itemA < itemB) { + return -1; + } else if (itemA > itemB) { + return 1; + } else { + return 0; + } + }), + sum: sum('foo'), + union: union('foo', 'bar', 'baz', 'qux'), + uniq: uniq('foo'), + uniqBy: uniqBy('foo', 'bar') +}); + +const component2 = EmberObject.extend({ + isAnimal: or('isDog', 'isCat') +}).create(); + +assertType(component2.get('isAnimal')); diff --git a/types/ember__object/test/core.ts b/types/ember__object/test/core.ts new file mode 100644 index 0000000000..984f5eec12 --- /dev/null +++ b/types/ember__object/test/core.ts @@ -0,0 +1,198 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +/** Newable tests */ +const co1 = new Ember.CoreObject(); + +// TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// co1.concatenatedProperties; // $ExpectType string[] +co1.isDestroyed; // $ExpectType boolean +co1.isDestroying; // $ExpectType boolean +co1.destroy(); // $ExpectType CoreObject +co1.toString(); // $ExpectType string + +/** .create tests */ +const co2 = Ember.CoreObject.create(); +// TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// co2.concatenatedProperties; // $ExpectType string[] +co2.isDestroyed; // $ExpectType boolean +co2.isDestroying; // $ExpectType boolean +co2.destroy(); // $ExpectType CoreObject +co2.toString(); // $ExpectType string + +/** .create tests w/ initial instance data passed in */ +const co3 = Ember.CoreObject.create({ foo: '123', bar: 456 }); + +co3.foo; // $ExpectType string +co3.bar; // $ExpectType number + +/** .extend with a zero-argument .create() */ +const co4 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz(): [string, number] { + return [this.foo, this.bar]; + } +}).create(); + +co4.foo; // $ExpectType string +co4.bar; // $ExpectType number +co4.baz; // $ExpectType () => [string, number] + +/** .extend with inconsistent arguments passed into .create() */ +const class05 = Ember.CoreObject.extend({ + foo: '123' as (string | boolean), + bar: 456, + baz() { + return [this.foo, this.bar]; + } +}); +const c05 = class05.create({ foo: 99 }); // $ExpectError +const c05b = class05.create({ foo: true }); +const c05c = class05.create({ foo: 'abc' }); +assertType(c05b.foo); // $ExpectError +assertType(c05c.foo); // $ExpectError + +/** two .extend arguments with a zero-argument .create() */ +const co6 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } +}, { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + } +}).create(); + +// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// assertType(co6.foo); // $ExpectError +assertType(co6.bar); // $ExpectType number +assertType<() => Array>(co6.baz); // $ExpectType () => (string | number)[] + +/** three .extend arguments with a zero-argument .create() */ +const co7 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } +}, { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + } +}, { + foo: '99', + money: 'in the banana stand', + func3() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.money; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + } +}).create(); +// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// assertType(co7.foo); // $ExpectError +assertType(co7.bar); // $ExpectType number +assertType(co7.money); // $ExpectType string +assertType<() => Array>(co7.baz); // $ExpectType () => (string | number)[] + +/** four .extend arguments with a zero-argument .create() */ +const co8 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } +}, { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + // this does not include stuff from later extend args + this.money; // $ExpectError + } +}, { + foo: '99', + money: 'in the banana stand', + func3() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.money; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + // this does not include stuff from later extend args + this.neighborhood; // $ExpectError + } +}, { + foo: '99', + neighborhood: 'sudden valley', + func4() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.neighborhood; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + this.money; // $ExpectType string + } +}).create(); + +// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// assertType(co8.foo); // $ExpectError +assertType(co8.bar); // $ExpectType number +assertType(co8.money); // $ExpectType string +assertType<() => Array>(co8.baz); // $ExpectType () => (string | number)[] diff --git a/types/ember__object/test/create-negative.ts b/types/ember__object/test/create-negative.ts new file mode 100644 index 0000000000..2298ae8cf3 --- /dev/null +++ b/types/ember__object/test/create-negative.ts @@ -0,0 +1,9 @@ +import { assertType } from './lib/assert'; +import Ember from 'ember'; +import { PersonWithNumberName, Person } from './create'; + +Person.create({ firstName: 99 }); // $ExpectError +Person.create({}, { firstName: 99 }); // $ExpectError +Person.create({}, {}, { firstName: 99 }); // $ExpectError + +const p4 = new PersonWithNumberName(); diff --git a/types/ember__object/test/create.ts b/types/ember__object/test/create.ts new file mode 100644 index 0000000000..fbc1b3600a --- /dev/null +++ b/types/ember__object/test/create.ts @@ -0,0 +1,54 @@ +import { assertType } from './lib/assert'; +import EmberObject, { computed } from '@ember/object'; +import ComputedProperty from '@ember/object/computed'; + +/** + * Zero-argument case + */ +const o = EmberObject.create(); +// create returns an object +assertType(o); +// object returned by create type-checks as an instance of Ember.Object +assertType(o.isDestroyed); // from instance +assertType(o.isDestroying); // from instance +assertType<(key: keyof EmberObject) => any>(o.get); // from prototype + +/** + * One-argument case + */ +const o1 = EmberObject.create({x: 9, y: 'hello', z: false}); +assertType(o1.x); +assertType(o1.y); +o1.y; // $ExpectType string +o1.z; // $ExpectType boolean + +const obj = EmberObject.create({ a: 1 }, { b: 2 }, { c: 3 }); +assertType(obj.b); +assertType(obj.a); +assertType(obj.c); + +export class Person extends EmberObject { + fullName = computed('firstName', 'lastName', function() { + return [this.firstName + this.lastName].join(' '); + }); + firstName: string; + lastName: string; + age: number; +} +const p = new Person(); + +assertType(p.firstName); +assertType>(p.fullName); +assertType(p.get('fullName')); + +const p2 = Person.create({ firstName: 'string' }); +const p2b = Person.create({}, { firstName: 'string' }); +const p2c = Person.create({}, {}, { firstName: 'string' }); + +export class PersonWithNumberName extends Person.extend({ + fullName: 6 +}) {} + +const p4 = new PersonWithNumberName(); +assertType(p4.firstName); +assertType(p4.fullName); diff --git a/types/ember__object/test/detect-instance.ts b/types/ember__object/test/detect-instance.ts new file mode 100755 index 0000000000..d65fa0f686 --- /dev/null +++ b/types/ember__object/test/detect-instance.ts @@ -0,0 +1,20 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; + +const ExtendClass = EmberObject.extend({ + foo: 'hello' +}); + +class ES6Class extends EmberObject { + bar: string; +} + +const testObject = null; + +if (ExtendClass.detectInstance(testObject)) { + assertType(testObject.foo); +} + +if (ES6Class.detectInstance(testObject)) { + assertType(testObject.bar); +} diff --git a/types/ember__object/test/detect.ts b/types/ember__object/test/detect.ts new file mode 100755 index 0000000000..878acced29 --- /dev/null +++ b/types/ember__object/test/detect.ts @@ -0,0 +1,20 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; + +const ExtendClass = EmberObject.extend({ + foo: 'hello' +}); + +class ES6Class extends EmberObject { + bar: string; +} + +const TestClass = EmberObject; + +if (ExtendClass.detect(TestClass)) { + assertType(TestClass.create().foo); +} + +if (ES6Class.detect(TestClass)) { + assertType(TestClass.create().bar); +} diff --git a/types/ember__object/test/event.ts b/types/ember__object/test/event.ts new file mode 100644 index 0000000000..b54529d587 --- /dev/null +++ b/types/ember__object/test/event.ts @@ -0,0 +1,61 @@ +import EmberObject, { observer } from '@ember/object'; +import { sendEvent, addListener, removeListener } from '@ember/object/events'; +import Evented, { on } from '@ember/object/evented'; + +function testOn() { + const Job = EmberObject.extend({ + logCompleted: on('completed', () => { + console.log('Job completed!'); + }) + }); + + const job = Job.create(); + + sendEvent(job, 'completed'); // Logs 'Job completed!' +} + +function testEvented() { + const Person = EmberObject.extend(Evented, { + greet() { + this.trigger('greet'); + } + }); + + const person = Person.create(); + + person.on('greet', () => { + console.log('Our person has greeted'); + }); + + person.on('greet', () => { + console.log('Our person has greeted'); + }).one('greet', () => { + console.log('Offer one-time special'); + }).off('event', {}, () => {}); + + person.greet(); +} + +function testObserver() { + EmberObject.extend({ + // TODO: enable after https://github.com/typed-ember/ember-cli-typescript/issues/290 + // valueObserver: observer('value', () => { + // // Executes whenever the "value" property changes + // }) + }); +} + +function testListener() { + EmberObject.extend({ + init() { + addListener(this, 'willDestroy', this, 'willDestroyListener'); + addListener(this, 'willDestroy', this, 'willDestroyListener', true); + addListener(this, 'willDestroy', this, this.willDestroyListener); + addListener(this, 'willDestroy', this, this.willDestroyListener, true); + removeListener(this, 'willDestroy', this, 'willDestroyListener'); + removeListener(this, 'willDestroy', this, this.willDestroyListener); + }, + willDestroyListener() { + } + }); +} diff --git a/types/ember__object/test/extend.ts b/types/ember__object/test/extend.ts new file mode 100644 index 0000000000..8d61168dc3 --- /dev/null +++ b/types/ember__object/test/extend.ts @@ -0,0 +1,61 @@ +import EmberObject from '@ember/object'; +import { assertType } from './lib/assert'; + +const Person = EmberObject.extend({ + firstName: '', + lastName: '', + + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, + getFullName2(): string { + return `${this.get('firstName')} ${this.get('lastName')}`; + } +}); + +assertType(Person.prototype.firstName); +assertType<() => string>(Person.prototype.getFullName); + +const person = Person.create({ + firstName: 'Joe', + lastName: 'Blow', + extra: 42 +}); + +assertType(person.getFullName()); +assertType(person.extra); + +class ES6Person extends EmberObject { + firstName: string; + lastName: string; + + get fullName() { + return `${this.firstName} ${this.lastName}`; + } + get fullName2(): string { + return `${this.get('firstName')} ${this.get('lastName')}`; + } +} + +assertType(ES6Person.prototype.firstName); +assertType(ES6Person.prototype.fullName); + +const es6Person = ES6Person.create({ + firstName: 'Joe', + lastName: 'Blow', + extra: 42 +}); + +assertType(es6Person.fullName); +assertType(es6Person.extra); + +class PersonWithStatics extends EmberObject { + static isPerson = true; +} +const PersonWithStatics2 = PersonWithStatics.extend({}); +class PersonWithStatics3 extends PersonWithStatics {} +class PersonWithStatics4 extends PersonWithStatics2 {} +assertType(PersonWithStatics.isPerson); +assertType(PersonWithStatics2.isPerson); +assertType(PersonWithStatics3.isPerson); +assertType(PersonWithStatics4.isPerson); diff --git a/types/ember__object/test/lib/assert.ts b/types/ember__object/test/lib/assert.ts new file mode 100644 index 0000000000..262d18bc2c --- /dev/null +++ b/types/ember__object/test/lib/assert.ts @@ -0,0 +1,5 @@ +/** Static assertion that `value` has type `T` */ +// Disable tslint here b/c the generic is used to let us do a type coercion and +// validate that coercion works for the type value "passed into" the function. +// tslint:disable-next-line:no-unnecessary-generics +export declare function assertType(value: T): T; diff --git a/types/ember__object/test/object.ts b/types/ember__object/test/object.ts new file mode 100644 index 0000000000..b47aa22ffb --- /dev/null +++ b/types/ember__object/test/object.ts @@ -0,0 +1,75 @@ +import EmberObject, { computed } from "@ember/object"; + +const LifetimeHooks = EmberObject.extend({ + resource: null as {} | null, + + init() { + this._super(); + this.resource = {}; + }, + + willDestroy() { + delete this.resource; + this._super(); + } +}); + +class MyObject30 extends EmberObject { + constructor() { + super(); + } +} + +class MyObject31 extends EmberObject { + constructor(properties: object) { + super(properties); + } +} + +class Foo extends EmberObject { + a = computed({ + get() { return ''; }, + set(key: string, newVal: string) { return ''; } + }); + b = 5; + baz() { + const y = this.b; // $ExpectType number + const z = this.a; // $ExpectType ComputedProperty + this.b = 10; + this.get('b').toFixed(4); // $ExpectType string + this.set('a', 'abc').split(','); // $ExpectType string[] + this.set('b', 10).toFixed(4); // $ExpectType string + + this.setProperties({ b: 11 }); + // this.setProperties({ b: '11' }); // $ExpectError + this.setProperties({ + a: 'def', + b: 11 + }); + } +} + +// TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291 +// class Foo extends EmberObject.extend({ +// a: computed({ +// get() { return ''; }, +// set(key: string, newVal: string) { return ''; } +// }) +// }) { +// b = 5; +// baz() { +// const y = this.b; // $ExpectType number +// const z = this.a; // $ExpectType ComputedProperty +// this.b = 10; +// this.get('b').toFixed(4); // $ExpectType string +// this.set('a', 'abc').split(','); // $ExpectType string[] +// this.set('b', 10).toFixed(4); // $ExpectType string + +// this.setProperties({ b: 11 }); +// // this.setProperties({ b: '11' }); // $ExpectError +// this.setProperties({ +// a: 'def', +// b: 11 +// }); +// } +// } diff --git a/types/ember__object/test/observable.ts b/types/ember__object/test/observable.ts new file mode 100644 index 0000000000..baa8e3d09a --- /dev/null +++ b/types/ember__object/test/observable.ts @@ -0,0 +1,114 @@ +import { assertType } from './lib/assert'; +import EmberObject, { computed, getWithDefault, getProperties, get, setProperties, set } from '@ember/object'; +import { removeObserver, addObserver } from '@ember/object/observers'; + +class MyComponent extends EmberObject { + foo = 'bar'; + + init() { + this._super.apply(this, arguments); + this.addObserver('foo', this, 'fooDidChange'); + this.addObserver('foo', this, this.fooDidChange); + addObserver(this, 'foo', this, 'fooDidChange'); + addObserver(this, 'foo', this, this.fooDidChange); + this.removeObserver('foo', this, 'fooDidChange'); + this.removeObserver('foo', this, this.fooDidChange); + removeObserver(this, 'foo', this, 'fooDidChange'); + removeObserver(this, 'foo', this, this.fooDidChange); + const lambda = () => { + this.fooDidChange(this, 'foo'); + }; + this.addObserver('foo', lambda); + this.removeObserver('foo', lambda); + addObserver(this, 'foo', lambda); + removeObserver(this, 'foo', lambda); + } + + fooDidChange(sender: this, key: keyof this) { + // your code + } +} + +const myComponent = MyComponent.create(); +myComponent.addObserver('foo', null, () => {}); +myComponent.set('foo', 'baz'); + +const person = EmberObject.create({ + name: 'Fred', + age: 29, + capitalized: computed(function() { + return this.get('name').toUpperCase(); + }) +}); + +const pojo = { name: 'Fred', age: 29 }; + +function testGet() { + assertType(get(person, 'name')); + assertType(get(person, 'age')); + assertType(get(person, 'capitalized')); + assertType(person.get('name')); + assertType(person.get('age')); + assertType(person.get('capitalized')); + assertType(get(pojo, 'name')); +} + +function testGetProperties() { + assertType<{ name: string }>(getProperties(person, 'name')); + assertType<{ name: string, age: number }>(getProperties(person, 'name', 'age')); + assertType<{ name: string, age: number }>(getProperties(person, [ 'name', 'age' ])); + assertType<{ name: string, age: number, capitalized: string }>(getProperties(person, 'name', 'age', 'capitalized')); + assertType<{ name: string }>(person.getProperties('name')); + assertType<{ name: string, age: number }>(person.getProperties('name', 'age')); + assertType<{ name: string, age: number }>(person.getProperties([ 'name', 'age' ])); + assertType<{ name: string, age: number, capitalized: string }>(person.getProperties('name', 'age', 'capitalized')); + assertType<{ name: string, age: number }>(getProperties(pojo, 'name', 'age')); +} + +function testGetWithDefault() { + assertType(getWithDefault(person, 'name', 'Joe')); + assertType(getWithDefault(person, 'age', 20)); + assertType(getWithDefault(person, 'capitalized', 'JOE')); + assertType(person.getWithDefault('name', 'Joe')); + assertType(person.getWithDefault('age', 20)); + assertType(person.getWithDefault('capitalized', 'JOE')); + assertType(getWithDefault(pojo, 'name', 'JOE')); +} + +function testSet() { + assertType(set(person, 'name', 'Joe')); + assertType(set(person, 'age', 35)); + assertType(set(person, 'capitalized', 'JOE')); + assertType(person.set('name', 'Joe')); + assertType(person.set('age', 35)); + assertType(person.set('capitalized', 'JOE')); + assertType(set(pojo, 'name', 'Joe')); +} + +function testSetProperties() { + assertType<{ name: string }>(setProperties(person, { name: 'Joe' })); + assertType<{ name: string, age: number }>(setProperties(person, { name: 'Joe', age: 35 })); + assertType<{ name: string, capitalized: string }>(setProperties(person, { name: 'Joe', capitalized: 'JOE' })); + assertType<{ name: string }>(person.setProperties({ name: 'Joe' })); + assertType<{ name: string, age: number }>(person.setProperties({ name: 'Joe', age: 35 })); + assertType<{ name: string, capitalized: string }>(person.setProperties({ name: 'Joe', capitalized: 'JOE' })); + assertType<{ name: string, age: number }>(setProperties(pojo, { name: 'Joe', age: 35 })); +} + +function testDynamic() { + const obj: any = {}; + const dynamicKey: string = 'dummy'; // tslint:disable-line:no-inferrable-types + + assertType(get(obj, 'dummy')); + assertType(get(obj, dynamicKey)); + assertType(getWithDefault(obj, 'dummy', 'default')); + assertType(getWithDefault(obj, dynamicKey, 'default')); + assertType<{ dummy: any }>(getProperties(obj, 'dummy')); + assertType<{ dummy: any }>(getProperties(obj, [ 'dummy' ])); + assertType(getProperties(obj, dynamicKey)); + assertType(getProperties(obj, [ dynamicKey ])); + assertType(set(obj, 'dummy', 'value')); + assertType(set(obj, dynamicKey, 'value')); + assertType<{ dummy: string }>(setProperties(obj, { dummy: 'value '})); + assertType(setProperties(obj, { [dynamicKey]: 'value' })); +} diff --git a/types/ember__object/test/reopen.ts b/types/ember__object/test/reopen.ts new file mode 100644 index 0000000000..13084c4bce --- /dev/null +++ b/types/ember__object/test/reopen.ts @@ -0,0 +1,72 @@ +import { assertType } from "./lib/assert"; +import EmberObject from "@ember/object"; +import Mixin from "@ember/object/mixin"; + +type Person = typeof Person.prototype; +const Person = EmberObject.extend({ + name: '', + sayHello() { + alert(`Hello. My name is ${this.get('name')}`); + } +}); + +assertType(Person.reopen()); + +assertType(Person.create().name); +// tslint:disable-next-line no-void-expression +assertType(Person.create().sayHello()); + +const Person2 = Person.reopenClass({ + species: 'Homo sapiens', + + createPerson(name: string): Person { + return Person.create({ name }); + } +}); + +assertType(Person2.create().name); +// tslint:disable-next-line no-void-expression +assertType(Person2.create().sayHello()); +assertType(Person2.species); + +const tom = Person2.create({ + name: 'Tom Dale' +}); + +const badTom = Person2.create({ name: 99 }); // $ExpectError + +const yehuda = Person2.createPerson('Yehuda Katz'); + +tom.sayHello(); // "Hello. My name is Tom Dale" +yehuda.sayHello(); // "Hello. My name is Yehuda Katz" +alert(Person2.species); // "Homo sapiens" + +const Person3 = Person2.reopen({ + goodbyeMessage: 'goodbye', + + sayGoodbye() { + alert(`${this.get('goodbyeMessage')}, ${this.get('name')}`); + } +}); + +const person3 = Person3.create(); +person3.get('name'); +person3.get('goodbyeMessage'); +person3.sayHello(); +person3.sayGoodbye(); + +interface AutoResizeMixin { resizable: true; } +declare const AutoResizeMixin: Mixin; + +const ResizableTextArea = EmberObject.reopen(AutoResizeMixin, { + scaling: 1.0 +}); +const text = ResizableTextArea.create(); +// TODO fix upstream +// assertType(text.resizable); +assertType(text.scaling); + +const Reopened = EmberObject.reopenClass({ a: 1 }, { b: 2 }, { c: 3 }); +assertType(Reopened.a); +assertType(Reopened.b); +assertType(Reopened.c); diff --git a/types/ember__object/tsconfig.json b/types/ember__object/tsconfig.json new file mode 100644 index 0000000000..e8f6e13c92 --- /dev/null +++ b/types/ember__object/tsconfig.json @@ -0,0 +1,51 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/object": ["ember__object"], + "@ember/object/*": ["ember__object/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "computed.d.ts", + "core.d.ts", + "evented.d.ts", + "events.d.ts", + "index.d.ts", + "internals.d.ts", + "mixin.d.ts", + "observable.d.ts", + "observers.d.ts", + "promise-proxy-mixin.d.ts", + "proxy.d.ts", + "test/lib/assert.ts", + "test/access-modifier.ts", + "test/core.ts", + "test/computed.ts", + "test/create.ts", + "test/create-negative.ts", + "test/detect.ts", + "test/detect-instance.ts", + "test/event.ts", + "test/extend.ts", + "test/object.ts", + "test/observable.ts", + "test/reopen.ts" + ] +} diff --git a/types/ember__object/tslint.json b/types/ember__object/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/ember__object/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} diff --git a/types/ember__polyfills/ember__polyfills-tests.ts b/types/ember__polyfills/ember__polyfills-tests.ts index 044ed0413c..68a6588a69 100644 --- a/types/ember__polyfills/ember__polyfills-tests.ts +++ b/types/ember__polyfills/ember__polyfills-tests.ts @@ -6,13 +6,10 @@ import { assign, merge } from '@ember/polyfills'; assign({ a: 6 }, { a: 'b'}).a; // $ExpectType string assign({ a: 6 }, {}).a; // $ExpectType number assign({ b: 6 }, {}).a; // $ExpectError - // TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291 - // assign({}, { b: 6 }, {}).b; // $ExpectType number + assign({}, { b: 6 }, {}).b; // $ExpectType number assign({ a: 'hello' }, { b: 6 }, {}).a; // $ExpectType string - // TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291 - // assign({ a: 'hello' }, { b: 6 }, { a: true }).a; // $ExpectType boolean - // TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291 - // assign({ a: 'hello' }, '', { a: true }).a; // $ExpectError + assign({ a: 'hello' }, { b: 6 }, { a: true }).a; // $ExpectType boolean + assign({ a: 'hello' }, '', { a: true }).a; // $ExpectError assign({ d: ['gobias industries'] }, { a: 'hello' }, { b: 6 }, { a: true }).d; // $ExpectType string[] })(); diff --git a/types/ember__polyfills/index.d.ts b/types/ember__polyfills/index.d.ts index 2a3c9b4a93..1bca6dbba4 100644 --- a/types/ember__polyfills/index.d.ts +++ b/types/ember__polyfills/index.d.ts @@ -4,7 +4,18 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import Ember from 'ember'; +import { Mix, Mix3, Mix4 } from './types'; -export const assign: typeof Ember.assign; -export const merge: typeof Ember.merge; +/** + * Copy properties from a source object to a target object. + * @deprecated Use Object.assign + */ +export function assign(target: T, source: U): Mix; +export function assign(target: T, source1: U, source2: V): Mix3; +export function assign(target: T, source1: U, source2: V, source3: W): Mix4; + +/** + * Merge the contents of two objects together into the first object. + * @deprecated Use Object.assign + */ +export function merge(original: T, updates: U): Mix; diff --git a/types/ember__polyfills/tsconfig.json b/types/ember__polyfills/tsconfig.json index a2a6bd371b..ab08b95d99 100644 --- a/types/ember__polyfills/tsconfig.json +++ b/types/ember__polyfills/tsconfig.json @@ -15,7 +15,8 @@ "../" ], "paths": { - "@ember/polyfills": ["ember__polyfills"] + "@ember/polyfills": ["ember__polyfills"], + "@ember/polyfills/*": ["ember__polyfills/*"] }, "types": [], "noEmit": true, @@ -23,6 +24,7 @@ }, "files": [ "index.d.ts", + "types.d.ts", "ember__polyfills-tests.ts" ] } diff --git a/types/ember__polyfills/types.d.ts b/types/ember__polyfills/types.d.ts new file mode 100644 index 0000000000..d1c8cf2306 --- /dev/null +++ b/types/ember__polyfills/types.d.ts @@ -0,0 +1,4 @@ +export type Mix = B & Pick>; +export type Mix3 = Mix, C>; +export type Mix4 = Mix3, C, D>; +export default Mix; diff --git a/types/ember__string/index.d.ts b/types/ember__string/index.d.ts index 1586b4dcc4..d000cfa443 100644 --- a/types/ember__string/index.d.ts +++ b/types/ember__string/index.d.ts @@ -4,15 +4,15 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import Ember from 'ember'; +import { SafeString } from 'handlebars'; -export const camelize: typeof Ember.String.camelize; -export const capitalize: typeof Ember.String.capitalize; -export const classify: typeof Ember.String.classify; -export const dasherize: typeof Ember.String.dasherize; -export const decamelize: typeof Ember.String.decamelize; -export const htmlSafe: typeof Ember.String.htmlSafe; -export const isHTMLSafe: typeof Ember.String.isHTMLSafe; -export const loc: typeof Ember.String.loc; -export const underscore: typeof Ember.String.underscore; -export const w: typeof Ember.String.w; +export function camelize(str: string): string; +export function capitalize(str: string): string; +export function classify(str: string): string; +export function dasherize(str: string): string; +export function decamelize(str: string): string; +export function htmlSafe(str: string): Handlebars.SafeString; +export function isHTMLSafe(str: string): boolean; +export function loc(template: string, args?: string[]): string; +export function underscore(str: string): string; +export function w(str: string): string[]; diff --git a/types/ember__utils/ember__utils-tests.ts b/types/ember__utils/ember__utils-tests.ts index 8b270f1bec..4e05bb1e43 100644 --- a/types/ember__utils/ember__utils-tests.ts +++ b/types/ember__utils/ember__utils-tests.ts @@ -17,8 +17,7 @@ import EmberObject from '@ember/object'; return; } const anotherString = maybeUndefined + 'another string'; - // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/256 - // isNone(); // $ExpectType boolean + isNone(); // $ExpectType boolean isNone(null); // $ExpectType boolean isNone(undefined); // $ExpectType boolean isNone(''); // $ExpectType boolean @@ -30,10 +29,9 @@ import EmberObject from '@ember/object'; /** tryInvoke */ let d = new Date('03/15/2013'); - // TODO fix enhance in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/257 - // tryInvoke(d, 'getTime'); // $ExpectType number - // tryInvoke(d, 'setFullYear', [2014]); // $ExpectType number - // tryInvoke(d, 'noSuchMethod', [2014]); // $ExpectType undefined + tryInvoke(d, 'getTime'); // $ExpectType number + tryInvoke(d, 'setFullYear', [2014]); // $ExpectType number + tryInvoke(d, 'noSuchMethod', [2014]); // $ExpectType undefined tryInvoke(d, 'getTime'); tryInvoke(d, 'setFullYear', [2014]); tryInvoke(d, 'noSuchMethod', [2014]); @@ -41,8 +39,7 @@ import EmberObject from '@ember/object'; (function() { /** isPresent */ - // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/258 - // isPresent(); // $ExpectType boolean + isPresent(); // $ExpectType boolean isPresent(null); // $ExpectType boolean isPresent(undefined); // $ExpectType boolean isPresent(''); // $ExpectType boolean @@ -63,29 +60,27 @@ import EmberObject from '@ember/object'; (function() { /** typeOf */ - // TODO: more specific return type in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/259 - // typeOf(null); // $ExpectType 'null' - // typeOf(undefined); // $ExpectType 'undefined' - // typeOf('michael'); // $ExpectType 'string' - // // tslint:disable-next-line:no-construct - // typeOf(new String('michael')); // $ExpectType 'string' - // typeOf(101); // $ExpectType 'number' - // // tslint:disable-next-line:no-construct - // typeOf(new Number(101)); // $ExpectType 'number' - // typeOf(true); // $ExpectType 'boolean' - // // tslint:disable-next-line:no-construct - // typeOf(new Boolean(true)); // $ExpectType 'boolean' - // typeOf(() => 4); // $ExpectType 'function' - // typeOf([1, 2, 90]); // $ExpectType 'array' - // typeOf(/abc/); // $ExpectType 'regexp' - // typeOf(new Date()); // $ExpectType 'date' - // typeOf(FileList); // $ExpectType 'filelist' - // // typeOf(EmberObject.extend()); // $ExpectType 'class' - // // typeOf(EmberObject.create()); // $ExpectType 'instance' - // typeOf(new Error('teamocil')); // $ExpectType 'error' + typeOf(null); // $ExpectType "null" + typeOf(undefined); // $ExpectType "undefined" + typeOf('michael'); // $ExpectType "string" + // tslint:disable-next-line:no-construct + typeOf(new String('michael')); // $ExpectType "string" + typeOf(101); // $ExpectType "number" + // tslint:disable-next-line:no-construct + typeOf(new Number(101)); // $ExpectType "number" + typeOf(true); // $ExpectType "boolean" + // tslint:disable-next-line:no-construct + typeOf(new Boolean(true)); // $ExpectType "boolean" + typeOf(() => 4); // $ExpectType "function" + typeOf([1, 2, 90]); // $ExpectType "array" + typeOf(/abc/); // $ExpectType "regexp" + typeOf(new Date()); // $ExpectType "date" + typeOf(new FileList()); // $ExpectType "filelist" + typeOf(EmberObject.extend()); // $ExpectType "class" + typeOf(EmberObject.create()); // $ExpectType "instance" + typeOf(new Error('teamocil')); // $ExpectType "error" - // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/260 - // typeOf(); + typeOf(); typeOf(null); typeOf(undefined); typeOf('michael'); @@ -130,8 +125,7 @@ import EmberObject from '@ember/object'; (function() { /** isBlank */ - // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/254 - // isBlank(); // $ExpectType boolean + isBlank(); // $ExpectType boolean isBlank(null); // $ExpectType boolean isBlank(undefined); // $ExpectType boolean isBlank(''); // $ExpectType boolean @@ -147,8 +141,7 @@ import EmberObject from '@ember/object'; (function() { /** isEmpty */ - // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/255 - // isEmpty(); // $ExpectType boolean + isEmpty(); // $ExpectType boolean isEmpty(null); // $ExpectType boolean isEmpty(undefined); // $ExpectType boolean isEmpty(''); // $ExpectType boolean diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 6749f6b47c..9ca9cee5ce 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -2048,6 +2048,11 @@ interface IObjectOptions { */ borderColor?: string; + /** + * Array specifying dash pattern of an object's border (hasBorder must be true) + */ + borderDashArray?: number[]; + /** * Color of controlling corners of an object (when it's active) */ @@ -3114,6 +3119,10 @@ interface ITextOptions extends IObjectOptions { * Line height */ lineHeight?: number; + /** + * Character spacing + */ + charSpacing?: number; /** * When defined, an object is rendered via stroke and this property specifies its color. * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 @@ -3254,6 +3263,15 @@ export class Text extends Object { * @param lineHeight Line height */ setLineHeight(lineHeight: number): Text; + /** + * Retrieves object's charSpacing + */ + getCharSpacing(): number; + /** + * Sets object's charSpacing + * @param charSpacing Character spacing + */ + setCharSpacing(charSpacing: number): Text; /** * Retrieves object's textAlign */ diff --git a/types/find-process/find-process-tests.ts b/types/find-process/find-process-tests.ts new file mode 100644 index 0000000000..0f43ada399 --- /dev/null +++ b/types/find-process/find-process-tests.ts @@ -0,0 +1,16 @@ +/// + +import find = require('find-process'); + +find('pid', 12345).then((processList) => { + processList.forEach((ps) => { + console.log('Full command with args: ' + ps.cmd); + console.log('User group ID (for *nix): ' + ps.gid); + console.log('command/process name: ' + ps.name); + console.log('Process ID: ' + ps.pid); + console.log('Parent process ID: ' + ps.ppid); + console.log('User ID (for *nix): ' + ps.uid); + }); +}, (err) => { + console.log(err.stack || err); +}); diff --git a/types/find-process/index.d.ts b/types/find-process/index.d.ts new file mode 100644 index 0000000000..078a36c0aa --- /dev/null +++ b/types/find-process/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for find-process 1.1 +// Project: https://github.com/yibn2008/find-process +// Definitions by: Buaban Buataitom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +declare function find(by: string, value: string | number): Promise>; +declare namespace find {} + +export = find; diff --git a/types/find-process/tsconfig.json b/types/find-process/tsconfig.json new file mode 100644 index 0000000000..4b17c53c33 --- /dev/null +++ b/types/find-process/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "find-process-tests.ts"] +} diff --git a/types/find-process/tslint.json b/types/find-process/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/find-process/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fluent-ffmpeg/index.d.ts b/types/fluent-ffmpeg/index.d.ts index 1e9eaf5eb4..317a772d59 100644 --- a/types/fluent-ffmpeg/index.d.ts +++ b/types/fluent-ffmpeg/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for node-fluent-ffmpeg 2.1 // Project: https://github.com/fluent-ffmpeg/node-fluent-ffmpeg -// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk , DingWeizhe +// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk +// DingWeizhe +// Mounir Abid // Definitions: https://github.com/DefinitelyType/DefinitelyTyped /// @@ -11,7 +13,7 @@ import * as stream from "stream"; declare namespace Ffmpeg { interface FfmpegCommandLogger { error(...data: any[]): void; - warning(...data: any[]): void; + warn(...data: any[]): void; info(...data: any[]): void; debug(...data: any[]): void; } diff --git a/types/google-map-react/google-map-react-tests.tsx b/types/google-map-react/google-map-react-tests.tsx index 552e75d362..09bd8588be 100644 --- a/types/google-map-react/google-map-react-tests.tsx +++ b/types/google-map-react/google-map-react-tests.tsx @@ -13,6 +13,17 @@ const options: MapOptions = { featureType: "administrative", elementType: "all", stylers: [ {saturation: "-100"} ] + }, + { + featureType: "administrative.neighborhood", + stylers: [ {visibility: "off" } ] + }, + { + elementType: "labels.text.stroke", + stylers: [ {color: "#242f3e"} ] + }, + { + stylers: [ {color: "#fcfffd"} ] } ], }; diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 6f4cf1fe7f..4c566df796 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -9,8 +9,8 @@ import * as React from 'react'; export type BootstrapURLKeys = ({ key: string; } | { client: string; v: string; }) & { language?: string }; export interface MapTypeStyle { - elementType: string; - featureType: string; + elementType?: string; + featureType?: string; stylers: any[]; } diff --git a/types/jwt-then/index.d.ts b/types/jwt-then/index.d.ts new file mode 100644 index 0000000000..9a957ff4d2 --- /dev/null +++ b/types/jwt-then/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for jwt-then 1.0 +// Project: https://github.com/fl0w/jwt-then#readme +// Definitions by: Definitions by: Max Uetrecht +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export type Secret = string | Buffer | { key: string; passphrase: string }; + +export interface SignOptions { + /** + * Signature algorithm. Could be one of these values : + * - HS256: HMAC using SHA-256 hash algorithm (default) + * - HS384: HMAC using SHA-384 hash algorithm + * - HS512: HMAC using SHA-512 hash algorithm + * - RS256: RSASSA using SHA-256 hash algorithm + * - RS384: RSASSA using SHA-384 hash algorithm + * - RS512: RSASSA using SHA-512 hash algorithm + * - ES256: ECDSA using P-256 curve and SHA-256 hash algorithm + * - ES384: ECDSA using P-384 curve and SHA-384 hash algorithm + * - ES512: ECDSA using P-521 curve and SHA-512 hash algorithm + * - none: No digital signature or MAC value included + */ + algorithm?: string; + keyid?: string; + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + expiresIn?: string | number; + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + notBefore?: string | number; + audience?: string | string[]; + subject?: string; + issuer?: string; + jwtid?: string; + noTimestamp?: boolean; + header?: object; + encoding?: string; +} + +/** + * Sign the given payload into a JSON Web Token string + * @param payload - Payload to sign, could be an literal, buffer or string + * @param secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * @param [options] - Options for the signature + * @returns A proiose containing the JSON Web Token string + */ +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options?: SignOptions, +): Promise; + +/** + * Verify given token using a secret or a public key to get a decoded token + * @param token - JWT string to verify + * @param secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * @param [options] - Options for the verification + * @returns A promise containing either an error or the decoded JSON Web Token string + */ +export function verify( + token: string, + secretOrPublicKey: string | Buffer, +): Promise; diff --git a/types/jwt-then/jwt-then-tests.ts b/types/jwt-then/jwt-then-tests.ts new file mode 100644 index 0000000000..d9ad3812ae --- /dev/null +++ b/types/jwt-then/jwt-then-tests.ts @@ -0,0 +1,11 @@ +import jwt = require("jwt-then"); +import fs = require("fs"); + +const testObject = { foo: "bar" }; + +(async () => { + const token = await jwt.sign(testObject, "foobar"); + const verified = await jwt.verify(token, "foobar"); + + console.log(token, verified); +})(); diff --git a/types/jwt-then/tsconfig.json b/types/jwt-then/tsconfig.json new file mode 100644 index 0000000000..aa5eb794cf --- /dev/null +++ b/types/jwt-then/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", + "jwt-then-tests.ts" + ] +} diff --git a/types/jwt-then/tslint.json b/types/jwt-then/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jwt-then/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lovefield/index.d.ts b/types/lovefield/index.d.ts index de02f3c914..bca0c708f1 100644 --- a/types/lovefield/index.d.ts +++ b/types/lovefield/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for Lovefield 2.1 // Project: http://google.github.io/lovefield/ // Definitions by: freshp86 +// zackzeno // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace lf { enum Order { ASC, DESC } @@ -59,10 +61,10 @@ declare namespace lf { } interface Transaction { - attach(query: query.Builder): Promise; + attach(query: query.Builder): Promise; begin(scope: schema.Table[]): Promise; commit(): Promise; - exec(queries: query.Builder[]): Promise; + exec(queries: query.Builder[]): Promise; rollback(): Promise; stats(): TransactionStats; } @@ -73,9 +75,9 @@ declare namespace lf { close(): void; createTransaction(type?: TransactionType): Transaction; delete(): query.Delete; - export(): Promise; + export(): Promise; getSchema(): schema.Database; - import(data: Object): Promise; + import(data: object): Promise; insertOrReplace(): query.Insert; insert(): query.Insert; observe(query: query.Select, callback: Function): void; @@ -87,7 +89,7 @@ declare namespace lf { namespace query { interface Builder { bind(...values: any[]): Builder; - exec(): Promise; + exec(): Promise; explain(): string; toSql(): string; } @@ -131,9 +133,9 @@ declare namespace lf { renameTableColumn( tableName: string, oldColumnName: string, newColumnName: string): Promise; - createRow(payload: Object): Row; + createRow(payload: object): Row; getVersion(): number; - dump(): Object[]; + dump(): object[]; } } // module raw @@ -166,7 +168,7 @@ declare namespace lf { interface ITable { as(name: string): Table; - createRow(value: Object): Row; + createRow(value: object): Row; getName(): string; } diff --git a/types/lovefield/lovefield-tests.ts b/types/lovefield/lovefield-tests.ts index fade4e6755..0c7203fbfc 100644 --- a/types/lovefield/lovefield-tests.ts +++ b/types/lovefield/lovefield-tests.ts @@ -1,4 +1,10 @@ import lf = require("lovefield"); +export interface IRow { + id: number; + description: string; + deadline: Date; + done: boolean; +} function main(): void { const schemaBuilder: lf.schema.Builder = lf.schema.create('todo', 1); @@ -28,11 +34,11 @@ function main(): void { }); return db.insertOrReplace().into(itemSchema).values([row]).exec(); }).then(() => { - const column = itemSchema['done']; - return todoDb.select().from(itemSchema).where(column.eq(false)).exec(); + const column = itemSchema.done; + return todoDb.select().from(itemSchema).where(column.eq(false)).exec() as Promise; }).then((results) => { results.forEach((row) => { - document.body.textContent = `${(row as any).description} before ${(row as any).deadline}`; + document.body.textContent = `${row.description} before ${row.deadline}`; }); return todoDb.delete().from(itemSchema); diff --git a/types/md5/index.d.ts b/types/md5/index.d.ts index 7cfed0ca35..071c5306fc 100644 --- a/types/md5/index.d.ts +++ b/types/md5/index.d.ts @@ -11,7 +11,7 @@ * @param {(string | Buffer)} message - a string or buffer to hash * @returns {string} the resultant MD5 hash of the given message */ -declare function md5(message: string | Buffer): string; +declare function md5(message: string | Buffer | Array): string; declare namespace md5 {} diff --git a/types/md5/md5-tests.ts b/types/md5/md5-tests.ts index 924c9b8d91..9e7cc52ef2 100644 --- a/types/md5/md5-tests.ts +++ b/types/md5/md5-tests.ts @@ -1,4 +1,3 @@ -import fs = require("fs"); import md5 = require("md5"); /** * API @@ -24,8 +23,12 @@ import md5 = require("md5"); * }); * * ************************************************** */ -console.log(md5('message')); // should print 78e731027d8fd50ed642340b7c9a63b3 +const message = 'message'; -fs.readFile('md5.d.ts', function(err: Error, buf: Buffer) { - console.log(md5(buf)); -}); \ No newline at end of file +console.log(md5(message)); // should print 78e731027d8fd50ed642340b7c9a63b3 + +const array = new Array(message.length); +for (let i = 0; i < message.length; ++i) + array[i] = message.charCodeAt(i); +const buffer = new Buffer(array); +console.log(md5(buffer)); // Should be same result as above. diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 70a4247d07..6c0c384284 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -697,7 +697,9 @@ declare module "mongoose" { | "findOne" | "findOneAndRemove" | "findOneAndUpdate" - | "update", + | "update" + | "updateOne" + | "updateMany", fn: HookSyncCallback, errorCb?: HookErrorCallback ): this; @@ -730,7 +732,9 @@ declare module "mongoose" { | "findOne" | "findOneAndRemove" | "findOneAndUpdate" - | "update", + | "update" + | "updateOne" + | "updateMany", parallel: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback @@ -2701,6 +2705,7 @@ declare module "mongoose" { * Triggers the save() hook. */ create(docs: any[], callback?: (err: any, res: T[]) => void): Promise; + create(docs: any[], options?: SaveOptions, callback?: (err: any, res: T[]) => void): Promise; create(...docs: any[]): Promise; create(...docsWithCallback: any[]): Promise; @@ -2988,6 +2993,7 @@ declare module "mongoose" { interface SaveOptions { safe?: boolean | WriteConcern; validateBeforeSave?: boolean; + session?: ClientSession; } interface WriteConcern { @@ -3030,7 +3036,7 @@ declare module "mongoose" { interface ModelOptions { session?: ClientSession | null; } - + interface ModelFindByIdAndUpdateOptions extends ModelOptions { /** true to return the modified document rather than the original. defaults to false */ new?: boolean; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index dea144c279..d8f55f6f97 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -1960,4 +1960,30 @@ db.createCollection('users'). ]).session(session).exec()). then((res: any) => { session.commitTransaction(); - }); \ No newline at end of file + }); + +/** https://mongoosejs.com/docs/transactions.html */ + +const Customer = db.model('Customer', new mongoose.Schema({ name: String })); + +db.createCollection('customers'). + then(() => db.startSession()). + then(_session => { + session = _session; + // Start a transaction + session.startTransaction(); + // This `create()` is part of the transaction because of the `session` + // option. + return Customer.create([{ name: 'Test' }], { session: session }); + }). + // Transactions execute in isolation, so unless you pass a `session` + // to `findOne()` you won't see the document until the transaction + // is committed. + then((customer: mongoose.Document[]) => Customer.findOne({ name: 'Test' }).exec()). + // This `findOne()` will return the doc, because passing the `session` + // means this `findOne()` will run as part of the transaction. + then(() => Customer.findOne({ name: 'Test' }).session(session).exec()). + // Once the transaction is committed, the write operation becomes + // visible outside of the transaction. + then(() => session.commitTransaction()). + then(() => Customer.findOne({ name: 'Test' }).exec()) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index ea3a5e8c47..d0ebd2124f 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 10.9.x +// Type definitions for Node.js 10.10.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -795,6 +795,14 @@ declare namespace NodeJS { disconnect(): void; connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + // TODO: This Set is readonly + allowedNodeEnvironmentFlags: Set; + /** * EventEmitter * 1. beforeExit @@ -1088,6 +1096,7 @@ declare module "http" { 'pragma'?: string; 'proxy-authenticate'?: string; 'public-key-pins'?: string; + 'referer'?: string; 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; @@ -1737,8 +1746,8 @@ declare module "os" { export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export function homedir(): string; export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; - export var constants: { - UV_UDP_REUSEADDR: number, + export const constants: { + UV_UDP_REUSEADDR: number; signals: { SIGHUP: number; SIGINT: number; @@ -1774,7 +1783,7 @@ declare module "os" { SIGPWR: number; SIGSYS: number; SIGUNUSED: number; - }, + }; errno: { E2BIG: number; EACCES: number; @@ -1855,13 +1864,36 @@ declare module "os" { ETXTBSY: number; EWOULDBLOCK: number; EXDEV: number; - }, + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } }; export function arch(): string; export function platform(): NodeJS.Platform; export function tmpdir(): string; export const EOL: string; export function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + export function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + export function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + export function setPriority(pid: number, priority: number): void; } declare module "https" { @@ -2097,22 +2129,53 @@ declare module "readline" { declare module "vm" { export interface Context { } - export interface ScriptOptions { + export interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ columnOffset?: number; + } + export interface ScriptOptions extends BaseOptions { displayErrors?: boolean; timeout?: number; cachedData?: Buffer; produceCachedData?: boolean; } - export interface RunningScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; + export interface RunningScriptOptions extends BaseOptions { displayErrors?: boolean; timeout?: number; } + export interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } export class Script { constructor(code: string, options?: ScriptOptions); runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; @@ -2126,6 +2189,7 @@ declare module "vm" { export function runInDebugContext(code: string): any; export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; export function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + export function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; } declare module "child_process" { @@ -2360,7 +2424,7 @@ declare module "child_process" { export interface SpawnSyncOptions { argv0?: string; // Not specified in the docs cwd?: string; - input?: string | Buffer | Uint8Array; + input?: string | Buffer | NodeJS.TypedArray | DataView; stdio?: StdioOptions; env?: NodeJS.ProcessEnv; uid?: number; @@ -2423,7 +2487,7 @@ declare module "child_process" { export interface ExecFileSyncOptions { cwd?: string; - input?: string | Buffer | Uint8Array; + input?: string | Buffer | NodeJS.TypedArray | DataView; stdio?: StdioOptions; env?: NodeJS.ProcessEnv; uid?: number; @@ -3189,6 +3253,7 @@ declare module "fs" { */ export type PathLike = string | Buffer | URL; + export type BinaryData = Buffer | DataView | NodeJS.TypedArray; export class Stats { isFile(): boolean; isDirectory(): boolean; @@ -3217,6 +3282,17 @@ declare module "fs" { birthtime: Date; } + export class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + export interface FSWatcher extends events.EventEmitter { close(): void; @@ -3964,21 +4040,21 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdir(path: PathLike, options: { encoding: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdir(path: PathLike, options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; + export function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; /** * Asynchronous readdir(3) - read a directory. @@ -3986,6 +4062,13 @@ declare module "fs" { */ export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace readdir { /** @@ -3993,21 +4076,28 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): Promise; + export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer" }): Promise; + export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + export function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + export function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise; } /** @@ -4015,21 +4105,28 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): string[]; + export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer[]; + export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[]; + export function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; /** * Asynchronous close(2) - close a file descriptor. @@ -4164,7 +4261,7 @@ declare module "fs" { * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ - export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. @@ -4172,20 +4269,20 @@ declare module "fs" { * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. */ - export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. */ - export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. */ - export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. @@ -4220,7 +4317,7 @@ declare module "fs" { * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ - export function __promisify__(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + export function __promisify__(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. @@ -4239,7 +4336,7 @@ declare module "fs" { * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ - export function writeSync(fd: number, buffer: Buffer | Uint8Array, offset?: number | null, length?: number | null, position?: number | null): number; + export function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; /** * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. @@ -4258,7 +4355,7 @@ declare module "fs" { * @param length The number of bytes to read. * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. */ - export function read(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void; + export function read(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace read { @@ -4269,7 +4366,7 @@ declare module "fs" { * @param length The number of bytes to read. * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. */ - export function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + export function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; } /** @@ -4280,7 +4377,7 @@ declare module "fs" { * @param length The number of bytes to read. * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. */ - export function readSync(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, position: number | null): number; + export function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; /** * Asynchronously reads the entire contents of a file. @@ -4379,6 +4476,8 @@ declare module "fs" { */ export function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + export type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + /** * Asynchronously writes data to a file, replacing the file if it already exists. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -4391,7 +4490,7 @@ declare module "fs" { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'w'` is used. */ - export function writeFile(path: PathLike | number, data: any, options: { encoding?: string | null; mode?: number | string; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronously writes data to a file, replacing the file if it already exists. @@ -4416,7 +4515,7 @@ declare module "fs" { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'w'` is used. */ - export function __promisify__(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): Promise; + export function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; } /** @@ -4431,7 +4530,7 @@ declare module "fs" { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'w'` is used. */ - export function writeFileSync(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void; + export function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; /** * Asynchronously append data to a file, creating the file if it does not exist. @@ -4445,7 +4544,7 @@ declare module "fs" { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'a'` is used. */ - export function appendFile(file: PathLike | number, data: any, options: { encoding?: string | null, mode?: string | number, flag?: string } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronously append data to a file, creating the file if it does not exist. @@ -4470,7 +4569,7 @@ declare module "fs" { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'a'` is used. */ - export function __promisify__(file: PathLike | number, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string } | string | null): Promise; + export function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; } /** @@ -4485,7 +4584,7 @@ declare module "fs" { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'a'` is used. */ - export function appendFileSync(file: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void; + export function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; /** * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 542e8111a2..b9a02f8dbd 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -186,6 +186,7 @@ namespace fs_tests { fs.writeFileSync("testfile", "content", "utf8"); fs.writeFileSync("testfile", "content", { encoding: "utf8" }); + fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" }); } { @@ -229,6 +230,14 @@ namespace fs_tests { fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } + { + fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException, bytesRead: number, buffer: DataView) => {}); + } + + { + fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0); + } + { var errno: number; fs.readFile('testfile', (err, data) => { @@ -247,6 +256,8 @@ namespace fs_tests { listS = fs.readdirSync('path', 'utf8'); listS = fs.readdirSync('path', null); listS = fs.readdirSync('path', undefined); + const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true }); + const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' }); let listB: Buffer[]; listB = fs.readdirSync('path', { encoding: 'buffer' }); @@ -255,8 +266,9 @@ namespace fs_tests { let enc = 'buffer'; fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] - } + fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException, files: fs.Dirent[]) => {}); + } { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); @@ -864,7 +876,7 @@ namespace util_tests { var arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); var arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); var arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); - var cbOptionalError: () => Promise = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); + var cbOptionalError: () => Promise = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return assert(typeof util.promisify.custom === 'symbol'); // util.deprecate const foo = () => {}; @@ -2421,6 +2433,8 @@ namespace child_process_tests { childProcess.spawnSync("echo test"); childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); + childProcess.spawnSync("echo test", {input: new Uint8Array([])}); + childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); } { @@ -2433,6 +2447,11 @@ namespace child_process_tests { childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); } + { + childProcess.execFileSync("echo test", {input: new Uint8Array([])}); + childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); + } + async function testPromisify() { const execFile = util.promisify(childProcess.execFile); let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); @@ -2868,6 +2887,16 @@ namespace os_tests { result = os.constants.errno.EWOULDBLOCK; result = os.constants.errno.EXDEV; } + + { + const prio = os.getPriority(); + os.setPriority(prio + 1); + + const prio2 = os.getPriority(1); + os.setPriority(2, prio + 1); + + os.setPriority(os.constants.priority.PRIORITY_LOW); + } } //////////////////////////////////////////////////// @@ -2921,6 +2950,17 @@ namespace vm_tests { { vm.runInThisContext('console.log("hello world"', './my-file.js'); } + + { + const fn: Function = vm.compileFunction('console.log("test")', [], { + parsingContext: vm.createContext(), + contextExtensions: [{ + a: 1, + }], + produceCachedData: false, + cachedData: Buffer.from('nope'), + }); + } } ///////////////////////////////////////////////////// @@ -3036,6 +3076,9 @@ namespace process_tests { process.setUncaughtExceptionCaptureCallback(null); const b: boolean = process.hasUncaughtExceptionCaptureCallback(); } + { + process.allowedNodeEnvironmentFlags.has('asdf'); + } } /////////////////////////////////////////////////////////// diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index de820c771f..4e52dd66a4 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -50,7 +50,8 @@ export const UNIT_SEP: string; export const WORKERS_SUPPORTED: boolean; // The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously. -export const SCRIPT_PATH: string; +// Assign it a value to override auto-detected path. +export let SCRIPT_PATH: string; // When passed to Papa Parse a Readable stream is returned. export const NODE_STREAM_INPUT = 1; diff --git a/types/passport-oauth2/index.d.ts b/types/passport-oauth2/index.d.ts index 323d39853d..7d7f3de21d 100644 --- a/types/passport-oauth2/index.d.ts +++ b/types/passport-oauth2/index.d.ts @@ -45,7 +45,7 @@ declare namespace OAuth2Strategy { tokenURL: string; clientID: string; clientSecret: string; - callbackURL: string; + callbackURL?: string; } interface StrategyOptions extends _StrategyOptionsBase { passReqToCallback?: false; diff --git a/types/passport-oauth2/passport-oauth2-tests.ts b/types/passport-oauth2/passport-oauth2-tests.ts index 133bf5ec4e..6a5d09ef27 100644 --- a/types/passport-oauth2/passport-oauth2-tests.ts +++ b/types/passport-oauth2/passport-oauth2-tests.ts @@ -33,7 +33,6 @@ function verifyFunction4(_req: Request, _accessToken: string, _refreshToken: str const strategyOptions2: StrategyOptionsWithRequest = { authorizationURL: 'http://www.example.com/auth', - callbackURL: 'http://www.example.com/callback', clientID: 'dummy', clientSecret: 'secret', tokenURL: 'http://www.example.com/token', diff --git a/types/postmark/index.d.ts b/types/postmark/index.d.ts index 24810299a7..b2b7ac0cfc 100644 --- a/types/postmark/index.d.ts +++ b/types/postmark/index.d.ts @@ -1,12 +1,10 @@ // Type definitions for postmark 1.4 // Project: http://wildbit.github.io/postmark.js -// Definitions by: Ben Bayard +// Definitions by: Ben Bayard +// Jinesh Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -export = postmark; - -declare const postmark: Postmark.Postmark; declare namespace Postmark { const defaults: Options; @@ -87,7 +85,9 @@ declare namespace Postmark { InlineCssForHtmlTestRender?: boolean; } - type PostmarkCallback = ((e: PostmarkError, ret: T) => undefined) | undefined; + type PostmarkCallback = + | ((e: PostmarkError, ret: T) => undefined) + | undefined; interface SimpleOptions { ssl: boolean; @@ -109,36 +109,64 @@ declare namespace Postmark { constructor(serverKey: string, options?: Partial); send(message: PostmarkMessage): Promise; - send(message: PostmarkMessage, callback: PostmarkCallback): undefined; + send( + message: PostmarkMessage, + callback: PostmarkCallback + ): undefined; - sendEmailWithTemplate(message: PostmarkMessageWithTemplate): Promise; - sendEmailWithTemplate(message: PostmarkMessageWithTemplate, callback: PostmarkCallback): undefined; + sendEmailWithTemplate( + message: PostmarkMessageWithTemplate + ): Promise; + sendEmailWithTemplate( + message: PostmarkMessageWithTemplate, + callback: PostmarkCallback + ): undefined; batch(message: PostmarkMessage[]): Promise; - batch(message: PostmarkMessage[], callback: PostmarkCallback): undefined; + batch( + message: PostmarkMessage[], + callback: PostmarkCallback + ): undefined; sendEmail(message: PostmarkMessage): Promise; - sendEmail(message: PostmarkMessage, callback: PostmarkCallback): undefined; + sendEmail( + message: PostmarkMessage, + callback: PostmarkCallback + ): undefined; sendEmailBatch(message: PostmarkMessage[]): Promise; - sendEmailBatch(message: PostmarkMessage[], callback: PostmarkCallback): undefined; + sendEmailBatch( + message: PostmarkMessage[], + callback: PostmarkCallback + ): undefined; // stats getDeliveryStatistics(): Promise; - getDeliveryStatistics(callback: PostmarkCallback): undefined; + getDeliveryStatistics( + callback: PostmarkCallback + ): undefined; // bounces getBounces(filter: BounceFilter): Promise; - getBounces(filter: BounceFilter, callback?: PostmarkCallback): undefined; + getBounces( + filter: BounceFilter, + callback?: PostmarkCallback + ): undefined; getBounce(id: number): Promise; getBounce(id: number, callback?: PostmarkCallback): undefined; getBounceDump(id: number): Promise; - getBounceDump(id: number, callback?: PostmarkCallback): undefined; + getBounceDump( + id: number, + callback?: PostmarkCallback + ): undefined; activateBounce(id: number): Promise; - activateBounce(id: number, callback?: PostmarkCallback): undefined; + activateBounce( + id: number, + callback?: PostmarkCallback + ): undefined; getBounceTags(): Promise; getBounceTags(callback?: PostmarkCallback): undefined; @@ -148,54 +176,112 @@ declare namespace Postmark { getServer(callback?: PostmarkCallback): undefined; editServer(server: Partial): Promise; - editServer(server: Partial, callback?: PostmarkCallback): undefined; + editServer( + server: Partial, + callback?: PostmarkCallback + ): undefined; // message info - getOutboundMessages(filter: OutboundMessageFilter): Promise; - getOutboundMessages(filter: OutboundMessageFilter, callback?: PostmarkCallback): undefined; + getOutboundMessages( + filter: OutboundMessageFilter + ): Promise; + getOutboundMessages( + filter: OutboundMessageFilter, + callback?: PostmarkCallback + ): undefined; getOutboundMessageDetails(id: number): Promise; - getOutboundMessageDetails(id: number, callback?: PostmarkCallback): undefined; + getOutboundMessageDetails( + id: number, + callback?: PostmarkCallback + ): undefined; getMessageOpens(filter: OpenMessageFilter): Promise; - getMessageOpens(filter: OpenMessageFilter, callback?: PostmarkCallback): undefined; + getMessageOpens( + filter: OpenMessageFilter, + callback?: PostmarkCallback + ): undefined; - getMessageOpensForSingleMessage(id: number, filter: Filter): Promise; - getMessageOpensForSingleMessage(id: number, filter: Filter, callback?: PostmarkCallback): undefined; + getMessageOpensForSingleMessage( + id: number, + filter: Filter + ): Promise; + getMessageOpensForSingleMessage( + id: number, + filter: Filter, + callback?: PostmarkCallback + ): undefined; - getInboundMessages(filter: InboundMessageFilter): Promise; - getInboundMessages(filter: InboundMessageFilter, callback?: PostmarkCallback): undefined; + getInboundMessages( + filter: InboundMessageFilter + ): Promise; + getInboundMessages( + filter: InboundMessageFilter, + callback?: PostmarkCallback + ): undefined; getInboundMessageDetails(id: number): Promise; - getInboundMessageDetails(id: number, callback?: PostmarkCallback): undefined; + getInboundMessageDetails( + id: number, + callback?: PostmarkCallback + ): undefined; bypassBlockedInboundMessage(id: number): Promise; - bypassBlockedInboundMessage(id: number, callback?: PostmarkCallback): undefined; + bypassBlockedInboundMessage( + id: number, + callback?: PostmarkCallback + ): undefined; getOuboundOverview(filter: BaseFilter): Promise; - getOuboundOverview(filter: BaseFilter, callback?: PostmarkCallback): undefined; + getOuboundOverview( + filter: BaseFilter, + callback?: PostmarkCallback + ): undefined; retryInboundHookForMessage(id: number): Promise; - retryInboundHookForMessage(id: number, callback?: PostmarkCallback): undefined; + retryInboundHookForMessage( + id: number, + callback?: PostmarkCallback + ): undefined; // templates getTemplate(id: number): Promise