diff --git a/notNeededPackages.json b/notNeededPackages.json index e0e880c3e6..e1a2f2e6cd 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1278,6 +1278,12 @@ "sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension", "asOfVersion": "2.13.2" }, + { + "libraryName": "redux-little-router", + "typingsPackageName": "redux-little-router", + "sourceRepoURL": "https://github.com/FormidableLabs/redux-little-router", + "asOfVersion": "15.1.0" + }, { "libraryName": "redux-persist", "typingsPackageName": "redux-persist", 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/bloom-filter/bloom-filter-tests.ts b/types/bloom-filter/bloom-filter-tests.ts new file mode 100644 index 0000000000..0b836a0f84 --- /dev/null +++ b/types/bloom-filter/bloom-filter-tests.ts @@ -0,0 +1,28 @@ +import BloomFilter = require('bloom-filter'); + +const numElements = 3; +const falsePositiveRate = 0.01; +const filter = BloomFilter.create(numElements, falsePositiveRate); + +// elements +const a = Buffer.from('99108ad8ed9bb6274d3980bab5a85c048f0950c8', 'hex'); +const c = Buffer.from('b5a2c786d9ef4658287ced5914b37a1b4aa32eee', 'hex'); + +// insert elements +// $ExpectType void +filter.insert(a); + +// $ExpectType boolean +!filter.contains(c); + +// reinstantiate from an object +const serialized = filter.toObject(); +const woahFilter = new BloomFilter(serialized); + +// initialize directly +const newFilter = new BloomFilter({ + vData: Buffer.from('123', 'hex'), // the data of the filter + nHashFuncs: 3, // the number of hash functions to use + nTweak: 2147483649, // the seed used for the hash fuctions + nFlags: 0 // flags used to update the filter when matched +}); diff --git a/types/bloom-filter/index.d.ts b/types/bloom-filter/index.d.ts new file mode 100644 index 0000000000..22841f066b --- /dev/null +++ b/types/bloom-filter/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for bloom-filter 0.2 +// Project: https://github.com/bitpay/bloom-filter +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare class Filter { + constructor(options: Filter.FilterOptions); + static create(elements: number, falsePositiveRate: number, nTweak?: number, nFlags?: number): Filter; + toObject(): Filter.FilterOptions; + hash(nHashNum: number, vDataToHash: Buffer): number; + insert(data: Buffer): void; + contains(data: Buffer): boolean; + clear(): void; + inspect(): string; + BLOOM_UPDATE_NONE: number; + BLOOM_UPDATE_ALL: number; + BLOOM_UPDATE_P2PUBKEY_ONLY: number; + MAX_BLOOM_FILTER_SIZE: number; + MAX_HASH_FUNCS: number; + MIN_HASH_FUNCS: number; + LN2SQUARED: number; + LN2: number; +} + +declare namespace Filter { + interface FilterOptions { + vData: Buffer; + nHashFuncs: number; + nTweak?: number; + nFlags?: number; + } + + function MurmurHash3(seed: number, data: Buffer): number; +} + +export = Filter; diff --git a/types/bloom-filter/tsconfig.json b/types/bloom-filter/tsconfig.json new file mode 100644 index 0000000000..788542822b --- /dev/null +++ b/types/bloom-filter/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bloom-filter-tests.ts" + ] +} diff --git a/types/bloom-filter/tslint.json b/types/bloom-filter/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/bloom-filter/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index aa6cd54eb7..49027a2bea 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -391,6 +391,8 @@ declare namespace Chart { easing?: string; onProgress?(chart: any): void; onComplete?(chart: any): void; + animateRotate?: boolean; + animateScale?: boolean; } interface ChartElementsOptions { 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/elliptic/elliptic-tests.ts b/types/elliptic/elliptic-tests.ts new file mode 100644 index 0000000000..d587be5e8d --- /dev/null +++ b/types/elliptic/elliptic-tests.ts @@ -0,0 +1,47 @@ +import elliptic = require('elliptic'); + +const ec = new elliptic.ec('secp256k1'); + +// Generate keys +const key = ec.genKeyPair(); + +// Sign the message's hash (input must be an array, or a hex-string) +const msgHash = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +const signature = key.sign(msgHash); + +// Export DER encoded signature in Array +const derSign = signature.toDER(); + +// Verify signature +console.log(key.verify(msgHash, derSign)); + +// CHECK WITH NO PRIVATE KEY + +const pubPoint = key.getPublic(); +const x = pubPoint.getX(); +const y = pubPoint.getY(); + +// Public Key MUST be either: +// 1) '04' + hex string of x + hex string of y; or +// 2) object with two hex string properties (x and y); or +// 3) object with two buffer properties (x and y) +const pub = pubPoint.encode('hex'); // case 1 +const aPub = { x: x.toString('hex'), y: y.toString('hex') }; // case 2 +const bPub = { x: x.toBuffer(), y: y.toBuffer() }; // case 3 +const cPub = { x: x.toArrayLike(Buffer), y: y.toArrayLike(Buffer) }; // case 3 + +// Import public key +const newKey = ec.keyFromPublic(pub, 'hex'); + +// Signature MUST be either: +// 1) DER-encoded signature as hex-string; or +// 2) DER-encoded signature as buffer; or +// 3) object with two hex-string properties (r and s); or +// 4) object with two buffer properties (r and s) + +// const signature = '3046022100...'; // case 1 +// const signature = new Buffer('...'); // case 2 +// const signature = { r: 'b1fc...', s: '9c42...' }; // case 3 + +// Verify signature +console.log(key.verify(msgHash, signature)); diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts new file mode 100644 index 0000000000..f819d17497 --- /dev/null +++ b/types/elliptic/index.d.ts @@ -0,0 +1,158 @@ +// Type definitions for elliptic 6.4 +// Project: https://github.com/indutny/elliptic +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import BN = require('bn.js'); + +// incomplete typings +export const utils: any; +export const rand: any; +export const eddsa: any; + +export type BNInput = string | BN | number | Buffer | number[]; + +export const version: number; + +export namespace curve { + class BaseCurve { + constructor(type: string, conf: BaseCurve.BaseCurveOptions) + p: BN; + type: string; + red: any; // ? + zero: any; // ? + one: any; // ? + two: any; // ? + n: BN | undefined | null; + g: any; // ? + redN: any; // ? + decodePoint(bytes: any, enc: string): any; // ? + } + + namespace BaseCurve { + class BasePoint { + constructor(curve: any, type: string); + curve: any; + type: string; + precomputed: PrecomputedValues | null; + encode(enc: string, compact: boolean): BN; + encodeCompressed(enc: string): BN; + validate(): boolean; + precompute(power: number): BasePoint; + dblp(k: any): any; // ? + } + + interface BaseCurveOptions { + p: number | string | number[] | Buffer | BN; + prime?: BN | string; + n?: number | BN | Buffer; + g?: any; // ? + gRed?: any; // ? + } + + interface PrecomputedValues { + doubles: any; // ? + naf: any; // ? + beta: any; // ? + } + } +} + +export namespace curves { + class PresetCurve { + constructor(options: PresetCurve.Options) + type: string; + g: any; // ? + n: BN | undefined | null; + hash: any; // ? + } + + namespace PresetCurve { + interface Options { + type: string; + prime: string | null; + p: string; + a: string; + b: string; + n: string; + hash: any; + gRed: boolean; + g: any; // ? + beta?: string; + lambda?: string; + basis?: any; // ? + } + } +} + +export class ec { + constructor(options: string | curves.PresetCurve) + curve: any; + n: BN | undefined | null; + nh: any; + g: any; + hash: any; + + keyPair(options: ec.KeyPairOptions): ec.KeyPair; + keyFromPrivate(priv: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; + genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; + sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; + sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; + verify(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, key: Buffer | ec.KeyPair, enc?: string): boolean; + recoverPubKey(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, j: number, enc?: string): any; + getKeyRecoveryParam(e: Error | undefined, signature: ec.Signature | ec.SignatureOptions, Q: BN, enc?: string): number; +} + +export namespace ec { + interface GenKeyPairOptions { + pers: any; + entropy: any; + persEnc?: string; + entropyEnc?: string; + } + + interface SignOptions { + pers: any; + persEnc?: string; + canonical?: boolean; + k?: BN; + } + + class KeyPair { + static fromPublic(ec: ec, pub: Buffer | KeyPair, enc?: string): KeyPair; + static fromPrivate(ec: ec, priv: Buffer | KeyPair, enc?: string): KeyPair; + constructor(ec: ec, options: KeyPairOptions) + ec: ec; + validate(): { readonly result: boolean, readonly reason: string }; + getPublic(compact: boolean, enc?: string): any; // ? + getPublic(enc?: string): any; // ? + getPrivate(enc?: 'hex'): Buffer | BN | string; + derive(pub: any): any; // ? + sign(msg: BNInput, enc: string, options?: SignOptions): Signature; + sign(msg: BNInput, options?: SignOptions): Signature; + verify(msg: BNInput, signature: Signature | SignatureOptions): boolean; + inspect(): string; + } + + class Signature { + constructor(options: SignatureOptions | Signature, enc?: string) + r: BN; + s: BN; + recoveryParam: number | null; + toDER(enc?: string | null): any; // ? + } + + interface SignatureOptions { + r: number; + s: number; + recoveryParam?: number; + } + + interface KeyPairOptions { + priv?: Buffer; + privEnc?: string; + pub?: Buffer; + pubEnc?: string; + } +} diff --git a/types/elliptic/tsconfig.json b/types/elliptic/tsconfig.json new file mode 100644 index 0000000000..505cd03374 --- /dev/null +++ b/types/elliptic/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", + "elliptic-tests.ts" + ] +} diff --git a/types/elliptic/tslint.json b/types/elliptic/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/elliptic/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/ember-resolver/ember-resolver-tests.ts b/types/ember-resolver/ember-resolver-tests.ts index d22a0d31be..6973daeda0 100644 --- a/types/ember-resolver/ember-resolver-tests.ts +++ b/types/ember-resolver/ember-resolver-tests.ts @@ -1,5 +1,5 @@ -import Application from '@ember/application'; import EmberResolver from 'ember-resolver'; +import { Ember } from 'ember'; const MyResolver = EmberResolver.extend({ pluralizedTypes: { @@ -7,6 +7,6 @@ const MyResolver = EmberResolver.extend({ } }); -const App = Application.extend({ +const App = Ember.Application.extend({ Resolver: MyResolver }); diff --git a/types/ember-resolver/index.d.ts b/types/ember-resolver/index.d.ts index 4fe466ae13..f2ede7fe32 100644 --- a/types/ember-resolver/index.d.ts +++ b/types/ember-resolver/index.d.ts @@ -5,11 +5,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -/// - -import Resolver from '@ember/application/resolver'; +import Ember from 'ember'; /** * An Ember `Resolver` implementation used by ember-cli. */ -export default class EmberResolver extends Resolver {} +export default class EmberResolver extends Ember.Resolver {} diff --git a/types/ember-resolver/v4/ember-resolver-tests.ts b/types/ember-resolver/v4/ember-resolver-tests.ts index d22a0d31be..db834b1985 100644 --- a/types/ember-resolver/v4/ember-resolver-tests.ts +++ b/types/ember-resolver/v4/ember-resolver-tests.ts @@ -1,4 +1,4 @@ -import Application from '@ember/application'; +import Ember from 'ember'; import EmberResolver from 'ember-resolver'; const MyResolver = EmberResolver.extend({ @@ -7,6 +7,6 @@ const MyResolver = EmberResolver.extend({ } }); -const App = Application.extend({ +const App = Ember.Application.extend({ Resolver: MyResolver }); diff --git a/types/ember-resolver/v4/index.d.ts b/types/ember-resolver/v4/index.d.ts index 8047dc1bc2..fd5359cff4 100644 --- a/types/ember-resolver/v4/index.d.ts +++ b/types/ember-resolver/v4/index.d.ts @@ -5,11 +5,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -/// - -import Resolver from '@ember/application/resolver'; +import Ember from 'ember'; /** * An Ember `Resolver` implementation used by ember-cli. */ -export default class EmberResolver extends Resolver {} +export default class EmberResolver extends Ember.Resolver {} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 6d79e1df8b..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[]; @@ -739,7 +740,7 @@ declare module 'ember' { class ContainerDebugAdapter extends Object { resolver: Resolver; canCatalogEntriesByType(type: string): boolean; - catalogEntriesByType(type: string): any[]; + catalogEntriesByType(type: string): string[]; } /** * Additional methods for the Controller. @@ -1004,32 +1005,54 @@ declare module 'ember' { * The container-debug-adapter which is used * to list all models. */ - containerDebugAdapter: any; + containerDebugAdapter: ContainerDebugAdapter; /** * Ember Data > v1.0.0-beta.18 * requires string model names to be passed * around instead of the actual factories. */ - acceptsModelName: any; + acceptsModelName: boolean; /** * Specifies how records can be filtered. * Records returned will need to have a `filterValues` * property with a key for every name in the returned array. */ - getFilters(): any[]; + getFilters(): DataAdapter.Column[]; /** * Fetch the model types and observe them for changes. */ - watchModelTypes(typesAdded: Function, typesUpdated: Function): Function; + watchModelTypes( + typesAdded: (types: DataAdapter.WrappedType[]) => void, + typesUpdated: (types: DataAdapter.WrappedType[]) => void + ): () => void; /** * Fetch the records of a given type and observe them for changes. */ watchRecords( modelName: string, - recordsAdded: Function, - recordsUpdated: Function, - recordsRemoved: Function - ): Function; + recordsAdded: (records: DataAdapter.WrappedRecord[]) => void, + recordsUpdated: (records: DataAdapter.WrappedRecord[]) => void, + recordsRemoved: (idx: number, count: number) => void + ): () => void; + } + namespace DataAdapter { + interface Column { + name: string; + desc: string; + } + interface WrappedRecord { + columnValues: object; + object: object; + } + interface WrappedType { + type: { + name: string; + count: number; + columns: Column[]; + object: typeof Object; + }; + release: () => void; + } } const Debug: { /** @@ -1038,14 +1061,14 @@ declare module 'ember' { * The following example demonstrates its usage by registering a handler that throws an error if the * message contains the word "should", otherwise defers to the default handler. */ - registerDeprecationHandler(handler: Function): any; + registerDeprecationHandler(handler: (message: string, options: { id: string, until: string }, next: () => void) => void): void; /** * Allows for runtime registration of handler functions that override the default warning behavior. * Warnings are invoked by calls made to [Ember.warn](http://emberjs.com/api/classes/Ember.html#method_warn). * The following example demonstrates its usage by registering a handler that does nothing overriding Ember's * default warning behavior. */ - registerWarnHandler(handler: Function): any; + registerWarnHandler(handler: (message: string, options: { id: string }, next: () => void) => void): void; }; /** * The DefaultResolver defines the default lookup rules to resolve @@ -1711,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 @@ -1725,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`. @@ -2399,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; @@ -3017,20 +3037,20 @@ declare module 'ember' { /** * Run a function meant for debugging. */ - function runInDebug(func: () => void): any; + function runInDebug(func: () => any): void; /** * Display a warning with the provided message. */ - function warn(message: string, test: boolean, options: { id: string }): any; - function warn(message: string, options: { id: string }): any; + function warn(message: string, test: boolean, options: { id: string }): void; + function warn(message: string, options: { id: string }): void; /** * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options */ - function warn(message: string, test: boolean, options?: { id?: string }): any; + function warn(message: string, test: boolean, options?: { id?: string }): void; /** * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options */ - function warn(message: string, options?: { id?: string }): any; + function warn(message: string, options?: { id?: string }): void; /** * Global helper method to create a new binding. Just pass the root object * along with a `to` and `from` path to create and connect the binding. @@ -3116,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. */ @@ -3128,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. */ @@ -3211,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. @@ -3225,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. @@ -3267,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 @@ -3309,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 @@ -3529,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' { @@ -3625,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 { } @@ -3768,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 { } @@ -3850,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/data-adapter.ts b/types/ember/test/data-adapter.ts new file mode 100644 index 0000000000..ea77b27e70 --- /dev/null +++ b/types/ember/test/data-adapter.ts @@ -0,0 +1,53 @@ +import Ember from 'ember'; + +const da = Ember.DataAdapter.create(); + +const filters = da.getFilters(); +filters.includes({ name: 'foo', desc: 'bar'}); // $ExpectType boolean +filters.includes({}); // $ExpectError + +filters[0].name; // $ExpectType string +filters[0].desc; // $ExpectType string + +da.watchModelTypes(// $ExpectType () => void + function added(wrappedTypes) { + wrappedTypes; + wrappedTypes[0].release; // $ExpectType () => void + wrappedTypes[0].type.columns[0].desc; // $ExpectType string + wrappedTypes[0].type.columns[0].name; // $ExpectType string + wrappedTypes[0].type.count; // $ExpectType number + wrappedTypes[0].type.name; // $ExpectType string + }, + function updated(wrappedTypes) { + wrappedTypes; + wrappedTypes[0].release; // $ExpectType () => void + wrappedTypes[0].type.columns[0].desc; // $ExpectType string + wrappedTypes[0].type.columns[0].name; // $ExpectType string + wrappedTypes[0].type.count; // $ExpectType number + wrappedTypes[0].type.name; // $ExpectType string + } +); +da.watchModelTypes(() => void); // $ExpectError + +da.watchRecords('house', // $ExpectType () => void + function added(records) { + records[0].object; // $ExpectType object + records[0].columnValues; // $ExpectType object + }, + function updated(records) { + records[0].object; // $ExpectType object + records[0].columnValues; // $ExpectType object + }, + function removed(idx, count) { + idx; // $ExpectType number + count; // $ExpectType number + } +); +da.watchRecords(() => void); // $ExpectError + +da.acceptsModelName; // $ExpectType boolean +da.containerDebugAdapter; // $ExpectType ContainerDebugAdapter + +const ca: Ember.ContainerDebugAdapter = da.containerDebugAdapter; +ca.canCatalogEntriesByType('controller'); // $ExpectType boolean +ca.catalogEntriesByType('controller'); // $ExpectType string[] diff --git a/types/ember/test/debug.ts b/types/ember/test/debug.ts new file mode 100644 index 0000000000..b3f4bb5f17 --- /dev/null +++ b/types/ember/test/debug.ts @@ -0,0 +1,53 @@ +import Ember from 'ember'; + +const { + runInDebug, + warn, + debug, + assert, + Debug: { registerDeprecationHandler, registerWarnHandler } +} = Ember; + +/** + * @ember/debug tests + */ +runInDebug(); // $ExpectError +let x = runInDebug(() => console.log('Should not show up in prod')); // $ExpectType void + +// Log a warning if we have more than 3 tomsters +const tomsterCount = 2; +warn('Too many tomsters!'); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3, { // $ExpectType void + id: 'ember-debug.too-many-tomsters' +}); + +debug(); // $ExpectError +debug('Too many tomsters!'); // $ExpectType void +debug('Too many tomsters!', 'foo'); // $ExpectError + +// Test for truthiness +const str = 'hello'; +assert('Must pass a string', typeof str === 'string'); // $ExpectType void + +// Fail unconditionally +assert('This code path should never be run'); // $ExpectType void + +// next is not called, so no warnings get the default behavior +registerWarnHandler(); // $ExpectError +registerWarnHandler(() => {}); // $ExpectType void +registerWarnHandler((message, { id }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + next; // $ExpectType () => void +}); + +// next is not called, so no warnings get the default behavior +registerDeprecationHandler(); // $ExpectError +registerDeprecationHandler(() => {}); // $ExpectType void +registerDeprecationHandler((message, { id, until }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + until; // $ExpectType string + next; // $ExpectType () => void +}); 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 015be1057b..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: keyof this, 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: keyof this, 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 6619ea0e47..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 @@ -40,6 +44,8 @@ "test/core-object.ts", "test/create-negative.ts", "test/create.ts", + "test/data-adapter.ts", + "test/debug.ts", "test/detect-instance.ts", "test/detect.ts", "test/ember-tests.ts", @@ -58,8 +64,8 @@ "test/route.ts", "test/router.ts", "test/run.ts", - "test/string.ts", "test/string-ext.ts", + "test/string.ts", "test/test.ts", "test/transition.ts", "test/utils.ts", diff --git a/types/ember__application/deprecations.d.ts b/types/ember__application/deprecations.d.ts new file mode 100644 index 0000000000..608ba5c7f7 --- /dev/null +++ b/types/ember__application/deprecations.d.ts @@ -0,0 +1,4 @@ +import Ember from 'ember'; + +export const deprecate: typeof Ember.deprecate; +export const deprecateFunc: typeof Ember.deprecateFunc; diff --git a/types/ember__application/globals-resolver.d.ts b/types/ember__application/globals-resolver.d.ts new file mode 100644 index 0000000000..e51f4681ed --- /dev/null +++ b/types/ember__application/globals-resolver.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class GlobalsResolver extends Ember.DefaultResolver { } diff --git a/types/ember__application/index.d.ts b/types/ember__application/index.d.ts new file mode 100644 index 0000000000..cdef372444 --- /dev/null +++ b/types/ember__application/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for @ember/application 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export default class Application extends Ember.Application { } +export const getOwner: typeof Ember.getOwner; +export const onLoad: typeof Ember.onLoad; +export const runLoadHooks: typeof Ember.runLoadHooks; +export const setOwner: typeof Ember.setOwner; diff --git a/types/ember__application/instance.d.ts b/types/ember__application/instance.d.ts new file mode 100644 index 0000000000..0d01298d52 --- /dev/null +++ b/types/ember__application/instance.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class ApplicationInstance extends Ember.ApplicationInstance { } diff --git a/types/ember__application/resolver.d.ts b/types/ember__application/resolver.d.ts new file mode 100644 index 0000000000..a218fcd3e7 --- /dev/null +++ b/types/ember__application/resolver.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class Resolver extends Ember.Resolver { } diff --git a/types/ember__application/test/application-instance.ts b/types/ember__application/test/application-instance.ts new file mode 100644 index 0000000000..4ee5cb2027 --- /dev/null +++ b/types/ember__application/test/application-instance.ts @@ -0,0 +1,29 @@ +import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; + +const appInstance = ApplicationInstance.create(); +appInstance.register('some:injection', class Foo {}); + +appInstance.register('some:injection', class Foo {}, { + singleton: true, +}); + +appInstance.register('some:injection', class Foo {}, { + instantiate: false, +}); + +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + +appInstance.register('some:injection', class Foo {}, { + singleton: false, + instantiate: true, +}); + +appInstance.factoryFor('router:main'); +appInstance.lookup('route:basic'); + +appInstance.boot(); + +(async () => { + await appInstance.boot(); +})(); diff --git a/types/ember__application/test/application.ts b/types/ember__application/test/application.ts new file mode 100755 index 0000000000..21d0237b71 --- /dev/null +++ b/types/ember__application/test/application.ts @@ -0,0 +1,41 @@ +import Application from "@ember/application"; +import EmberObject from "@ember/object"; + +const BaseApp = Application.extend({ + modulePrefix: 'my-app' +}); + +BaseApp.initializer({ + name: 'my-initializer', + initialize(app) { + app.register('foo:bar', EmberObject.extend({ foo: 'bar' })); + } +}); + +BaseApp.instanceInitializer({ + name: 'my-instance-initializer', + initialize(app) { + app.lookup('foo:bar').get('foo'); + } +}); + +const App1 = BaseApp.create({ + rootElement: '#app-one', + customEvents: { + paste: 'paste' + } +}); + +const App2 = BaseApp.create({ + rootElement: '#app-two', + customEvents: { + mouseenter: null, + mouseleave: null + } +}); + +const App3 = BaseApp.create(); + +const App3Instance1 = App3.buildInstance(); // $ExpectType ApplicationInstance + +const App3Instance2 = App3.buildInstance({ foo: 'bar' }); // $ExpectType ApplicationInstance diff --git a/types/ember__application/test/deprecations.ts b/types/ember__application/test/deprecations.ts new file mode 100644 index 0000000000..12639ad0b5 --- /dev/null +++ b/types/ember__application/test/deprecations.ts @@ -0,0 +1,14 @@ +import { deprecate, deprecateFunc } from '@ember/application/deprecations'; + +deprecate('this is no longer advised', false, { + id: 'no-longer-advised', + until: 'v4.0' +}); +deprecate('this is no longer advised', false); + +deprecateFunc('this is no longer advised', () => {}); +deprecateFunc( + 'this is no longer advised', + { id: 'no-longer-do-this', until: 'v4.0' }, + () => {} +); diff --git a/types/ember__application/test/globals-resolver.ts b/types/ember__application/test/globals-resolver.ts new file mode 100644 index 0000000000..c0efb5579b --- /dev/null +++ b/types/ember__application/test/globals-resolver.ts @@ -0,0 +1,6 @@ +import GlobalsResolver from "@ember/application/globals-resolver"; + +const gr = GlobalsResolver.create(); + +gr.resolve('App.IndexController'); +gr.resolve(); // $ExpectError diff --git a/types/ember__application/test/resolver.ts b/types/ember__application/test/resolver.ts new file mode 100644 index 0000000000..20413aa5a4 --- /dev/null +++ b/types/ember__application/test/resolver.ts @@ -0,0 +1,3 @@ +import Resolver from "@ember/application/resolver"; + +const res = Resolver.create(); diff --git a/types/ember__application/tsconfig.json b/types/ember__application/tsconfig.json new file mode 100644 index 0000000000..833859d183 --- /dev/null +++ b/types/ember__application/tsconfig.json @@ -0,0 +1,37 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "deprecations.d.ts", + "globals-resolver.d.ts", + "index.d.ts", + "instance.d.ts", + "resolver.d.ts", + "test/application.ts", + "test/deprecations.ts", + "test/resolver.ts", + "test/globals-resolver.ts", + "test/application-instance.ts" + ] +} diff --git a/types/ember__application/tslint.json b/types/ember__application/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__application/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__array/index.d.ts b/types/ember__array/index.d.ts new file mode 100644 index 0000000000..991f7961f2 --- /dev/null +++ b/types/ember__array/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for @ember/array 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +type EmberArray = Ember.Array; +export const EmberArray: typeof Ember.Array; +export default EmberArray; +export const A: typeof Ember.A; +export const isArray: typeof Ember.isArray; diff --git a/types/ember__array/mutable.d.ts b/types/ember__array/mutable.d.ts new file mode 100644 index 0000000000..a477c92f69 --- /dev/null +++ b/types/ember__array/mutable.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; + +type MutableArray = Ember.MutableArray; +export const MutableArray: typeof Ember.MutableArray; +export default MutableArray; diff --git a/types/ember__array/proxy.d.ts b/types/ember__array/proxy.d.ts new file mode 100644 index 0000000000..ced7b5c14c --- /dev/null +++ b/types/ember__array/proxy.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class ArrayProxy extends Ember.ArrayProxy { } diff --git a/types/ember__array/test/array-ext.ts b/types/ember__array/test/array-ext.ts new file mode 100755 index 0000000000..72e9098100 --- /dev/null +++ b/types/ember__array/test/array-ext.ts @@ -0,0 +1,22 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; +import { ArrayPrototypeExtensions } from '@ember/array/types/prototype-extensions'; + +declare global { + interface Array extends ArrayPrototypeExtensions {} +} + +class Person extends EmberObject { + name: string; +} + +const person = Person.create({ name: 'Joe' }); +const array = [person]; + +assertType(array.get('length')); +assertType(array.get('firstObject')); +assertType(array.mapBy('name')); +assertType(array.map(p => p.get('name'))); +assertType(array.sortBy('name')); +assertType(array.uniq()); +assertType(array.uniqBy('name')); diff --git a/types/ember__array/test/array-proxy.ts b/types/ember__array/test/array-proxy.ts new file mode 100644 index 0000000000..f4ca116e14 --- /dev/null +++ b/types/ember__array/test/array-proxy.ts @@ -0,0 +1,27 @@ +import { assertType } from './lib/assert'; +import ArrayProxy from '@ember/array/proxy'; +import { A } from '@ember/array'; + +const pets = ['dog', 'cat', 'fish']; +const proxy = ArrayProxy.create({ content: A(pets) }); + +proxy.get('firstObject'); // 'dog' +proxy.set('content', A(['amoeba', 'paramecium'])); +proxy.get('firstObject'); // 'amoeba' + +const overridden = ArrayProxy.create({ + content: A(pets), + objectAtContent(idx: number): string { + return this.get('content').objectAt(idx)!.toUpperCase(); + } +}); + +overridden.get('firstObject'); // 'DOG' + +class MyNewProxy extends ArrayProxy { + isNew = true; +} + +const x = MyNewProxy.create({ content: A([1, 2, 3]) }) as MyNewProxy; +assertType(x.get('firstObject')); +assertType(x.isNew); diff --git a/types/ember__array/test/array.ts b/types/ember__array/test/array.ts new file mode 100755 index 0000000000..5d578e4319 --- /dev/null +++ b/types/ember__array/test/array.ts @@ -0,0 +1,56 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; +import EmberArray, { A } from '@ember/array'; +import MutableArray from '@ember/array/mutable'; + +type Person = typeof Person.prototype; +const Person = EmberObject.extend({ + name: '', + isHappy: false +}); + +const people = A([ + Person.create({ name: 'Yehuda', isHappy: true }), + Person.create({ name: 'Majd', isHappy: false }), +]); + +assertType(people.get('length')); +assertType(people.get('lastObject')); +assertType(people.get('firstObject')); +assertType(people.isAny('isHappy')); +assertType(people.isAny('isHappy', 'false')); + +const persons1: Person[] = people.filterBy('isHappy'); +const persons2: MutableArray = people.filterBy('isHappy'); +const persons3: Person[] = people.rejectBy('isHappy'); +const persons4: MutableArray = people.rejectBy('isHappy'); +const persons5: Person[] = people.filter((person) => person.get('name') === 'Yehuda'); +const persons6: MutableArray = people.filter((person) => person.get('name') === 'Yehuda'); + +assertType(people.get('[]')); +assertType(people.get('[]').get('firstObject')); // $ExpectType any + +assertType>(people.mapBy('isHappy')); // $ExpectType Array +assertType(people.mapBy('name.length')); + +const last = people.get('lastObject'); // $ExpectType ({ name: string; isHappy: boolean; } & EmberObject & { name: string; isHappy: boolean; }) | undefined +if (last) { + assertType(last.get('name')); +} + +const first = people.get('lastObject'); +if (first) { + assertType(first.get('isHappy')); +} + +const letters: EmberArray = A(['a', 'b', 'c']); +const codes: number[] = letters.map((item, index, enumerable) => { + assertType(item); + assertType(index); + return item.charCodeAt(0); +}); + +const value = '1,2,3'; +const filters = A(value.split(',')); +filters.push('4'); +filters.sort(); diff --git a/types/ember__array/test/lib/assert.ts b/types/ember__array/test/lib/assert.ts new file mode 100755 index 0000000000..262d18bc2c --- /dev/null +++ b/types/ember__array/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__array/tsconfig.json b/types/ember__array/tsconfig.json new file mode 100644 index 0000000000..e6c8d509e0 --- /dev/null +++ b/types/ember__array/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mutable.d.ts", + "proxy.d.ts", + "types/prototype-extensions.d.ts", + "test/lib/assert.ts", + "test/array.ts", + "test/array-ext.ts", + "test/array-proxy.ts" + ] +} diff --git a/types/ember__array/tslint.json b/types/ember__array/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__array/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__array/types/prototype-extensions.d.ts b/types/ember__array/types/prototype-extensions.d.ts new file mode 100644 index 0000000000..a6197166ef --- /dev/null +++ b/types/ember__array/types/prototype-extensions.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export interface ArrayPrototypeExtensions extends Ember.MutableArray, Ember.Observable, Ember.Copyable {} diff --git a/types/ember__debug/container-debug-adapter.d.ts b/types/ember__debug/container-debug-adapter.d.ts new file mode 100644 index 0000000000..4bd24103a4 --- /dev/null +++ b/types/ember__debug/container-debug-adapter.d.ts @@ -0,0 +1,2 @@ +import Ember from 'ember'; +export default class ContainerDebugAdapter extends Ember.ContainerDebugAdapter { } diff --git a/types/ember__debug/data-adapter.d.ts b/types/ember__debug/data-adapter.d.ts new file mode 100644 index 0000000000..bc86573991 --- /dev/null +++ b/types/ember__debug/data-adapter.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class DataAdapter extends Ember.DataAdapter {} diff --git a/types/ember__debug/ember__debug-tests.ts b/types/ember__debug/ember__debug-tests.ts new file mode 100644 index 0000000000..0fbdcbc174 --- /dev/null +++ b/types/ember__debug/ember__debug-tests.ts @@ -0,0 +1,45 @@ +import { runInDebug, warn, debug, assert, registerWarnHandler, registerDeprecationHandler } from "@ember/debug"; + +/** + * @ember/debug tests + */ +runInDebug(); // $ExpectError +runInDebug(() => console.log('Should not show up in prod')); // $ExpectType void + +// Log a warning if we have more than 3 tomsters +const tomsterCount = 2; +warn('Too many tomsters!'); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3, { // $ExpectType void + id: 'ember-debug.too-many-tomsters' +}); + +debug(); // $ExpectError +debug('Too many tomsters!'); // $ExpectType void +debug('Too many tomsters!', 'foo'); // $ExpectError + +// Test for truthiness +const str = 'hello'; +assert('Must pass a string', typeof str === 'string'); // $ExpectType void + +// Fail unconditionally +assert('This code path should never be run'); // $ExpectType void + +// next is not called, so no warnings get the default behavior +registerWarnHandler(); // $ExpectError +registerWarnHandler(() => {}); // $ExpectType void +registerWarnHandler((message, { id }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + next; // $ExpectType () => void +}); + +// next is not called, so no warnings get the default behavior +registerDeprecationHandler(); // $ExpectError +registerDeprecationHandler(() => {}); // $ExpectType void +registerDeprecationHandler((message, { id, until }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + until; // $ExpectType string + next; // $ExpectType () => void +}); diff --git a/types/ember__debug/index.d.ts b/types/ember__debug/index.d.ts new file mode 100644 index 0000000000..8f1352baff --- /dev/null +++ b/types/ember__debug/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for @ember/debug 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; +export const assert: typeof Ember.assert; +export const debug: typeof Ember.debug; +export const inspect: typeof Ember.inspect; +export const registerDeprecationHandler: typeof Ember.Debug.registerDeprecationHandler; +export const registerWarnHandler: typeof Ember.Debug.registerWarnHandler; +export const runInDebug: typeof Ember.runInDebug; +export const warn: typeof Ember.warn; diff --git a/types/ember__debug/tsconfig.json b/types/ember__debug/tsconfig.json new file mode 100644 index 0000000000..c7688e6861 --- /dev/null +++ b/types/ember__debug/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "data-adapter.d.ts", + "container-debug-adapter.d.ts", + "ember__debug-tests.ts" + ] +} diff --git a/types/ember__debug/tslint.json b/types/ember__debug/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/ember__debug/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} diff --git a/types/ember__error/ember__error-tests.ts b/types/ember__error/ember__error-tests.ts new file mode 100644 index 0000000000..a5e605cfee --- /dev/null +++ b/types/ember__error/ember__error-tests.ts @@ -0,0 +1,3 @@ +import Error from '@ember/error'; + +new Error('Fuuuuuuuu'); // $ExpectType Error diff --git a/types/ember__error/index.d.ts b/types/ember__error/index.d.ts new file mode 100644 index 0000000000..40a660ae0e --- /dev/null +++ b/types/ember__error/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for @ember/error 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 const Error: typeof Ember.Error; +export default Error; diff --git a/types/ember__error/tsconfig.json b/types/ember__error/tsconfig.json new file mode 100644 index 0000000000..92f8f7f0ca --- /dev/null +++ b/types/ember__error/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/error": ["ember__error"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__error-tests.ts" + ] +} diff --git a/types/ember__error/tslint.json b/types/ember__error/tslint.json new file mode 100644 index 0000000000..495d29983d --- /dev/null +++ b/types/ember__error/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} 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 new file mode 100644 index 0000000000..68a6588a69 --- /dev/null +++ b/types/ember__polyfills/ember__polyfills-tests.ts @@ -0,0 +1,22 @@ +import { assign, merge } from '@ember/polyfills'; + +(() => { /* assign */ + assign({}, { a: 'b'}); + assign({}, { a: 'b'}).a; // $ExpectType string + assign({ a: 6 }, { a: 'b'}).a; // $ExpectType string + assign({ a: 6 }, {}).a; // $ExpectType number + assign({ b: 6 }, {}).a; // $ExpectError + assign({}, { b: 6 }, {}).b; // $ExpectType number + assign({ a: 'hello' }, { b: 6 }, {}).a; // $ExpectType string + 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[] +})(); + +(() => { /* merge */ + merge({}, { a: 'b'}); + merge({}, { a: 'b'}).a; // $ExpectType string + merge({ a: 6 }, { a: 'b'}).a; // $ExpectType string + merge({ a: 6 }, {}).a; // $ExpectType number + merge({ b: 6 }, {}).a; // $ExpectError +})(); diff --git a/types/ember__polyfills/index.d.ts b/types/ember__polyfills/index.d.ts new file mode 100644 index 0000000000..1bca6dbba4 --- /dev/null +++ b/types/ember__polyfills/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for @ember/polyfills 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Mix, Mix3, Mix4 } from './types'; + +/** + * 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 new file mode 100644 index 0000000000..ab08b95d99 --- /dev/null +++ b/types/ember__polyfills/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/polyfills": ["ember__polyfills"], + "@ember/polyfills/*": ["ember__polyfills/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "types.d.ts", + "ember__polyfills-tests.ts" + ] +} diff --git a/types/ember__polyfills/tslint.json b/types/ember__polyfills/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__polyfills/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} 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__runloop/ember__runloop-tests.ts b/types/ember__runloop/ember__runloop-tests.ts new file mode 100644 index 0000000000..132d687bbd --- /dev/null +++ b/types/ember__runloop/ember__runloop-tests.ts @@ -0,0 +1,203 @@ +import Ember from 'ember'; +import RSVP from 'rsvp'; +import { run } from '@ember/runloop'; + +Ember.run.queues; // $ExpectType EmberRunQueues[] +const queues: string[] = Ember.run.queues; + +function testRun() { + run(() => { // $ExpectType number + // code to be executed within a RunLoop + return 123; + }); + + function destroyApp(application: Ember.Application) { + Ember.run(application, 'destroy'); + run(application, function() { + this.destroy(); + }); + } +} + +function testBind() { + Ember.Component.extend({ + init() { + const bound = Ember.run.bind(this, this.setupEditor); + bound(); + }, + + editor: null as string | null, + + setupEditor(editor: string) { + this.set('editor', editor); + } + }); +} + +function testCancel() { + const myContext = {}; + + const runNext = run.next(myContext, () => { + // will not be executed + }); + + run.cancel(runNext); + + const runLater = run.later(myContext, () => { + // will not be executed + }, 500); + + run.cancel(runLater); + + const runScheduleOnce = run.scheduleOnce('afterRender', myContext, () => { + // will not be executed + }); + + run.cancel(runScheduleOnce); + + const runOnce = run.once(myContext, () => { + // will not be executed + }); + + run.cancel(runOnce); + + const throttle = run.throttle(myContext, () => { + // will not be executed + }, 1, false); + + run.cancel(throttle); + + const debounce = run.debounce(myContext, () => { + // will not be executed + }, 1); + + run.cancel(debounce); + + const debounceImmediate = run.debounce(myContext, () => { + // will be executed since we passed in true (immediate) + }, 100, true); + + // the 100ms delay until this method can be called again will be canceled + run.cancel(debounceImmediate); +} + +function testDebounce() { + function runIt() { + } + + const myContext = { name: 'debounce' }; + + run.debounce(runIt, 150); + run.debounce(myContext, runIt, 150); + run.debounce(myContext, runIt, 150, true); + + Ember.Component.extend({ + searchValue: 'test', + fetchResults(value: string) {}, + + actions: { + handleTyping() { + // the fetchResults function is passed into the component from its parent + Ember.run.debounce(this, this.get('fetchResults'), this.get('searchValue'), 250); + } + } + }); +} + +function testBegin() { + run.begin(); + // code to be executed within a RunLoop + run.end(); +} + +function testJoin() { + run.join(() => { + // creates a new run-loop + }); + + run(() => { + // creates a new run-loop + run.join(() => { + // joins with the existing run-loop, and queues for invocation on + // the existing run-loops action queue. + }); + }); + + new RSVP.Promise((resolve) => { + Ember.run.later(() => { + resolve({ msg: 'Hold Your Horses' }); + }, 3000); + }); +} + +function testLater() { + const myContext = {}; + run.later(myContext, () => { + // code here will execute within a RunLoop in about 500ms with this == myContext + }, 500); +} + +function testNext() { + const myContext = {}; + run.next(myContext, () => { + // code to be executed in the next run loop, + // which will be scheduled after the current one + }); +} + +function testOnce() { + Ember.Component.extend({ + init() { + Ember.run.once(this, 'processFullName'); + }, + + processFullName() { + } + }); +} + +function testSchedule() { + Ember.Component.extend({ + init() { + run.schedule('sync', this, () => { + // this will be executed in the first RunLoop queue, when bindings are synced + console.log('scheduled on sync queue'); + }); + + run.schedule('actions', this, () => { + // this will be executed in the 'actions' queue, after bindings have synced. + console.log('scheduled on actions queue'); + }); + } + }); + + Ember.run.schedule('actions', () => { + // Do more things + }); +} + +function testScheduleOnce() { + function sayHi() { + console.log('hi'); + } + + const myContext = {}; + run(() => { + run.scheduleOnce('afterRender', myContext, sayHi); + run.scheduleOnce('afterRender', myContext, sayHi); + // sayHi will only be executed once, in the afterRender queue of the RunLoop + }); + run.scheduleOnce('actions', myContext, () => { + console.log('Closure'); + }); +} + +function testThrottle() { + function runIt() { + } + + const myContext = { name: 'throttle' }; + + run.throttle(runIt, 150); + run.throttle(myContext, runIt, 150); +} diff --git a/types/ember__runloop/index.d.ts b/types/ember__runloop/index.d.ts new file mode 100644 index 0000000000..acc8c3ad8a --- /dev/null +++ b/types/ember__runloop/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for @ember/runloop 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export const begin: typeof Ember.run.begin; +export const bind: typeof Ember.run.bind; +export const cancel: typeof Ember.run.cancel; +export const debounce: typeof Ember.run.debounce; +export const end: typeof Ember.run.end; +export const join: typeof Ember.run.join; +export const later: typeof Ember.run.later; +export const next: typeof Ember.run.next; +export const once: typeof Ember.run.once; +export const run: typeof Ember.run; +export const schedule: typeof Ember.run.schedule; +export const scheduleOnce: typeof Ember.run.scheduleOnce; +export const throttle: typeof Ember.run.throttle; diff --git a/types/ember__runloop/tsconfig.json b/types/ember__runloop/tsconfig.json new file mode 100644 index 0000000000..ef1e325ff4 --- /dev/null +++ b/types/ember__runloop/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/runloop": ["ember__runloop"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__runloop-tests.ts" + ] +} diff --git a/types/ember__runloop/tslint.json b/types/ember__runloop/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/ember__runloop/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} diff --git a/types/ember__string/ember__string-tests.ts b/types/ember__string/ember__string-tests.ts new file mode 100644 index 0000000000..f9f7dbef50 --- /dev/null +++ b/types/ember__string/ember__string-tests.ts @@ -0,0 +1,33 @@ +import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } from '@ember/string'; + +dasherize(); // $ExpectError +dasherize('blue man group'); // $ExpectType string +dasherize('', ''); // $ExpectError + +camelize(); // $ExpectError +camelize('blue man group'); // $ExpectType string +camelize('', ''); // $ExpectError + +decamelize(); // $ExpectError +decamelize('blue man group'); // $ExpectType string +decamelize('', ''); // $ExpectError + +underscore(); // $ExpectError +underscore('blue man group'); // $ExpectType string +underscore('', ''); // $ExpectError + +w(); // $ExpectError +w('blue man group'); // $ExpectType string[] +w('', ''); // $ExpectError + +classify(); // $ExpectError +classify('blue man group'); // $ExpectType string +classify('', ''); // $ExpectError + +capitalize(); // $ExpectError +capitalize('blue man group'); // $ExpectType string +capitalize('', ''); // $ExpectError + +loc(); // $ExpectError +loc("_Hello World"); // $ExpectType string +loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string diff --git a/types/ember__string/index.d.ts b/types/ember__string/index.d.ts new file mode 100644 index 0000000000..d000cfa443 --- /dev/null +++ b/types/ember__string/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for @ember/string 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { SafeString } from 'handlebars'; + +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__string/tsconfig.json b/types/ember__string/tsconfig.json new file mode 100644 index 0000000000..100fad10f5 --- /dev/null +++ b/types/ember__string/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/string": ["ember__string"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__string-tests.ts" + ] +} diff --git a/types/ember__string/tslint.json b/types/ember__string/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__string/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__test/adapter.d.ts b/types/ember__test/adapter.d.ts new file mode 100644 index 0000000000..5f312cf381 --- /dev/null +++ b/types/ember__test/adapter.d.ts @@ -0,0 +1,2 @@ +import Ember from 'ember'; +export default class TestAdapter extends Ember.Test.Adapter { } diff --git a/types/ember__test/ember__test-tests.ts b/types/ember__test/ember__test-tests.ts new file mode 100644 index 0000000000..b98ab26a01 --- /dev/null +++ b/types/ember__test/ember__test-tests.ts @@ -0,0 +1,39 @@ +import { registerWaiter, registerHelper, registerAsyncHelper } from '@ember/test'; +import TestAdapter from '@ember/test/adapter'; + +const pending = 0; +registerWaiter(() => pending !== 0); + +declare const MyDb: { + hasPendingTransactions(): boolean; +}; + +registerWaiter(MyDb, MyDb.hasPendingTransactions); +registerWaiter(); // $ExpectError + +registerHelper('boot', app => { + app.advanceReadiness(); // $ExpectType void + app.deferReadiness(); // $ExpectType void + app.register('foo', class {}); // $ExpectType void + app.register('foo'); // $ExpectError + app.register(); // $ExpectError +}); + +registerAsyncHelper('boot', app => { + app.advanceReadiness(); + app.deferReadiness(); + app.register('foo', class {}); +}); + +registerAsyncHelper('waitForPromise', (app, promise) => { + app.advanceReadiness(); + app.deferReadiness(); + app.register('foo', class {}); + return new Promise(() => { + const adapter = new TestAdapter(); + adapter.asyncStart(); + return promise.then(() => { + adapter.asyncEnd(); + }); + }); +}); diff --git a/types/ember__test/index.d.ts b/types/ember__test/index.d.ts new file mode 100644 index 0000000000..94bc312566 --- /dev/null +++ b/types/ember__test/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for @ember/test 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; +export const registerAsyncHelper: typeof Ember.Test.registerAsyncHelper; +export const registerHelper: typeof Ember.Test.registerHelper; +export const registerWaiter: typeof Ember.Test.registerWaiter; +export const unregisterHelper: typeof Ember.Test.unregisterHelper; +export const unregisterWaiter: typeof Ember.Test.unregisterWaiter; diff --git a/types/ember__test/tsconfig.json b/types/ember__test/tsconfig.json new file mode 100644 index 0000000000..89f8c76b60 --- /dev/null +++ b/types/ember__test/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/test": ["ember__test"], + "@ember/test/*": ["ember__test/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "adapter.d.ts", + "ember__test-tests.ts" + ] +} diff --git a/types/ember__test/tslint.json b/types/ember__test/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/ember__test/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} 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/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index e1762b843e..0711243d0c 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -363,6 +363,10 @@ function ShallowWrapperTest() { shallowWrapper.simulate('click', args); } + function test_simulateError(error: any) { + shallowWrapper.simulateError(error); + } + function test_setState() { shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }, () => console.log('state updated')); } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index a91f60b3c6..60262e3d04 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -221,6 +221,13 @@ export interface CommonWrapper

> { */ simulate(event: string, ...args: any[]): this; + /** + * Used to simulate throwing a rendering error. Pass an error to throw. + * Returns itself. + * @param error + */ + simulateError(error: any): this; + /** * A method to invoke setState() on the root component instance similar to how you might in the definition of * the component, and re-renders. This method is useful for testing your component in hard to achieve states, 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/faker/index.d.ts b/types/faker/index.d.ts index 248a0ba96c..a9d044cfcb 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -201,8 +201,8 @@ declare namespace Faker { }; system: { - fileName(ext: string, type: string): string; - commonFileName(ext: string, type: string): string; + fileName(ext?: string, type?: string): string; + commonFileName(ext: string, type?: string): string; mimeType(): string; commonFileType(): string; commonFileExt(): string; 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/jest-when/index.d.ts b/types/jest-when/index.d.ts new file mode 100644 index 0000000000..af62a95830 --- /dev/null +++ b/types/jest-when/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jest-when 1.1 +// Project: https://github.com/timkindberg/jest-when#readme +// Definitions by: Alden Taylor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export interface PartialMockInstance { + mockReturnValue: jest.MockInstance['mockReturnValue']; +} + +export interface When { + (fn: jest.Mocked | jest.Mock): When; + // due to no-unnecessary-generics lint rule, the generics have been replaced with 'any' + // calledWith(...matchers: any[]): PartialMockInstance; + // expectCalledWith(...matchers: any[]): PartialMockInstance; + calledWith(...matchers: any[]): PartialMockInstance; + expectCalledWith(...matchers: any[]): PartialMockInstance; +} + +export const when: When; diff --git a/types/jest-when/jest-when-tests.ts b/types/jest-when/jest-when-tests.ts new file mode 100644 index 0000000000..13da65928d --- /dev/null +++ b/types/jest-when/jest-when-tests.ts @@ -0,0 +1,57 @@ +import { when } from 'jest-when'; + +describe('mock-when test', () => { + it('basic usage:', () => { + const fn = jest.fn(); + when(fn).calledWith(1).mockReturnValue('yay!'); + + const result = fn(1); + expect(result).toEqual('yay!'); + }); + + it('Supports multiple args:', () => { + const fn = jest.fn(); + when(fn).calledWith(1, true, 'foo').mockReturnValue('yay!'); + + const result = fn(1, true, 'foo'); + expect(result).toEqual('yay!'); + }); + + it('Supports jest matchers:', () => { + const fn = jest.fn(); + when(fn).calledWith( + expect.anything(), + expect.any(Number), + expect.arrayContaining([false]) + ).mockReturnValue('yay!'); + + const result = fn('whatever', 100, [true, false]); + expect(result).toEqual('yay!'); + }); + + it('Supports compound declarations:', () => { + const fn = jest.fn(); + when(fn).calledWith(1).mockReturnValue('no'); + when(fn).calledWith(2).mockReturnValue('way?'); + when(fn).calledWith(3).mockReturnValue('yes'); + when(fn).calledWith(4).mockReturnValue('way!'); + + expect(fn(1)).toEqual('no'); + expect(fn(2)).toEqual('way?'); + expect(fn(3)).toEqual('yes'); + expect(fn(4)).toEqual('way!'); + expect(fn(5)).toEqual(undefined); + }); + + it('Assert the args:', () => { + const fn = jest.fn(); + when(fn).expectCalledWith(1).mockReturnValue('x'); + let testPassed = false; + try { + fn(2); // Will throw a helpful jest assertion error with args diff + } catch (e) { + testPassed = true; + } + expect(testPassed).toBeTruthy(); + }); +}); diff --git a/types/jest-when/tsconfig.json b/types/jest-when/tsconfig.json new file mode 100644 index 0000000000..46c037813f --- /dev/null +++ b/types/jest-when/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", + "jest-when-tests.ts" + ] +} \ No newline at end of file diff --git a/types/redux-little-router/tslint.json b/types/jest-when/tslint.json similarity index 100% rename from types/redux-little-router/tslint.json rename to types/jest-when/tslint.json diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 5af6969665..166be7d526 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -13,6 +13,8 @@ // Rafael Kallis // Conan Lai // Peter Thorson +// Will Garcia +// Simon Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -147,6 +149,13 @@ export interface UriOptions { relativeOnly?: boolean; } +export interface DataUriOptions { + /** + * optional parameter defaulting to true which will require = padding if true or make padding optional if false + */ + paddingRequired?: boolean; +} + export interface Base64Options { /** * optional parameter defaulting to true which will require = padding if true or make padding optional if false @@ -630,6 +639,11 @@ export interface StringSchema extends AnySchema { */ uri(options?: UriOptions): this; + /** + * Requires the string value to be a valid data URI string. + */ + dataUri(options?: DataUriOptions): this; + /** * Requires the string value to be a valid GUID. */ diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 5defe20cc1..c9805e1fc3 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -120,6 +120,12 @@ base64Opts = { paddingRequired: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +let dataUriOpts: Joi.DataUriOptions = null; + +dataUriOpts = { paddingRequired: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + let whenOpts: Joi.WhenOptions = null; whenOpts = { is: x }; @@ -818,6 +824,8 @@ strSchema = strSchema.normalize(); strSchema = strSchema.normalize('NFKC'); strSchema = strSchema.base64(); strSchema = strSchema.base64(base64Opts); +strSchema = strSchema.dataUri(); +strSchema = strSchema.dataUri(dataUriOpts); { // common strSchema = strSchema.allow(x); 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/kue/index.d.ts b/types/kue/index.d.ts index 4117ef0a82..9153039ff0 100644 --- a/types/kue/index.d.ts +++ b/types/kue/index.d.ts @@ -78,6 +78,8 @@ export declare class Job extends events.EventEmitter { public failed_at: string | number; public started_at: string | number; public client: redisClientFactory.RedisClient; + public workerId: string; + private _error: string; private _max_attempts; static priorities: Priorities; 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/mali/index.d.ts b/types/mali/index.d.ts index 1c73b18c75..8e536d5330 100644 --- a/types/mali/index.d.ts +++ b/types/mali/index.d.ts @@ -10,68 +10,68 @@ import { EventEmitter } from 'events'; import { Stream } from 'stream'; declare class Mali extends EventEmitter { - constructor(path: any, name?: string | ReadonlyArray, options?: any); - name: string; - env: string; - ports: ReadonlyArray; // ? not sure which it is - silent: boolean; + constructor(path: any, name?: string | ReadonlyArray, options?: any); + name: string; + env: string; + ports: ReadonlyArray; + silent: boolean; - addService(path: any, name: string | ReadonlyArray, options?: any): void; - use(service?: any, name?: any, fns?: any): void; - start(port?: any, creds?: any, options?: any): any; // gnarly type asserting for these functions so Im just gonna let them handle it. - toJSON(): any; - close(): void; - inspect(): any; + addService(path: any, name: string | ReadonlyArray, options?: any): void; + use(service?: any, name?: any, fns?: any): void; + start(port: number | string, creds?: any, options?: any): any; // gnarly type inferring for these functions so Im just gonna let them handle it. + toJSON(): any; + close(): Promise; + inspect(): any; } declare namespace Mali { - interface Context { - name: string; - fullName: string; - service: string; - package: string; - app: any; // ? app - call: any; - request: Request; - response: Response; - req: any; // ? - res: any; // ? - type: string; - metadata: string; - get(field: string): any; - set(field: any, val?: any): void; // do I need `?:` if its of type `any`? - sendMetadata(md: any): void; - getStatus(field: string): any; - setStatus(field: any, val?: any): void; // ^ - } + interface Context { + name: string; + fullName: string; + service: string; + package: string; + app: any; // ? app + call: any; + request: Request; + response: Response; + req: any; // ? + res: any; // ? + type: string; + metadata: string; + get(field: string): any; + set(field: any, val?: any): void; // do I need `?:` if its of type `any`? + sendMetadata(md: any): void; + getStatus(field: string): any; + setStatus(field: any, val?: any): void; // ^ + } - class Request { - constructor(call: any, type: string); - call: any; - type: string; - metadata: any; - req: any; // ? + class Request { + constructor(call: any, type: string); + call: any; + type: string; + metadata: any; + req: any; // ? - getMetadata(): any; - get(field: string): any; - } + getMetadata(): any; + get(field: string): any; + } - class Response { - constructor(call: any, type: string); - call: any; - type: string; - metadata: any; - status: any; - res: any; // ? - set(field: any, val?: any): void; // is `val?:` necessary when its of type `any`? - get(field: string): any; - getMetadata(): any; - sendMetadata(md?: any): void; - getStatus(field: string): any; - setStatus(field: any, val?: any): void; // ^ same as above - } + class Response { + constructor(call: any, type: string); + call: any; + type: string; + metadata: any; + status: any; + res: any; // ? + set(field: any, val?: any): void; // is `val?:` necessary when its of type `any`? + get(field: string): any; + getMetadata(): any; + sendMetadata(md?: any): void; + getStatus(field: string): any; + setStatus(field: any, val?: any): void; // ^ same as above + } - function exec(ctx: Context, handler: any, cb?: any): void; + function exec(ctx: Context, handler: any, cb?: any): void; } export = Mali; 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/memdown/index.d.ts b/types/memdown/index.d.ts new file mode 100644 index 0000000000..ab7b8dfe36 --- /dev/null +++ b/types/memdown/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for memdown 3.0 +// Project: https://github.com/Level/memdown +// Definitions by: Meirion Hughes +// Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { AbstractLevelDOWN } from 'abstract-leveldown'; + +export interface MemDown extends AbstractLevelDOWN {} + +export interface MemDownConstructor { + // tslint:disable-next-line no-unnecessary-generics + new (): MemDown; + // tslint:disable-next-line no-unnecessary-generics + (): MemDown; +} + +export const MemDown: MemDownConstructor; +export default MemDown; diff --git a/types/memdown/memdown-tests.ts b/types/memdown/memdown-tests.ts new file mode 100644 index 0000000000..f93a4bb779 --- /dev/null +++ b/types/memdown/memdown-tests.ts @@ -0,0 +1,16 @@ +import MemDown from 'memdown'; + +const test = (db: MemDown) => { + db.open(() => { + db.put("key", "value", (err?: Error) => { }); + db.get("key", (err?: Error) => { }); + db.get("key", (err: Error | undefined, value: string) => { }); + db.close(() => {}); + }); +}; + +// doesn't need `new` and can be called as a function +test(new MemDown()); +test(new MemDown()); +test(MemDown()); +test(MemDown()); diff --git a/types/memdown/tsconfig.json b/types/memdown/tsconfig.json new file mode 100644 index 0000000000..dd3aa17b6c --- /dev/null +++ b/types/memdown/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", + "memdown-tests.ts" + ] +} \ No newline at end of file diff --git a/types/memdown/tslint.json b/types/memdown/tslint.json new file mode 100644 index 0000000000..256ee54775 --- /dev/null +++ b/types/memdown/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 3534f82f49..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; @@ -2759,6 +2764,24 @@ declare module "mongoose" { /** sets the document fields to return */ select?: any; }, callback?: (err: any, res: T | null) => void): DocumentQuery; + + + /** + * Issue a mongodb findOneAndDelete command by a document's _id field. + * findByIdAndDelete(id, ...) is equivalent to findByIdAndDelete({ _id: id }, ...). + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed, else a Query object is returned. + * @param id value of _id to query by + */ + findByIdAndDelete(): DocumentQuery; + findByIdAndDelete(id: any | number | string, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findByIdAndDelete(id: any | number | string, options: { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** sets the document fields to return */ + select?: any; + }, callback?: (err: any, res: T | null) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) @@ -2970,6 +2993,7 @@ declare module "mongoose" { interface SaveOptions { safe?: boolean | WriteConcern; validateBeforeSave?: boolean; + session?: ClientSession; } interface WriteConcern { @@ -3012,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/native-toast/index.d.ts b/types/native-toast/index.d.ts new file mode 100644 index 0000000000..1b9e532255 --- /dev/null +++ b/types/native-toast/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for native-toast 2.0 +// Project: https://github.com/egoist/native-toast +// Definitions by: Michael Nahkies +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const toast: { + (options: ToastOptions): Toast, + success: (options: ToastOptions) => Toast, + warning: (options: ToastOptions) => Toast, + info: (options: ToastOptions) => Toast, + error: (options: ToastOptions) => Toast, +}; + +export default toast; + +export interface ToastOptions { + message?: string; + position?: "center" | "west" | "east" | "south" | "south-west" | "south-east" | "north" | "north-west" | "north-east"; + timeout?: number; + el?: HTMLElement; + rounded?: boolean; + type?: "success" | "warning" | "info" | "error"; + debug?: boolean; + edge?: boolean; + icon?: boolean; + closeOnClick?: boolean; + elements?: HTMLElement[]; +} + +export interface Toast { + show(): void; + hide(): void; + destroy(): void; +} diff --git a/types/native-toast/native-toast-tests.ts b/types/native-toast/native-toast-tests.ts new file mode 100644 index 0000000000..73d6890549 --- /dev/null +++ b/types/native-toast/native-toast-tests.ts @@ -0,0 +1,20 @@ +import toast, { Toast, ToastOptions } from "native-toast"; + +let t: Toast; + +t = toast({ + message: "Team created", + position: "north-east", + timeout: 5000, + type: "success", +}); + +t.hide(); +t.show(); + +const o: ToastOptions = { + message: "test", + position: "west" +}; + +toast.success(o); diff --git a/types/native-toast/tsconfig.json b/types/native-toast/tsconfig.json new file mode 100644 index 0000000000..d36ee00fd9 --- /dev/null +++ b/types/native-toast/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "native-toast-tests.ts" + ] +} diff --git a/types/native-toast/tslint.json b/types/native-toast/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/native-toast/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/parity-pmr/parity-pmr-tests.ts b/types/parity-pmr/parity-pmr-tests.ts index 03bcc3534d..4fbb2b31b4 100644 --- a/types/parity-pmr/parity-pmr-tests.ts +++ b/types/parity-pmr/parity-pmr-tests.ts @@ -17,9 +17,7 @@ format({}); // Invalid sub type // $ExpectError -format({ - messageType: 1 -}); +format({ messageType: 1 }); // $ExpectType PMRMessage parse(buffer); diff --git a/types/parity-poe/parity-poe-tests.ts b/types/parity-poe/parity-poe-tests.ts index c5b50d5189..fb9c267572 100644 --- a/types/parity-poe/parity-poe-tests.ts +++ b/types/parity-poe/parity-poe-tests.ts @@ -21,9 +21,7 @@ formatInbound({}); // Invalid sub type // $ExpectError -formatInbound({ - messageType: 1 -}); +formatInbound({ messageType: 1 }); /** * parseInbound tests @@ -52,9 +50,7 @@ formatOutbound({}); // Invalid sub type // $ExpectError -formatOutbound({ - messageType: 1 -}); +formatOutbound({ messageType: 1 }); /** * parseOutbound tests 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