From 64a51e86db17b9b82324cf67572f7cb5524857ac Mon Sep 17 00:00:00 2001 From: HowardRichards Date: Thu, 30 Jan 2014 14:10:37 +0000 Subject: [PATCH 001/149] Added additional definitions to Valerie Added ModelValidation types --- valerie/valerie-tests.ts | 12 +++- valerie/valerie.d.ts | 150 +++++++++++++++++++++++++++++++++------ 2 files changed, 139 insertions(+), 23 deletions(-) diff --git a/valerie/valerie-tests.ts b/valerie/valerie-tests.ts index bf9ce7880..22adc7a13 100644 --- a/valerie/valerie-tests.ts +++ b/valerie/valerie-tests.ts @@ -285,4 +285,14 @@ function RuleTests() { .rule(() => { return anyValue; }) .end(); -} \ No newline at end of file +} + +function ModelValidation() { + + var model = {}; + + var validatedModel = valerie.validatableModel(model) + .validateAll() + .end(); + +} diff --git a/valerie/valerie.d.ts b/valerie/valerie.d.ts index 847e0a7a0..1140d0a94 100644 --- a/valerie/valerie.d.ts +++ b/valerie/valerie.d.ts @@ -7,7 +7,10 @@ /** * - * Extensions to KO functions to provide validation + * Extensions to KO functions to provide validation + * + * Version 1.1 - added missing methods to ModelValidationState + * */ interface KnockoutObservable { // starts validation for observable @@ -23,7 +26,6 @@ interface KnockoutObservableArray { validate(validationOptions?: Valerie.ValidationOptions): Valerie.PropertyValidationState>; } - interface KnockoutObservableArrayFunctions { /** * Creates and sets a model validation state on a Knockout observable array.
@@ -198,8 +200,6 @@ interface KnockoutBindingHandlers { visibleWhenValid: KnockoutBindingHandler; } - - // // root valerie namespace - static methods // @@ -208,12 +208,10 @@ declare var valerie: Valerie.Static; // additional types for Valerie (all inside this namespace) declare module Valerie { - // // Static methods on valerie namespace // interface Static { - /** * Maps a source model to a destination model, including only applicable properties * @param {Object|Array} sourceModel the source model @@ -263,10 +261,128 @@ declare module Valerie { // ctor new: (model: any, options?: ModelValidationStateOptions) => ModelValidationState; - addValidationStates(validationStateOrStates: any): void; - model: any; options?: ModelValidationStateOptions + + // methods + + /** + * Adds validation states to this validation state.
+ * [fluent] + * @name valerie.ModelValidationState#addValidationStates + * @fluent + * @param {object|array.} validationStateOrStates the validation states to add + * @return {valerie.ModelValidationState} + */ + addValidationStates(validationStateOrStates: any): ModelValidationState; + + /** + * Sets the value or function used to determine if the model is applicable.
+ * [fluent] + * @name valerie.ModelValidationState#applicable + * @fluent + * @param {boolean|function} [valueOrFunction = true] the value or function to use + * @return {valerie.ModelValidationState} + */ + applicable(valueOrFunction: any): ModelValidationState; + + /** + * Clears the static summary of validation states that are in a failure state.
+ * [fluent] + * @name valerie.ModelValidationState#clearSummary + * @fluent + * @param {boolean} [clearSubModelSummaries = false] whether to clear the static summaries for sub-models + * @return {valerie.ModelValidationState} + */ + clearSummary(valueOrFunction: any): ModelValidationState; + + /** + * Includes any validation failures for this model in a validation summary.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + includeInSummary(): ModelValidationState; + + /** + * Sets the value or function used to determine the name of the model.
+ * [fluent] + * @fluent + * @param {string|function} valueOrFunction the value or function to use + * @return {valerie.ModelValidationState} + */ + name(valueOrFunction: any): ModelValidationState; + + /** + * Removes validation states.
+ * [fluent] + * @fluent + * @param {object|array.} validationStateOrStates the validation states to remove + * @return {valerie.ModelValidationState} + */ + removeValidationStates(validationStateOrStates: any): ModelValidationState; + + /** + * Stops validating the given sub-model by adding the validation state that belongs to it. + * @param {*} validatableSubModel the sub - model to start validating + * @return {valerie.ModelValidationState } + */ + startValidatingSubModel(validatableSubModel: any): ModelValidationState; + + /** + * Stops validating the given sub-model by removing the validation state that belongs to it. + * @param {*} validatableSubModel the sub-model to stop validating + * @return {valerie.ModelValidationState} + */ + stopValidatingSubModel(validatableSubModel: any): ModelValidationState; + + /** + * Updates the static summary of validation states that are in a failure state.
+ * [fluent] + * @fluent + * @param {boolean} [updateSubModelSummaries = false] whether to update the static summaries for sub-models + * @return {valerie.ModelValidationState} + */ + updateSummary(updateSubModelSummaries: boolean): ModelValidationState; + + /** + * Adds the validation states for all the descendant properties and sub-models that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateAll(): ModelValidationState; + + /** + * Adds the validation states for all the descendant properties that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateAllProperties(): ModelValidationState; + + /** + * Adds the validation states for all the child properties that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateChildProperties(): ModelValidationState; + + /** + * Adds the validation states for all the child properties and sub-models that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateChildPropertiesAndSubModels(): ModelValidationState; + + + /** + * Ends a chain of fluent method calls on this model validation state. + * @return {function} the model the validation state is for + */ + end(): any; } // Construction options for a model validation state. @@ -282,7 +398,6 @@ declare module Valerie { // PropertyValidationState // interface PropertyValidationState { - // properties: // the observable or computed the validation state is for @@ -310,12 +425,12 @@ declare module Valerie { during(earliest: () => Date, latest: Date, options?: ValidationOptions): PropertyValidationState; // dateFN + date during(earliest: Date, latest: () => Date, options?: ValidationOptions): PropertyValidationState; // date + dateFN during(earliest: () => Date, latest: () => Date, options?: ValidationOptions): PropertyValidationState; // dateFN + dateFN - earliest(earliest: Date, options?: ValidationOptions): PropertyValidationState; // date value + earliest(earliest: Date, options?: ValidationOptions): PropertyValidationState; // date value earliest(earliest: () => Date, options?: ValidationOptions): PropertyValidationState; // date function email(): PropertyValidationState; entryFormat(format: string): PropertyValidationState; excludeFromSummary(): PropertyValidationState; - expression(regularExpression: RegExp, options?: ValidationOptions): PropertyValidationState; // regex + expression(regularExpression: RegExp, options?: ValidationOptions): PropertyValidationState; // regex expression(regularExpressionString: string, options?: ValidationOptions): PropertyValidationState; // regex string float(options?: ValidationOptions): PropertyValidationState; integer(options?: ValidationOptions): PropertyValidationState; @@ -377,7 +492,6 @@ declare module Valerie { touched(): boolean; // get touched state touched(value: boolean): boolean; // set touched state result(): ValidationResult; - } interface ValidationResult { @@ -390,7 +504,6 @@ declare module Valerie { //TODO: not added static members/methods createFailedResult(message: string): ValidationResult; - } interface IRule { @@ -411,7 +524,7 @@ declare module Valerie { } interface ValidatableModel { - name: (value:string) => PropertyValidationState; + name: (value: string) => PropertyValidationState; // return original observableArray end: () => T; @@ -438,7 +551,6 @@ declare module Valerie { // A helper for parsing and formatting numeric values. interface NumericHelper { - // Adds thousands separators to the given numeric string. addThousandsSeparator(numericString: string): string; @@ -468,13 +580,10 @@ declare module Valerie { // Unformats a numeric string; removes currency signs, thousands separators and normalises decimal separators. unformat(numericString: string): string; - } - interface ValidationState { - - // Finds and returns the validation states + // Finds and returns the validation states findIn(model: any, includeSubModels?: boolean, recurse?: boolean, @@ -486,15 +595,12 @@ declare module Valerie { // nforms if the given model, observable or computed has a validation state. has(modelOrObservableOrComputed: any): boolean; - // Sets the validation state for the given model, observable or computed. setFor(modelOrObservableOrComputed: any, state: IValidationState): void; - } } declare module Valerie.Rules { - /* Todo: add classes in valerie.rules namespace From 0737d4dccb2f285c50b77da91dcf526e6fcf5347 Mon Sep 17 00:00:00 2001 From: HowardRichards Date: Wed, 16 Apr 2014 14:30:07 +0100 Subject: [PATCH 002/149] Added more static valerie namespace definitions --- valerie/valerie-tests.ts | 37 +++++++++++ valerie/valerie.d.ts | 128 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 160 insertions(+), 5 deletions(-) diff --git a/valerie/valerie-tests.ts b/valerie/valerie-tests.ts index 22adc7a13..b33932e29 100644 --- a/valerie/valerie-tests.ts +++ b/valerie/valerie-tests.ts @@ -296,3 +296,40 @@ function ModelValidation() { .end(); } + +function UtilsStaticTests() { + + var t1 = valerie.utils.asArray(1); + var t2 = valerie.utils.asArray([1,2]); + + var t3 = valerie.utils.asFunction(1); + var t4 = valerie.utils.asFunction(() => { return 1; }); + + var t5 = valerie.utils.isArray([1, 2]); + var t5 = valerie.utils.isArrayOrObject(1); + var t6 = valerie.utils.isFunction("x"); + var t7 = valerie.utils.isMissing(null); + var t8 = valerie.utils.isObject({}); + var t9 = valerie.utils.isString("test"); + + var opts: Valerie.ValidationOptions = {}; // all values are optional + var t10 = valerie.utils.mergeOptions(opts, opts); +} + +function ValidationResultStaticTests() { + + var t1 = valerie.ValidationResult.passedInstance; + + var t2 = valerie.ValidationResult.createFailedResult("message"); + +} + +function ValidationStateStaticTests() { + + var t1 = valerie.validationState.findIn({}); + var t2 = valerie.validationState.getFor({}); + var t3 = valerie.validationState.has({}); + + var state = {}; + var t4 = valerie.validationState.setFor({}, state); +} diff --git a/valerie/valerie.d.ts b/valerie/valerie.d.ts index 1140d0a94..1514f3a4d 100644 --- a/valerie/valerie.d.ts +++ b/valerie/valerie.d.ts @@ -3,13 +3,13 @@ // Definitions by: Howard Richards // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// + /** * * Extensions to KO functions to provide validation * - * Version 1.1 - added missing methods to ModelValidationState + * Version 1.2 - added more static methods to valerie object * */ interface KnockoutObservable { @@ -246,9 +246,78 @@ declare module Valerie { // (value should be observable or computed) validatableProperty(value: T, options?: ValidationOptions): PropertyValidationState; + // Validation result class + ValidationResult: ValidationResultStatic; + // additional namespaces for static methods: + converters: ConvertersStatic; + + /* + //TODO: additional namespaces/statics not yet used + dom: DomStatic; + formatting: FormattingStatic; + koBindingsHelper: KoBindingsHelperStatic; + koExtras: KoExtrasStatic; + rules: RulesStatic; + */ + + utils: UtilsStatic; + validationState: ValidationState; + + } + + interface ValidationResultStatic { + + passedInstance: ValidationResult; + + // static method to create validatio failed message + createFailedResult(message: string): ValidationResult; + } + + // Contains converters, always singletons. + interface ConvertersStatic { + + //TODO: other converters to be added + + passThrough: Valerie.IConverter; + } + + + interface UtilsStatic { + + // Creates a function that returns the given value as an array of one item, or simply returns the given value if it is already an array. + asArray(value: any): any[]; + + // Creates a function that returns the given value, or simply returns the given value if it is already a function + asFunction(value: T): () => T; + asFunction(fn: () => T): () => T; + + // Tests whether the given value is an array + isArray(value: any): boolean; + + // Tests whether the given value is an array or object. + isArrayOrObject(value: any): boolean; + + // Tests whether the given value is a function. + isFunction(value: any): boolean; + + // Tests whether the given value is "missing".undefined, null, an empty string or an empty array are considered to be "missing". + isMissing(value: any): boolean; + + // Tests whether the given value is an object. + isObject(value: any): boolean; + + // Tests whether the give value is a string. + isString(value: any): boolean; + + //Merges the given default options with the given options. + // - either parameter can be omitted and a clone of the other parameter will be returned + // - the merge is shallow + // - array properties are shallow cloned + mergeOptions(defaultOptions: ValidationOptions, options): ValidationOptions; + } // callback interface (see mapModel above) @@ -296,6 +365,53 @@ declare module Valerie { */ clearSummary(valueOrFunction: any): ModelValidationState; + /*** + * Gets whether the model has failed validation. + * @return {boolean} + */ + failed(): boolean; + + /*** + * Gets the validation states that belong to the model that are in a failure state. + * @return {Valerie.IValidationState[]} + */ + failedStates(): Valerie.IValidationState[]; + + /*** + * Gets the name of the model. + * @return {string} + */ + getName(): string; + + isApplicable(): boolean; + message(): string; + passed(): boolean; + + /*** + * Gets or sets whether the computation that updates the validation result has been paused. + * @param {boolean} [value = false] true if the computation should be paused, false if the computation should not be paused + * @return {boolean} true if computation is paused, false otherwise + */ + paused(value: boolean): boolean; + + pending(): boolean; + + pendingStates(): IValidationState[]; + + refresh(): void; + + result(): ValidationResult; + + summary(): summaryItem[] + + /*** + * Gets or sets whether the model has been 'touched' by user action + */ + touched(value: boolean): boolean; + + + validationStates(): IValidationState[]; + /** * Includes any validation failures for this model in a validation summary.
* [fluent] @@ -501,9 +617,6 @@ declare module Valerie { pending: boolean; //true if the activity hasn't yet completed message: string; //a message from the activity new: (state: any, message?: string) => ValidationResult; - - //TODO: not added static members/methods - createFailedResult(message: string): ValidationResult; } interface IRule { @@ -598,6 +711,11 @@ declare module Valerie { // Sets the validation state for the given model, observable or computed. setFor(modelOrObservableOrComputed: any, state: IValidationState): void; } + + interface summaryItem { + name: string; + message: string; + } } declare module Valerie.Rules { From 439b1fdf0469b7488988318be9dbee6c71fa8ab7 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:11:26 -0700 Subject: [PATCH 003/149] rx.js renamed to rx. --- rx-lite.d.ts | 565 ++++++++++++++++++++++++++++++++++++++ rx.aggregates.d.ts | 61 ++++ rx.all.ts | 20 ++ rx.async-lite.d.ts | 65 +++++ rx.async-tests.ts | 88 ++++++ rx.async.d.ts | 43 +++ rx.backpressure-lite.d.ts | 49 ++++ rx.backpressure-tests.ts | 22 ++ rx.backpressure.d.ts | 11 + rx.binding-lite.d.ts | 72 +++++ rx.binding.d.ts | 11 + rx.coincidence-lite.d.ts | 34 +++ rx.coincidence.d.ts | 36 +++ rx.d.ts | 102 +++++++ rx.experimental.d.ts | 321 ++++++++++++++++++++++ rx.joinpatterns.d.ts | 60 ++++ rx.lite.d.ts | 50 ++++ rx.testing.d.ts | 62 +++++ rx.time-lite.d.ts | 62 +++++ rx.time.d.ts | 35 +++ rx.virtualtime.d.ts | 39 +++ 21 files changed, 1808 insertions(+) create mode 100644 rx-lite.d.ts create mode 100644 rx.aggregates.d.ts create mode 100644 rx.all.ts create mode 100644 rx.async-lite.d.ts create mode 100644 rx.async-tests.ts create mode 100644 rx.async.d.ts create mode 100644 rx.backpressure-lite.d.ts create mode 100644 rx.backpressure-tests.ts create mode 100644 rx.backpressure.d.ts create mode 100644 rx.binding-lite.d.ts create mode 100644 rx.binding.d.ts create mode 100644 rx.coincidence-lite.d.ts create mode 100644 rx.coincidence.d.ts create mode 100644 rx.d.ts create mode 100644 rx.experimental.d.ts create mode 100644 rx.joinpatterns.d.ts create mode 100644 rx.lite.d.ts create mode 100644 rx.testing.d.ts create mode 100644 rx.time-lite.d.ts create mode 100644 rx.time.d.ts create mode 100644 rx.virtualtime.d.ts diff --git a/rx-lite.d.ts b/rx-lite.d.ts new file mode 100644 index 000000000..c7a148137 --- /dev/null +++ b/rx-lite.d.ts @@ -0,0 +1,565 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.d.ts and rx.lite.d.ts +// Do not include the file separately. + +declare module Rx { + export module internals { + function isEqual(left: any, right: any): boolean; + function addRef(xs: Observable, r: { getDisposable(): IDisposable; }): Observable; + + // Priority Queue for Scheduling + export class PriorityQueue { + constructor(capacity: number); + + length: number; + + isHigherPriority(left: number, right: number): boolean; + percolate(index: number): void; + heapify(index: number): void; + peek(): ScheduledItem; + removeAt(index: number): void; + dequeue(): ScheduledItem; + enqueue(item: ScheduledItem): void; + remove(item: ScheduledItem): boolean; + + static count: number; + } + + export class ScheduledItem { + constructor(scheduler: IScheduler, state: any, action: (scheduler: IScheduler, state: any) => IDisposable, dueTime: TTime, comparer?: (x: TTime, y: TTime) => number); + + scheduler: IScheduler; + state: TTime; + action: (scheduler: IScheduler, state: any) => IDisposable; + dueTime: TTime; + comparer: (x: TTime, y: TTime) => number; + disposable: SingleAssignmentDisposable; + + invoke(): void; + compareTo(other: ScheduledItem): number; + isCancelled(): boolean; + invokeCore(): IDisposable; + } + } + + export module config { + export var Promise: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }; + } + + export module helpers { + function noop(): void; + function identity(value: T): T; + function defaultNow(): number; + function defaultComparer(left: any, right: any): boolean; + function defaultSubComparer(left: any, right: any): number; + function defaultKeySerializer(key: any): string; + function defaultError(err: any): void; + function isPromise(p: any): boolean; + function asArray(...args: T[]): T[]; + function not(value: any): boolean; + } + + export interface IDisposable { + dispose(): void; + } + + export class CompositeDisposable implements IDisposable { + constructor (...disposables: IDisposable[]); + constructor (disposables: IDisposable[]); + + isDisposed: boolean; + length: number; + + dispose(): void; + add(item: IDisposable): void; + remove(item: IDisposable): boolean; + clear(): void; + contains(item: IDisposable): boolean; + toArray(): IDisposable[]; + } + + export class Disposable implements IDisposable { + constructor(action: () => void); + + static create(action: () => void): IDisposable; + static empty: IDisposable; + + dispose(): void; + } + + // Single assignment + export class SingleAssignmentDisposable implements IDisposable { + constructor(); + + isDisposed: boolean; + current: IDisposable; + + dispose(): void ; + getDisposable(): IDisposable; + setDisposable(value: IDisposable): void ; + } + + // Multiple assignment disposable + export class SerialDisposable implements IDisposable { + constructor(); + + isDisposed: boolean; + + dispose(): void; + getDisposable(): IDisposable; + setDisposable(value: IDisposable): void; + } + + export class RefCountDisposable implements IDisposable { + constructor(disposable: IDisposable); + + dispose(): void; + + isDisposed: boolean; + getDisposable(): IDisposable; + } + + export interface IScheduler { + now(): number; + + schedule(action: () => void): IDisposable; + scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; + scheduleWithAbsoluteAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) =>IDisposable): IDisposable; + scheduleWithRelative(dueTime: number, action: () => void): IDisposable; + scheduleWithRelativeAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) =>IDisposable): IDisposable; + + scheduleRecursive(action: (action: () =>void ) =>void ): IDisposable; + scheduleRecursiveWithState(state: TState, action: (state: TState, action: (state: TState) =>void ) =>void ): IDisposable; + scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithAbsoluteAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) =>void ) =>void ): IDisposable; + scheduleRecursiveWithRelativeAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) =>void ) =>void ): IDisposable; + + schedulePeriodic(period: number, action: () => void): IDisposable; + schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; + } + + // Current Thread IScheduler + interface ICurrentThreadScheduler extends IScheduler { + scheduleRequired(): boolean; + } + + // Notifications + export class Notification { + accept(observer: IObserver): void; + accept(onNext: (value: T) => TResult, onError?: (exception: any) => TResult, onCompleted?: () => TResult): TResult; + toObservable(scheduler?: IScheduler): Observable; + hasValue: boolean; + equals(other: Notification): boolean; + kind: string; + value: T; + exception: any; + + static createOnNext(value: T): Notification; + static createOnError(exception: any): Notification; + static createOnCompleted(): Notification; + } + + /** + * Promise A+ + */ + export interface IPromise { + then(onFulfilled: (value: T) => IPromise, onRejected: (reason: any) => IPromise): IPromise; + then(onFulfilled: (value: T) => IPromise, onRejected?: (reason: any) => R): IPromise; + then(onFulfilled: (value: T) => R, onRejected: (reason: any) => IPromise): IPromise; + then(onFulfilled?: (value: T) => R, onRejected?: (reason: any) => R): IPromise; + } + + // Observer + export interface IObserver { + onNext(value: T): void; + onError(exception: any): void; + onCompleted(): void; + } + + export interface Observer extends IObserver { + toNotifier(): (notification: Notification) => void; + asObserver(): Observer; + } + + interface ObserverStatic { + create(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observer; + fromNotifier(handler: (notification: Notification) => void): Observer; + } + + export var Observer: ObserverStatic; + + export interface IObservable { + subscribe(observer: Observer): IDisposable; + subscribe(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; + } + + export interface Observable extends IObservable { + forEach(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; // alias for subscribe + toArray(): Observable; + + catch(handler: (exception: any) => Observable): Observable; + catchException(handler: (exception: any) => Observable): Observable; // alias for catch + catch(handler: (exception: any) => IPromise): Observable; + catchException(handler: (exception: any) => IPromise): Observable; // alias for catch + catch(second: Observable): Observable; + catchException(second: Observable): Observable; // alias for catch + combineLatest(second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + combineLatest(second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + combineLatest(second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; + combineLatest(souces: Observable[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; + combineLatest(souces: IPromise[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; + concat(...sources: Observable[]): Observable; + concat(...sources: IPromise[]): Observable; + concat(sources: Observable[]): Observable; + concat(sources: IPromise[]): Observable; + concatAll(): T; + concatObservable(): T; // alias for concatAll + concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat + concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat + concatMap(selector: (value: T, index: number) => Observable): Observable; // alias for selectConcat + concatMap(selector: (value: T, index: number) => IPromise): Observable; // alias for selectConcat + concatMap(sequence: Observable): Observable; // alias for selectConcat + merge(maxConcurrent: number): T; + merge(other: Observable): Observable; + merge(other: IPromise): Observable; + mergeAll(): T; + mergeObservable(): T; // alias for mergeAll + skipUntil(other: Observable): Observable; + skipUntil(other: IPromise): Observable; + switch(): T; + switchLatest(): T; // alias for switch + takeUntil(other: Observable): Observable; + takeUntil(other: IPromise): Observable; + zip(second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + zip(second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + zip(second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + zip(second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + zip(second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + zip(second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + zip(second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + zip(second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; + zip(second: Observable[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable; + zip(second: IPromise[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable; + + asObservable(): Observable; + dematerialize(): Observable; + distinctUntilChanged(skipParameter: boolean, comparer: (x: T, y: T) => boolean): Observable; + distinctUntilChanged(keySelector?: (value: T) => TValue, comparer?: (x: TValue, y: TValue) => boolean): Observable; + do(observer: Observer): Observable; + doAction(observer: Observer): Observable; // alias for do + do(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; + doAction(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; // alias for do + finally(action: () => void): Observable; + finallyAction(action: () => void): Observable; // alias for finally + ignoreElements(): Observable; + materialize(): Observable>; + repeat(repeatCount?: number): Observable; + retry(retryCount?: number): Observable; + scan(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; + scan(accumulator: (acc: T, value: T) => T): Observable; + skipLast(count: number): Observable; + startWith(...values: T[]): Observable; + startWith(scheduler: IScheduler, ...values: T[]): Observable; + takeLast(count: number, scheduler?: IScheduler): Observable; + takeLastBuffer(count: number): Observable; + + select(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; + map(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for select + selectMany(selector: (value: T) => Observable, resultSelector: (item: T, other: TOther) => TResult): Observable; + selectMany(selector: (value: T) => IPromise, resultSelector: (item: T, other: TOther) => TResult): Observable; + selectMany(selector: (value: T) => Observable): Observable; + selectMany(selector: (value: T) => IPromise): Observable; + selectMany(other: Observable): Observable; + selectMany(other: IPromise): Observable; + flatMap(selector: (value: T) => Observable, resultSelector: (item: T, other: TOther) => TResult): Observable; // alias for selectMany + flatMap(selector: (value: T) => IPromise, resultSelector: (item: T, other: TOther) => TResult): Observable; // alias for selectMany + flatMap(selector: (value: T) => Observable): Observable; // alias for selectMany + flatMap(selector: (value: T) => IPromise): Observable; // alias for selectMany + flatMap(other: Observable): Observable; // alias for selectMany + flatMap(other: IPromise): Observable; // alias for selectMany + + selectConcat(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; + selectConcat(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; + selectConcat(selector: (value: T, index: number) => Observable): Observable; + selectConcat(selector: (value: T, index: number) => IPromise): Observable; + selectConcat(sequence: Observable): Observable; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param [thisArg] Object to use as this when executing callback. + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + selectSwitch(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param [thisArg] Object to use as this when executing callback. + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + flatMapLatest(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param [thisArg] Object to use as this when executing callback. + * @since 2.2.28 + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + switchMap(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch + + skip(count: number): Observable; + skipWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + take(count: number, scheduler?: IScheduler): Observable; + takeWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + where(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + filter(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; // alias for where + + /** + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * @param promiseCtor The constructor of the promise. + * @returns An ES6 compatible promise with the last value from the observable sequence. + */ + toPromise>(promiseCtor: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): TPromise; }): TPromise; + /** + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns An ES6 compatible promise with the last value from the observable sequence. + */ + toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }): IPromise; + + // Experimental Flattening + + /** + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 + * @returns A exclusive observable with only the results that happen when subscribed. + */ + exclusive(): Observable; + + /** + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 + * @param selector Selector to invoke for every item in the current subscription. + * @param [thisArg] An optional context to invoke with the selector parameter. + * @returns {An exclusive observable with only the results that happen when subscribed. + */ + exclusiveMap(selector: (value: I, index: number, source: Observable) => R, thisArg?: any): Observable; + } + + interface ObservableStatic { + create(subscribe: (observer: Observer) => IDisposable): Observable; + create(subscribe: (observer: Observer) => () => void): Observable; + create(subscribe: (observer: Observer) => void): Observable; + createWithDisposable(subscribe: (observer: Observer) => IDisposable): Observable; + defer(observableFactory: () => Observable): Observable; + defer(observableFactory: () => IPromise): Observable; + empty(scheduler?: IScheduler): Observable; + fromArray(array: T[], scheduler?: IScheduler): Observable; + fromArray(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(function* () { yield 42; }); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param generator Generator to convert from. + * @param [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns The observable sequence whose elements are pulled from the given generator sequence. + */ + fromItreable(generator: () => { next(): { done: boolean; value?: T; }; }, scheduler?: IScheduler): Observable; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param iterable Iterable to convert from. + * @param [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns The observable sequence whose elements are pulled from the given generator sequence. + */ + fromItreable(iterable: {}, scheduler?: IScheduler): Observable; // todo: can't describe ES6 Iterable via TypeScript type system + generate(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable; + never(): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * + * @example + * var res = Rx.Observable.of(1, 2, 3); + * @since 2.2.28 + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + of(...values: T[]): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); + * @since 2.2.28 + * @param [scheduler] A scheduler to use for scheduling the arguments. + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + ofWithScheduler(scheduler?: IScheduler, ...values: T[]): Observable; + range(start: number, count: number, scheduler?: IScheduler): Observable; + repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; + return(value: T, scheduler?: IScheduler): Observable; + /** + * @since 2.2.28 + */ + just(value: T, scheduler?: IScheduler): Observable; // alias for return + returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return + throw(exception: Error, scheduler?: IScheduler): Observable; + throw(exception: any, scheduler?: IScheduler): Observable; + throwException(exception: Error, scheduler?: IScheduler): Observable; // alias for throw + throwException(exception: any, scheduler?: IScheduler): Observable; // alias for throw + + catch(sources: Observable[]): Observable; + catch(sources: IPromise[]): Observable; + catchException(sources: Observable[]): Observable; // alias for catch + catchException(sources: IPromise[]): Observable; // alias for catch + catch(...sources: Observable[]): Observable; + catch(...sources: IPromise[]): Observable; + catchException(...sources: Observable[]): Observable; // alias for catch + catchException(...sources: IPromise[]): Observable; // alias for catch + + combineLatest(first: Observable, second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: IPromise, second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + combineLatest(first: Observable, second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; + combineLatest(souces: Observable[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; + combineLatest(souces: IPromise[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; + + concat(...sources: Observable[]): Observable; + concat(...sources: IPromise[]): Observable; + concat(sources: Observable[]): Observable; + concat(sources: IPromise[]): Observable; + merge(...sources: Observable[]): Observable; + merge(...sources: IPromise[]): Observable; + merge(sources: Observable[]): Observable; + merge(sources: IPromise[]): Observable; + merge(scheduler: IScheduler, ...sources: Observable[]): Observable; + merge(scheduler: IScheduler, ...sources: IPromise[]): Observable; + merge(scheduler: IScheduler, sources: Observable[]): Observable; + merge(scheduler: IScheduler, sources: IPromise[]): Observable; + + zip(first: Observable, sources: Observable[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable; + zip(first: Observable, sources: IPromise[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable; + zip(source1: Observable, source2: Observable, resultSelector: (item1: T1, item2: T2) => TResult): Observable; + zip(source1: Observable, source2: IPromise, resultSelector: (item1: T1, item2: T2) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: Observable, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; + zip(source1: Observable, source2: IPromise, source3: Observable, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; + zip(source1: Observable, source2: IPromise, source3: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: Observable, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: IPromise, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: IPromise, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: IPromise, source3: Observable, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: IPromise, source3: Observable, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: IPromise, source3: IPromise, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: IPromise, source3: IPromise, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; + zip(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5) => TResult): Observable; + zipArray(...sources: Observable[]): Observable; + zipArray(sources: Observable[]): Observable; + + /** + * Converts a Promise to an Observable sequence + * @param promise An ES6 Compliant promise. + * @returns An Observable sequence which wraps the existing promise success and failure. + */ + fromPromise(promise: IPromise): Observable; + } + + export var Observable: ObservableStatic; + + interface ISubject extends Observable, Observer, IDisposable { + hasObservers(): boolean; + } + + export interface Subject extends ISubject { + } + + interface SubjectStatic { + new (): Subject; + create(observer?: Observer, observable?: Observable): ISubject; + } + + export var Subject: SubjectStatic; + + export interface AsyncSubject extends Subject { + } + + interface AsyncSubjectStatic { + new (): AsyncSubject; + } + + export var AsyncSubject: AsyncSubjectStatic; +} diff --git a/rx.aggregates.d.ts b/rx.aggregates.d.ts new file mode 100644 index 000000000..001d1b993 --- /dev/null +++ b/rx.aggregates.d.ts @@ -0,0 +1,61 @@ +// Type definitions for RxJS-Aggregates v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Rx { + export interface Observable { + finalValue(): Observable; + aggregate(accumulator: (acc: T, value: T) => T): Observable; + aggregate(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; + + reduce(accumulator: (acc: T, value: T) => T): Observable; + reduce(accumulator: (acc: TAcc, value: T) => TAcc, seed: TAcc): Observable; // TS0.9.5: won't work https://typescript.codeplex.com/discussions/471751 + + any(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + some(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; // alias for any + + isEmpty(): Observable; + all(predicate?: (value: T) => boolean, thisArg?: any): Observable; + every(predicate?: (value: T) => boolean, thisArg?: any): Observable; // alias for all + contains(value: T): Observable; + contains(value: TOther, comparer: (value1: T, value2: TOther) => boolean): Observable; + count(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + sum(keySelector?: (value: T, index: number, source: Observable) => number, thisArg?: any): Observable; + minBy(keySelector: (item: T) => TKey, comparer: (value1: TKey, value2: TKey) => number): Observable; + minBy(keySelector: (item: T) => number): Observable; + min(comparer?: (value1: T, value2: T) => number): Observable; + maxBy(keySelector: (item: T) => TKey, comparer: (value1: TKey, value2: TKey) => number): Observable; + maxBy(keySelector: (item: T) => number): Observable; + max(comparer?: (value1: T, value2: T) => number): Observable; + average(keySelector?: (value: T, index: number, source: Observable) => number, thisArg?: any): Observable; + + sequenceEqual(second: Observable, comparer: (value1: T, value2: TOther) => number): Observable; + sequenceEqual(second: IPromise, comparer: (value1: T, value2: TOther) => number): Observable; + sequenceEqual(second: Observable): Observable; + sequenceEqual(second: IPromise): Observable; + sequenceEqual(second: TOther[], comparer: (value1: T, value2: TOther) => number): Observable; + sequenceEqual(second: T[]): Observable; + + elementAt(index: number): Observable; + elementAtOrDefault(index: number, defaultValue?: T): Observable; + + single(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + singleOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; + + first(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + firstOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; + + last(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + lastOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; + + find(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + findIndex(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; + } +} + +declare module "rx.aggregates" { + export = Rx; +} \ No newline at end of file diff --git a/rx.all.ts b/rx.all.ts new file mode 100644 index 000000000..c546477b8 --- /dev/null +++ b/rx.all.ts @@ -0,0 +1,20 @@ +// Type definitions for RxJS-All v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +declare module "rx.all" { + export = Rx; +} \ No newline at end of file diff --git a/rx.async-lite.d.ts b/rx.async-lite.d.ts new file mode 100644 index 000000000..be13320c2 --- /dev/null +++ b/rx.async-lite.d.ts @@ -0,0 +1,65 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.async.d.ts and rx.lite.d.ts +// Do not include the file separately. + +/// + +declare module Rx { + interface ObservableStatic { + /** + * Invokes the asynchronous function, surfacing the result through an observable sequence. + * @param functionAsync Asynchronous function which returns a Promise to run. + * @returns An observable sequence exposing the function's result value, or an exception. + */ + startAsync(functionAsync: () => IPromise): Observable; + + fromCallback: { + // with single result callback without selector + (func: (callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; + (func: (arg1: T1, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + // with any callback with selector + (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): () => Observable; + (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2, arg3: T3) => Observable; + // with any callback without selector + (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; + (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + // with any function with selector + (func: Function, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (...args: any[]) => Observable; + // with any function without selector + (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; + }; + + fromNodeCallback: { + // with single result callback without selector + (func: (callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; + (func: (arg1: T1, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + // with any callback with selector + (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): () => Observable; + (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2, arg3: T3) => Observable; + // with any callback without selector + (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; + (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + // with any function with selector + (func: Function, scheduler: IScheduler, context: any, selector: (results: TC[]) => T): (...args: any[]) => Observable; + // with any function without selector + (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; + }; + + fromEvent(element: NodeList, eventName: string, selector?: (arguments: any[]) => T): Observable; + fromEvent(element: Node, eventName: string, selector?: (arguments: any[]) => T): Observable; + fromEventPattern(addHandler: (handler: Function) => void, removeHandler: (handler: Function) => void, selector?: (arguments: any[])=>T): Observable; + } +} diff --git a/rx.async-tests.ts b/rx.async-tests.ts new file mode 100644 index 000000000..9c3bce516 --- /dev/null +++ b/rx.async-tests.ts @@ -0,0 +1,88 @@ +// Tests for RxJS-Async TypeScript definitions +// Tests by Igor Oleinikov + +/// + +module Rx.Tests.Async { + + var obsNum: Rx.Observable; + var obsStr: Rx.Observable; + var sch: Rx.IScheduler; + + function start() { + obsNum = Rx.Observable.start(()=> 10, sch, obsStr); + obsNum = Rx.Observable.start(()=> 10, sch); + obsNum = Rx.Observable.start(()=> 10); + } + + function toAsync() { + obsNum = Rx.Observable.toAsync(()=> 1, sch)(); + obsNum = Rx.Observable.toAsync((a1: number)=> a1)(1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number)=> a1 + a2.toFixed(0))("", 1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date)=> a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean)=> a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); + } + + function fromCallback() { + // 0 arguments + var func0: (cb: (result: number)=> void)=> void; + obsNum = Rx.Observable.fromCallback(func0)(); + obsNum = Rx.Observable.fromCallback(func0, sch)(); + obsNum = Rx.Observable.fromCallback(func0, sch, obsStr)(); + obsNum = Rx.Observable.fromCallback(func0, sch, obsStr, (results: number[]) => results[0])(); + + // 1 argument + var func1: (a: string, cb: (result: number)=> void)=> number; + obsNum = Rx.Observable.fromCallback(func1)(""); + obsNum = Rx.Observable.fromCallback(func1, sch)(""); + obsNum = Rx.Observable.fromCallback(func1, sch, {})(""); + obsNum = Rx.Observable.fromCallback(func1, sch, {}, (results: number[]) => results[0])(""); + + // 2 arguments + var func2: (a: number, b: string, cb: (result: string) => number) => Date; + obsStr = Rx.Observable.fromCallback(func2)(1, ""); + obsStr = Rx.Observable.fromCallback(func2, sch)(1, ""); + obsStr = Rx.Observable.fromCallback(func2, sch, {})(1, ""); + obsStr = Rx.Observable.fromCallback(func2, sch, {}, (results: string[]) => results[0])(1, ""); + + // 3 arguments + var func3: (a: number, b: string, c: boolean, cb: (result: string) => number) => Date; + obsStr = Rx.Observable.fromCallback(func3)(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, sch)(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, sch, {})(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, sch, {}, (results: string[]) => results[0])(1, "", true); + + // multiple results + var func0m: (cb: (result1: number, result2: number, result3: number) => void) => void; + obsNum = Rx.Observable.fromCallback(func0m, sch, obsStr, (results: number[]) => results[0])(); + var func1m: (a: string, cb: (result1: number, result2: number, result3: number) => void) => void; + obsNum = Rx.Observable.fromCallback(func1m, sch, obsStr, (results: number[]) => results[0])(""); + var func2m: (a: string, b: number, cb: (result1: string, result2: string, result3: string) => void) => void; + obsStr = Rx.Observable.fromCallback(func2m, sch, obsStr, (results: string[]) => results[0])("", 10); + } + + function toPromise() { + var promiseImpl: { + new(resolver: (resolvePromise: (value: T)=> void, rejectPromise: (reason: any)=> void)=> void): Rx.IPromise; + }; + + Rx.config.Promise = promiseImpl; + + var p: IPromise = obsNum.toPromise(promiseImpl); + + p = obsNum.toPromise(); + + p = p.then(x=> x); + p = p.then(x=> p); + p = p.then(undefined, reason=> 10); + p = p.then(undefined, reason=> p); + + var ps: IPromise = p.then(undefined, reason=> "error"); + ps = p.then(x=> ""); + ps = p.then(x=> ps); + } + + function startAsync() { + var o: Rx.Observable = Rx.Observable.startAsync(() => >null); + } +} \ No newline at end of file diff --git a/rx.async.d.ts b/rx.async.d.ts new file mode 100644 index 000000000..9370c828b --- /dev/null +++ b/rx.async.d.ts @@ -0,0 +1,43 @@ +// Type definitions for RxJS-Async v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: zoetrope , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module Rx { + interface ObservableStatic { + start(func: () => T, scheduler?: IScheduler, context?: any): Observable; + + toAsync(func: () => TResult, scheduler?: IScheduler, context?: any): () => Observable; + toAsync(func: (arg1: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; + toAsync(func: (arg1?: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1) => Observable; + toAsync(func: (...args: T1[]) => TResult, scheduler?: IScheduler, context?: any): (...args: T1[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; + toAsync(func: (arg1: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2) => Observable; + toAsync(func: (arg1: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, ...args: T2[]) => Observable; + toAsync(func: (arg1?: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, ...args: T2[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3) => Observable; + toAsync(func: (arg1: T1, arg2: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; + } +} + +declare module "rx.async" { + export = Rx; +} \ No newline at end of file diff --git a/rx.backpressure-lite.d.ts b/rx.backpressure-lite.d.ts new file mode 100644 index 000000000..d1c244195 --- /dev/null +++ b/rx.backpressure-lite.d.ts @@ -0,0 +1,49 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.backpressure.d.ts and rx.lite.d.ts +// Do not include the file separately. + +/// + +declare module Rx { + export interface Observable { + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param pauser The observable sequence used to pause the underlying sequence. + * @returns The observable sequence which is paused based upon the pauser. + */ + pausable(pauser: Observable): Observable; + pausable(pauser?: ISubject): PausableObservable; + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param pauser The observable sequence used to pause the underlying sequence. + * @returns The observable sequence which is paused based upon the pauser. + */ + pausableBuffered(pauser?: ISubject): PausableObservable; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + */ + controlled(enableQueue?: boolean): ControlledObservable; + } + + export interface ControlledObservable extends Observable { + request(numberOfItems?: number): IDisposable; + } + + export interface PausableObservable extends Observable { + pause(): void; + resume(): void; + } +} diff --git a/rx.backpressure-tests.ts b/rx.backpressure-tests.ts new file mode 100644 index 000000000..f036a1dc3 --- /dev/null +++ b/rx.backpressure-tests.ts @@ -0,0 +1,22 @@ +// Tests for RxJS-BackPressure TypeScript definitions +// Tests by Igor Oleinikov + +/// +/// + +function testPausable() { + var o: Rx.Observable; + + var pauser = new Rx.Subject(); + + var p = o.pausable(pauser); + p = o.pausableBuffered(pauser); +} + +function testControlled() { + var o: Rx.Observable; + var c = o.controlled(); + + var d: Rx.IDisposable = c.request(); + d = c.request(5); +} diff --git a/rx.backpressure.d.ts b/rx.backpressure.d.ts new file mode 100644 index 000000000..9c5e8abd5 --- /dev/null +++ b/rx.backpressure.d.ts @@ -0,0 +1,11 @@ +// Type definitions for RxJS-BackPressure v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "rx.backpressure" { + export = Rx; +} \ No newline at end of file diff --git a/rx.binding-lite.d.ts b/rx.binding-lite.d.ts new file mode 100644 index 000000000..f896e260d --- /dev/null +++ b/rx.binding-lite.d.ts @@ -0,0 +1,72 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.binding.d.ts and rx.lite.d.ts +// Do not include the file separately. + +/// + +declare module Rx { + export interface BehaviorSubject extends Subject { + } + + interface BehaviorSubjectStatic { + new (initialValue: T): BehaviorSubject; + } + + export var BehaviorSubject: BehaviorSubjectStatic; + + export interface ReplaySubject extends Subject { + } + + interface ReplaySubjectStatic { + new (bufferSize?: number, window?: number, scheduler?: IScheduler): ReplaySubject; + } + + export var ReplaySubject: ReplaySubjectStatic; + + interface ConnectableObservable extends Observable { + connect(): IDisposable; + refCount(): Observable; + } + + interface ConnectableObservableStatic { + new (): ConnectableObservable; + } + + export var ConnectableObservable: ConnectableObservableStatic; + + export interface Observable { + multicast(subject: Observable): ConnectableObservable; + multicast(subjectSelector: () => ISubject, selector: (source: ConnectableObservable) => Observable): Observable; + publish(): ConnectableObservable; + publish(selector: (source: ConnectableObservable) => Observable): Observable; + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence. + * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * + * @example + * var res = source.share(); + * + * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + share(): Observable; + publishLast(): ConnectableObservable; + publishLast(selector: (source: ConnectableObservable) => Observable): Observable; + publishValue(initialValue: T): ConnectableObservable; + publishValue(selector: (source: ConnectableObservable) => Observable, initialValue: T): Observable; + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. + * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * + * @example + * var res = source.shareValue(42); + * + * @param initialValue Initial value received by observers upon subscription. + * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + shareValue(initialValue: T): Observable; + replay(selector?: boolean, bufferSize?: number, window?: number, scheduler?: IScheduler): ConnectableObservable; // hack to catch first omitted parameter + replay(selector: (source: ConnectableObservable) => Observable, bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; + shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; + } +} diff --git a/rx.binding.d.ts b/rx.binding.d.ts new file mode 100644 index 000000000..b93411a52 --- /dev/null +++ b/rx.binding.d.ts @@ -0,0 +1,11 @@ +// Type definitions for RxJS-Binding v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "rx.binding" { + export = Rx; +} \ No newline at end of file diff --git a/rx.coincidence-lite.d.ts b/rx.coincidence-lite.d.ts new file mode 100644 index 000000000..801e42168 --- /dev/null +++ b/rx.coincidence-lite.d.ts @@ -0,0 +1,34 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts +// Do not include the file separately. + +/// + +declare module Rx { + + interface Observable { + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns An observable that triggers on successive pairs of observations from the input observable as an array. + */ + pairwise(): Observable; + + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + partition(predicate: (value: T, index: number, source: Observable) => boolean, thisArg: any): Observable[]; + } +} diff --git a/rx.coincidence.d.ts b/rx.coincidence.d.ts new file mode 100644 index 000000000..87fa6a55b --- /dev/null +++ b/rx.coincidence.d.ts @@ -0,0 +1,36 @@ +// Type definitions for RxJS-Coincidence v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module Rx { + + interface Observable { + join( + right: Observable, + leftDurationSelector: (leftItem: T) => Observable, + rightDurationSelector: (rightItem: TRight) => Observable, + resultSelector: (leftItem: T, rightItem: TRight) => TResult): Observable; + + groupJoin( + right: Observable, + leftDurationSelector: (leftItem: T) => Observable, + rightDurationSelector: (rightItem: TRight) => Observable, + resultSelector: (leftItem: T, rightItem: Observable) => TResult): Observable; + + window(windowOpenings: Observable): Observable>; + window(windowClosingSelector: () => Observable): Observable>; + window(windowOpenings: Observable, windowClosingSelector: () => Observable): Observable>; + + buffer(bufferOpenings: Observable): Observable; + buffer(bufferClosingSelector: () => Observable): Observable; + buffer(bufferOpenings: Observable, bufferClosingSelector: () => Observable): Observable; + } +} + +declare module "rx.coincidence" { + export = Rx; +} \ No newline at end of file diff --git a/rx.d.ts b/rx.d.ts new file mode 100644 index 000000000..1f26a94a9 --- /dev/null +++ b/rx.d.ts @@ -0,0 +1,102 @@ +// Type definitions for RxJS v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: gsino , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Rx { + export interface IScheduler { + catch(handler: (exception: any) => boolean): IScheduler; + catchException(handler: (exception: any) => boolean): IScheduler; + } + + export class Scheduler implements IScheduler { + constructor( + now: () => number, + schedule: (state: any, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, + scheduleRelative: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, + scheduleAbsolute: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable); + + static normalize(timeSpan: number): number; + + static immediate: IScheduler; + static currentThread: ICurrentThreadScheduler; + static timeout: IScheduler; + + now(): number; + catch(handler: (exception: any) => boolean): IScheduler; + catchException(handler: (exception: any) => boolean): IScheduler; + + schedule(action: () => void): IDisposable; + scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; + scheduleWithAbsoluteAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + scheduleWithRelative(dueTime: number, action: () => void): IDisposable; + scheduleWithRelativeAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + + scheduleRecursive(action: (action: () => void) => void): IDisposable; + scheduleRecursiveWithState(state: TState, action: (state: TState, action: (state: TState) => void) => void): IDisposable; + scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithAbsoluteAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithRelativeAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; + + schedulePeriodic(period: number, action: () => void): IDisposable; + schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; + } + + // Observer + export interface Observer { + checked(): Observer; + } + + interface ObserverStatic { + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param scheduler Scheduler to schedule observer messages on. + * @returns Observer whose messages are scheduled on the given scheduler. + */ + notifyOn(scheduler: IScheduler): Observer; + } + + export interface Observable { + observeOn(scheduler: IScheduler): Observable; + subscribeOn(scheduler: IScheduler): Observable; + + amb(rightSource: Observable): Observable; + amb(rightSource: IPromise): Observable; + onErrorResumeNext(second: Observable): Observable; + onErrorResumeNext(second: IPromise): Observable; + bufferWithCount(count: number, skip?: number): Observable; + windowWithCount(count: number, skip?: number): Observable>; + defaultIfEmpty(defaultValue?: T): Observable; + distinct(skipParameter: boolean, valueSerializer: (value: T) => string): Observable; + distinct(keySelector?: (value: T) => TKey, keySerializer?: (key: TKey) => string): Observable; + groupBy(keySelector: (value: T) => TKey, skipElementSelector?: boolean, keySerializer?: (key: TKey) => string): Observable>; + groupBy(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, keySerializer?: (key: TKey) => string): Observable>; + groupByUntil(keySelector: (value: T) => TKey, skipElementSelector: boolean, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; + groupByUntil(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; + } + + interface ObservableStatic { + using(resourceFactory: () => TResource, observableFactory: (resource: TResource) => Observable): Observable; + amb(...sources: Observable[]): Observable; + amb(...sources: IPromise[]): Observable; + amb(sources: Observable[]): Observable; + amb(sources: IPromise[]): Observable; + onErrorResumeNext(...sources: Observable[]): Observable; + onErrorResumeNext(...sources: IPromise[]): Observable; + onErrorResumeNext(sources: Observable[]): Observable; + onErrorResumeNext(sources: IPromise[]): Observable; + } + + interface GroupedObservable extends Observable { + key: TKey; + underlyingObservable: Observable; + } +} + +declare module "rx" { + export = Rx +} diff --git a/rx.experimental.d.ts b/rx.experimental.d.ts new file mode 100644 index 000000000..60aec86e1 --- /dev/null +++ b/rx.experimental.d.ts @@ -0,0 +1,321 @@ +// Type definitions for RxJS-Experimental v2.2.28 +// Project: https://github.com/Reactive-Extensions/RxJS/ +// Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Rx { + + interface Observable { + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + let(selector: (source: Observable) => Observable): Observable; + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + letBind(selector: (source: Observable) => Observable): Observable; + + /** + * Repeats source as long as condition holds emulating a do while loop. + * @param condition The condition which determines if the source will be repeated. + * @returns An observable sequence which is repeated as long as the condition holds. + */ + doWhile(condition: () => boolean): Observable; + + /** + * Expands an observable sequence by recursively invoking selector. + * + * @param selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. + * @param [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. + * @returns An observable sequence containing all the elements produced by the recursive expansion. + */ + expand(selector: (item: T) => Observable, scheduler?: IScheduler): Observable; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param second Second observable sequence or promise. + * @param resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + forkJoin(second: Observable, resultSelector: (left: T, right: TSecond) => TResult): Observable; + forkJoin(second: IPromise, resultSelector: (left: T, right: TSecond) => TResult): Observable; + + /** + * Comonadic bind operator. + * @param selector A transform function to apply to each element. + * @param [scheduler] Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns An observable sequence which results from the comonadic bind operation. + */ + manySelect(selector: (item: Observable, index: number, source: Observable) => TResult, scheduler?: IScheduler): Observable; + } + + interface ObservableStatic { + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, elseSource: Observable): Observable; + if(condition: () => boolean, thenSource: Observable, elseSource: IPromise): Observable; + if(condition: () => boolean, thenSource: IPromise, elseSource: Observable): Observable; + if(condition: () => boolean, thenSource: IPromise, elseSource: IPromise): Observable; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, scheduler?: IScheduler): Observable; + if(condition: () => boolean, thenSource: IPromise, scheduler?: IScheduler): Observable; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, elseSource: Observable): Observable; + ifThen(condition: () => boolean, thenSource: Observable, elseSource: IPromise): Observable; + ifThen(condition: () => boolean, thenSource: IPromise, elseSource: Observable): Observable; + ifThen(condition: () => boolean, thenSource: IPromise, elseSource: IPromise): Observable; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, scheduler?: IScheduler): Observable; + ifThen(condition: () => boolean, thenSource: IPromise, scheduler?: IScheduler): Observable; + + /** + * Concatenates the observable sequences obtained by running the specified result selector for each element in source. + * There is an alias for this method called 'forIn' for browsers (sources: T[], resultSelector: (item: T) => Observable): Observable; + + /** + * Concatenates the observable sequences obtained by running the specified result selector for each element in source. + * There is an alias for this method called 'forIn' for browsers (sources: T[], resultSelector: (item: T) => Observable): Observable; + + /** + * Repeats source as long as condition holds emulating a while loop. + * There is an alias for this method called 'whileDo' for browsers (condition: () => boolean, source: Observable): Observable; + while(condition: () => boolean, source: IPromise): Observable; + + /** + * Repeats source as long as condition holds emulating a while loop. + * There is an alias for this method called 'whileDo' for browsers (condition: () => boolean, source: Observable): Observable; + whileDo(condition: () => boolean, source: IPromise): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, elseSource: Observable): Observable; + case(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: Observable): Observable; + case(selector: () => string, sources: { [key: string]: Observable; }, elseSource: IPromise): Observable; + case(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: IPromise): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, scheduler?: IScheduler): Observable; + case(selector: () => string, sources: { [key: string]: IPromise; }, scheduler?: IScheduler): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, elseSource: Observable): Observable; + case(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: Observable): Observable; + case(selector: () => number, sources: { [key: number]: Observable; }, elseSource: IPromise): Observable; + case(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: IPromise): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, scheduler?: IScheduler): Observable; + case(selector: () => number, sources: { [key: number]: IPromise; }, scheduler?: IScheduler): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, elseSource: Observable): Observable; + switchCase(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: Observable): Observable; + switchCase(selector: () => string, sources: { [key: string]: Observable; }, elseSource: IPromise): Observable; + switchCase(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: IPromise): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, scheduler?: IScheduler): Observable; + switchCase(selector: () => string, sources: { [key: string]: IPromise; }, scheduler?: IScheduler): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, elseSource: Observable): Observable; + switchCase(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: Observable): Observable; + switchCase(selector: () => number, sources: { [key: number]: Observable; }, elseSource: IPromise): Observable; + switchCase(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: IPromise): Observable; + + /** + * Uses selector to determine which source in sources to use. + * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, scheduler?: IScheduler): Observable; + switchCase(selector: () => number, sources: { [key: number]: IPromise; }, scheduler?: IScheduler): Observable; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * res = Rx.Observable.forkJoin([obs1, obs2]); + * @param sources Array of source sequences or promises. + * @returns An observable sequence with an array collecting the last elements of all the input sequences. + */ + forkJoin(sources: Observable[]): Observable; + forkJoin(sources: IPromise[]): Observable; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @param args Source sequences or promises. + * @returns An observable sequence with an array collecting the last elements of all the input sequences. + */ + forkJoin(...args: Observable[]): Observable; + forkJoin(...args: IPromise[]): Observable; + } +} + +declare module "rx.experimental" { + export = Rx; +} \ No newline at end of file diff --git a/rx.joinpatterns.d.ts b/rx.joinpatterns.d.ts new file mode 100644 index 000000000..929c66a6f --- /dev/null +++ b/rx.joinpatterns.d.ts @@ -0,0 +1,60 @@ +// Type definitions for RxJS-Join v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Rx { + + interface Pattern1 { + and(other: Observable): Pattern2; + then(selector: (item1: T1) => TR): Plan; + } + interface Pattern2 { + and(other: Observable): Pattern3; + then(selector: (item1: T1, item2: T2) => TR): Plan; + } + interface Pattern3 { + and(other: Observable): Pattern4; + then(selector: (item1: T1, item2: T2, item3: T3) => TR): Plan; + } + interface Pattern4 { + and(other: Observable): Pattern5; + then(selector: (item1: T1, item2: T2, item3: T3, item4: T4) => TR): Plan; + } + interface Pattern5 { + and(other: Observable): Pattern6; + then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5) => TR): Plan; + } + interface Pattern6 { + and(other: Observable): Pattern7; + then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6) => TR): Plan; + } + interface Pattern7 { + and(other: Observable): Pattern8; + then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6, item7: T7) => TR): Plan; + } + interface Pattern8 { + and(other: Observable): Pattern9; + then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6, item7: T7, item8: T8) => TR): Plan; + } + interface Pattern9 { + then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6, item7: T7, item8: T8, item9: T9) => TR): Plan; + } + + interface Plan { } + + interface Observable { + and(other: Observable): Pattern2; + then(selector: (item1: T) => TR): Plan; + } + + interface ObservableStatic { + when(plan: Plan): Observable; + } +} + +declare module "rx.joinpatterns" { + export = Rx; +} \ No newline at end of file diff --git a/rx.lite.d.ts b/rx.lite.d.ts new file mode 100644 index 000000000..046ef527d --- /dev/null +++ b/rx.lite.d.ts @@ -0,0 +1,50 @@ +// Type definitions for RxJS-Lite v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: gsino , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +/// +/// +/// + +declare module Rx { + export class Scheduler implements IScheduler { + constructor( + now: () => number, + schedule: (state: any, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, + scheduleRelative: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, + scheduleAbsolute: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable); + + static normalize(timeSpan: number): number; + + static immediate: IScheduler; + static currentThread: ICurrentThreadScheduler; + static timeout: IScheduler; + + now(): number; + + schedule(action: () => void): IDisposable; + scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; + scheduleWithAbsoluteAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + scheduleWithRelative(dueTime: number, action: () => void): IDisposable; + scheduleWithRelativeAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + + scheduleRecursive(action: (action: () => void) => void): IDisposable; + scheduleRecursiveWithState(state: TState, action: (state: TState, action: (state: TState) => void) => void): IDisposable; + scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithAbsoluteAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; + scheduleRecursiveWithRelativeAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; + + schedulePeriodic(period: number, action: () => void): IDisposable; + schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; + } +} + +declare module "rx.lite" { + export = Rx; +} \ No newline at end of file diff --git a/rx.testing.d.ts b/rx.testing.d.ts new file mode 100644 index 000000000..0adc83e50 --- /dev/null +++ b/rx.testing.d.ts @@ -0,0 +1,62 @@ +// Type definitions for RxJS-Testing v2.2.28 +// Project: https://github.com/Reactive-Extensions/RxJS/ +// Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module Rx { + export class TestScheduler extends VirtualTimeScheduler { + constructor(); + + createColdObservable(...records: Recorded[]): Observable; + createHotObservable(...records: Recorded[]): Observable; + createObserver(): MockObserver; + + startWithTiming(create: () => Observable, createdAt: number, subscribedAt: number, disposedAt: number): MockObserver; + startWithDispose(create: () => Observable, disposedAt: number): MockObserver; + startWithCreate(create: () => Observable): MockObserver; + } + + export class Recorded { + constructor(time: number, value: any, equalityComparer?: (x: any, y: any) => boolean); + equals(other: Recorded): boolean; + toString(): string; + time: number; + value: any; + } + + export var ReactiveTest: { + created: number; + subscribed: number; + disposed: number; + + onNext(ticks: number, value: any): Recorded; + onNext(ticks: number, predicate: (value: any) => boolean): Recorded; + onError(ticks: number, exception: any): Recorded; + onError(ticks: number, predicate: (exception: any) => boolean): Recorded; + onCompleted(ticks: number): Recorded; + + subscribe(subscribeAt: number, unsubscribeAt?: number): Subscription; + }; + + export class Subscription { + constructor(subscribeAt: number, unsubscribeAt?: number); + equals(other: Subscription): boolean; + } + + export interface MockObserver extends Observer { + messages: Recorded[]; + } + + interface MockObserverStatic extends ObserverStatic { + new (scheduler: IScheduler): MockObserver; + } + + export var MockObserver: MockObserverStatic; +} + +declare module "rx.testing" { + export = Rx; +} \ No newline at end of file diff --git a/rx.time-lite.d.ts b/rx.time-lite.d.ts new file mode 100644 index 000000000..a5b102827 --- /dev/null +++ b/rx.time-lite.d.ts @@ -0,0 +1,62 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts +// Do not include the file separately. + +/// + +declare module Rx { + export interface TimeInterval { + value: T; + interval: number; + } + + export interface Timestamp { + value: T; + timestamp: number; + } + + export interface Observable { + delay(dueTime: number, scheduler?: IScheduler): Observable; + throttle(dueTime: number, scheduler?: IScheduler): Observable; + timeInterval(scheduler?: IScheduler): Observable>; + timestamp(scheduler?: IScheduler): Observable>; + sample(interval: number, scheduler?: IScheduler): Observable; + sample(sampler: Observable, scheduler?: IScheduler): Observable; + timeout(dueTime: Date, other?: Observable, scheduler?: IScheduler): Observable; + timeout(dueTime: number, other?: Observable, scheduler?: IScheduler): Observable; + + delaySubscription(dueTime: number, scheduler?: IScheduler): Observable; + delayWithSelector(delayDurationSelector: (item: T) => number): Observable; + delayWithSelector(subscriptionDelay: number, delayDurationSelector: (item: T) => number): Observable; + + timeoutWithSelector(firstTimeout: Observable, timeoutdurationSelector?: (item: T) => Observable, other?: Observable): Observable; + throttleWithSelector(throttleDurationSelector: (item: T) => Observable): Observable; + + skipLastWithTime(duration: number, scheduler?: IScheduler): Observable; + takeLastWithTime(duration: number, timerScheduler?: IScheduler, loopScheduler?: IScheduler): Observable; + + takeLastBufferWithTime(duration: number, scheduler?: IScheduler): Observable; + takeWithTime(duration: number, scheduler?: IScheduler): Observable; + skipWithTime(duration: number, scheduler?: IScheduler): Observable; + + skipUntilWithTime(startTime: Date, scheduler?: IScheduler): Observable; + skipUntilWithTime(duration: number, scheduler?: IScheduler): Observable; + takeUntilWithTime(endTime: Date, scheduler?: IScheduler): Observable; + takeUntilWithTime(duration: number, scheduler?: IScheduler): Observable; + } + + interface ObservableStatic { + interval(period: number, scheduler?: IScheduler): Observable; + interval(dutTime: number, period: number, scheduler?: IScheduler): Observable; + timer(dueTime: number, period: number, scheduler: IScheduler): Observable; + timer(dueTime: number, scheduler: IScheduler): Observable; + generateWithRelativeTime( + initialState: TState, + condition: (state: TState) => boolean, + iterate: (state: TState) => TState, + resultSelector: (state: TState) => TResult, + timeSelector: (state: TState) => number, + scheduler?: IScheduler): Observable; + } +} diff --git a/rx.time.d.ts b/rx.time.d.ts new file mode 100644 index 000000000..6efd7d9cf --- /dev/null +++ b/rx.time.d.ts @@ -0,0 +1,35 @@ +// Type definitions for RxJS-Time v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module Rx { + export interface Observable { + windowWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable>; + windowWithTime(timeSpan: number, scheduler?: IScheduler): Observable>; + windowWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable>; + bufferWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable; + bufferWithTime(timeSpan: number, scheduler?: IScheduler): Observable; + bufferWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable; + } + + interface ObservableStatic { + timer(dueTime: Date, period: number, scheduler: IScheduler): Observable; + timer(dueTime: Date, scheduler: IScheduler): Observable; + + generateWithAbsoluteTime( + initialState: TState, + condition: (state: TState) => boolean, + iterate: (state: TState) => TState, + resultSelector: (state: TState) => TResult, + timeSelector: (state: TState) => Date, + scheduler?: IScheduler): Observable; + } +} + +declare module "rx.time" { + export = Rx; +} \ No newline at end of file diff --git a/rx.virtualtime.d.ts b/rx.virtualtime.d.ts new file mode 100644 index 000000000..50a1bb39b --- /dev/null +++ b/rx.virtualtime.d.ts @@ -0,0 +1,39 @@ +// Type definitions for RxJS-VirtualTime v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: gsino , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Rx { + // Virtual IScheduler + export /*abstract*/ class VirtualTimeScheduler extends Scheduler { + constructor(initialClock: TAbsolute, comparer: (first: TAbsolute, second: TAbsolute) => number); + + advanceBy(time: TRelative): void; + advanceTo(time: TAbsolute): void; + scheduleAbsolute(dueTime: TAbsolute, action: () => void): IDisposable; + scheduleAbsoluteWithState(state: TState, dueTime: TAbsolute, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + scheduleRelative(dueTime: TRelative, action: () => void): IDisposable; + scheduleRelativeWithState(state: TState, dueTime: TRelative, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; + sleep(time: TRelative): void; + start(): IDisposable; + stop(): void; + + isEnabled: boolean; + + /* protected abstract */ add(from: TAbsolute, by: TRelative): TAbsolute; + /* protected abstract */ toDateTimeOffset(duetime: TAbsolute): number; + /* protected abstract */ toRelative(duetime: number): TRelative; + + /* protected */ getNext(): internals.ScheduledItem; + } + + export class HistoricalScheduler extends VirtualTimeScheduler { + constructor(initialClock: number, comparer: (first: number, second: number) => number); + } +} + +declare module "rx.virtualtime" { + export = Rx; +} \ No newline at end of file From 3854edf9c3d5172c6f5f70f783218543be6892fb Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 10:03:38 -0700 Subject: [PATCH 004/149] Added few helpers functions. --- rx/rx-lite.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rx/rx-lite.d.ts b/rx/rx-lite.d.ts index c7a148137..eea3c55ce 100644 --- a/rx/rx-lite.d.ts +++ b/rx/rx-lite.d.ts @@ -49,6 +49,8 @@ declare module Rx { export module helpers { function noop(): void; + function notDefined(value: any): boolean; + function isScheduler(value: any): boolean; function identity(value: T): T; function defaultNow(): number; function defaultComparer(left: any, right: any): boolean; From f9155131802b5062676acf94164e1f3c04e3c6c2 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 10:41:20 -0700 Subject: [PATCH 005/149] Removed rx files before merging. --- rx/rx-lite.d.ts | 567 ----------------------------------- rx/rx.aggregates.d.ts | 61 ---- rx/rx.all.ts | 20 -- rx/rx.async-lite.d.ts | 65 ---- rx/rx.async-tests.ts | 88 ------ rx/rx.async.d.ts | 43 --- rx/rx.backpressure-lite.d.ts | 49 --- rx/rx.backpressure-tests.ts | 22 -- rx/rx.backpressure.d.ts | 11 - rx/rx.binding-lite.d.ts | 72 ----- rx/rx.binding.d.ts | 11 - rx/rx.coincidence-lite.d.ts | 34 --- rx/rx.coincidence.d.ts | 36 --- rx/rx.d.ts | 102 ------- rx/rx.experimental.d.ts | 321 -------------------- rx/rx.joinpatterns.d.ts | 60 ---- rx/rx.lite.d.ts | 50 --- rx/rx.testing.d.ts | 62 ---- rx/rx.time-lite.d.ts | 62 ---- rx/rx.time.d.ts | 35 --- rx/rx.virtualtime.d.ts | 39 --- 21 files changed, 1810 deletions(-) delete mode 100644 rx/rx-lite.d.ts delete mode 100644 rx/rx.aggregates.d.ts delete mode 100644 rx/rx.all.ts delete mode 100644 rx/rx.async-lite.d.ts delete mode 100644 rx/rx.async-tests.ts delete mode 100644 rx/rx.async.d.ts delete mode 100644 rx/rx.backpressure-lite.d.ts delete mode 100644 rx/rx.backpressure-tests.ts delete mode 100644 rx/rx.backpressure.d.ts delete mode 100644 rx/rx.binding-lite.d.ts delete mode 100644 rx/rx.binding.d.ts delete mode 100644 rx/rx.coincidence-lite.d.ts delete mode 100644 rx/rx.coincidence.d.ts delete mode 100644 rx/rx.d.ts delete mode 100644 rx/rx.experimental.d.ts delete mode 100644 rx/rx.joinpatterns.d.ts delete mode 100644 rx/rx.lite.d.ts delete mode 100644 rx/rx.testing.d.ts delete mode 100644 rx/rx.time-lite.d.ts delete mode 100644 rx/rx.time.d.ts delete mode 100644 rx/rx.virtualtime.d.ts diff --git a/rx/rx-lite.d.ts b/rx/rx-lite.d.ts deleted file mode 100644 index eea3c55ce..000000000 --- a/rx/rx-lite.d.ts +++ /dev/null @@ -1,567 +0,0 @@ -// DefinitelyTyped: partial - -// This file contains common part of defintions for rx.d.ts and rx.lite.d.ts -// Do not include the file separately. - -declare module Rx { - export module internals { - function isEqual(left: any, right: any): boolean; - function addRef(xs: Observable, r: { getDisposable(): IDisposable; }): Observable; - - // Priority Queue for Scheduling - export class PriorityQueue { - constructor(capacity: number); - - length: number; - - isHigherPriority(left: number, right: number): boolean; - percolate(index: number): void; - heapify(index: number): void; - peek(): ScheduledItem; - removeAt(index: number): void; - dequeue(): ScheduledItem; - enqueue(item: ScheduledItem): void; - remove(item: ScheduledItem): boolean; - - static count: number; - } - - export class ScheduledItem { - constructor(scheduler: IScheduler, state: any, action: (scheduler: IScheduler, state: any) => IDisposable, dueTime: TTime, comparer?: (x: TTime, y: TTime) => number); - - scheduler: IScheduler; - state: TTime; - action: (scheduler: IScheduler, state: any) => IDisposable; - dueTime: TTime; - comparer: (x: TTime, y: TTime) => number; - disposable: SingleAssignmentDisposable; - - invoke(): void; - compareTo(other: ScheduledItem): number; - isCancelled(): boolean; - invokeCore(): IDisposable; - } - } - - export module config { - export var Promise: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }; - } - - export module helpers { - function noop(): void; - function notDefined(value: any): boolean; - function isScheduler(value: any): boolean; - function identity(value: T): T; - function defaultNow(): number; - function defaultComparer(left: any, right: any): boolean; - function defaultSubComparer(left: any, right: any): number; - function defaultKeySerializer(key: any): string; - function defaultError(err: any): void; - function isPromise(p: any): boolean; - function asArray(...args: T[]): T[]; - function not(value: any): boolean; - } - - export interface IDisposable { - dispose(): void; - } - - export class CompositeDisposable implements IDisposable { - constructor (...disposables: IDisposable[]); - constructor (disposables: IDisposable[]); - - isDisposed: boolean; - length: number; - - dispose(): void; - add(item: IDisposable): void; - remove(item: IDisposable): boolean; - clear(): void; - contains(item: IDisposable): boolean; - toArray(): IDisposable[]; - } - - export class Disposable implements IDisposable { - constructor(action: () => void); - - static create(action: () => void): IDisposable; - static empty: IDisposable; - - dispose(): void; - } - - // Single assignment - export class SingleAssignmentDisposable implements IDisposable { - constructor(); - - isDisposed: boolean; - current: IDisposable; - - dispose(): void ; - getDisposable(): IDisposable; - setDisposable(value: IDisposable): void ; - } - - // Multiple assignment disposable - export class SerialDisposable implements IDisposable { - constructor(); - - isDisposed: boolean; - - dispose(): void; - getDisposable(): IDisposable; - setDisposable(value: IDisposable): void; - } - - export class RefCountDisposable implements IDisposable { - constructor(disposable: IDisposable); - - dispose(): void; - - isDisposed: boolean; - getDisposable(): IDisposable; - } - - export interface IScheduler { - now(): number; - - schedule(action: () => void): IDisposable; - scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; - scheduleWithAbsoluteAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) =>IDisposable): IDisposable; - scheduleWithRelative(dueTime: number, action: () => void): IDisposable; - scheduleWithRelativeAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) =>IDisposable): IDisposable; - - scheduleRecursive(action: (action: () =>void ) =>void ): IDisposable; - scheduleRecursiveWithState(state: TState, action: (state: TState, action: (state: TState) =>void ) =>void ): IDisposable; - scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithAbsoluteAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) =>void ) =>void ): IDisposable; - scheduleRecursiveWithRelativeAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) =>void ) =>void ): IDisposable; - - schedulePeriodic(period: number, action: () => void): IDisposable; - schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; - } - - // Current Thread IScheduler - interface ICurrentThreadScheduler extends IScheduler { - scheduleRequired(): boolean; - } - - // Notifications - export class Notification { - accept(observer: IObserver): void; - accept(onNext: (value: T) => TResult, onError?: (exception: any) => TResult, onCompleted?: () => TResult): TResult; - toObservable(scheduler?: IScheduler): Observable; - hasValue: boolean; - equals(other: Notification): boolean; - kind: string; - value: T; - exception: any; - - static createOnNext(value: T): Notification; - static createOnError(exception: any): Notification; - static createOnCompleted(): Notification; - } - - /** - * Promise A+ - */ - export interface IPromise { - then(onFulfilled: (value: T) => IPromise, onRejected: (reason: any) => IPromise): IPromise; - then(onFulfilled: (value: T) => IPromise, onRejected?: (reason: any) => R): IPromise; - then(onFulfilled: (value: T) => R, onRejected: (reason: any) => IPromise): IPromise; - then(onFulfilled?: (value: T) => R, onRejected?: (reason: any) => R): IPromise; - } - - // Observer - export interface IObserver { - onNext(value: T): void; - onError(exception: any): void; - onCompleted(): void; - } - - export interface Observer extends IObserver { - toNotifier(): (notification: Notification) => void; - asObserver(): Observer; - } - - interface ObserverStatic { - create(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observer; - fromNotifier(handler: (notification: Notification) => void): Observer; - } - - export var Observer: ObserverStatic; - - export interface IObservable { - subscribe(observer: Observer): IDisposable; - subscribe(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; - } - - export interface Observable extends IObservable { - forEach(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; // alias for subscribe - toArray(): Observable; - - catch(handler: (exception: any) => Observable): Observable; - catchException(handler: (exception: any) => Observable): Observable; // alias for catch - catch(handler: (exception: any) => IPromise): Observable; - catchException(handler: (exception: any) => IPromise): Observable; // alias for catch - catch(second: Observable): Observable; - catchException(second: Observable): Observable; // alias for catch - combineLatest(second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; - combineLatest(second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; - combineLatest(second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; - combineLatest(souces: Observable[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; - combineLatest(souces: IPromise[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; - concat(...sources: Observable[]): Observable; - concat(...sources: IPromise[]): Observable; - concat(sources: Observable[]): Observable; - concat(sources: IPromise[]): Observable; - concatAll(): T; - concatObservable(): T; // alias for concatAll - concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat - concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat - concatMap(selector: (value: T, index: number) => Observable): Observable; // alias for selectConcat - concatMap(selector: (value: T, index: number) => IPromise): Observable; // alias for selectConcat - concatMap(sequence: Observable): Observable; // alias for selectConcat - merge(maxConcurrent: number): T; - merge(other: Observable): Observable; - merge(other: IPromise): Observable; - mergeAll(): T; - mergeObservable(): T; // alias for mergeAll - skipUntil(other: Observable): Observable; - skipUntil(other: IPromise): Observable; - switch(): T; - switchLatest(): T; // alias for switch - takeUntil(other: Observable): Observable; - takeUntil(other: IPromise): Observable; - zip(second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; - zip(second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; - zip(second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - zip(second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - zip(second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - zip(second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - zip(second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - zip(second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; - zip(second: Observable[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable; - zip(second: IPromise[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable; - - asObservable(): Observable; - dematerialize(): Observable; - distinctUntilChanged(skipParameter: boolean, comparer: (x: T, y: T) => boolean): Observable; - distinctUntilChanged(keySelector?: (value: T) => TValue, comparer?: (x: TValue, y: TValue) => boolean): Observable; - do(observer: Observer): Observable; - doAction(observer: Observer): Observable; // alias for do - do(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; - doAction(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; // alias for do - finally(action: () => void): Observable; - finallyAction(action: () => void): Observable; // alias for finally - ignoreElements(): Observable; - materialize(): Observable>; - repeat(repeatCount?: number): Observable; - retry(retryCount?: number): Observable; - scan(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; - scan(accumulator: (acc: T, value: T) => T): Observable; - skipLast(count: number): Observable; - startWith(...values: T[]): Observable; - startWith(scheduler: IScheduler, ...values: T[]): Observable; - takeLast(count: number, scheduler?: IScheduler): Observable; - takeLastBuffer(count: number): Observable; - - select(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; - map(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for select - selectMany(selector: (value: T) => Observable, resultSelector: (item: T, other: TOther) => TResult): Observable; - selectMany(selector: (value: T) => IPromise, resultSelector: (item: T, other: TOther) => TResult): Observable; - selectMany(selector: (value: T) => Observable): Observable; - selectMany(selector: (value: T) => IPromise): Observable; - selectMany(other: Observable): Observable; - selectMany(other: IPromise): Observable; - flatMap(selector: (value: T) => Observable, resultSelector: (item: T, other: TOther) => TResult): Observable; // alias for selectMany - flatMap(selector: (value: T) => IPromise, resultSelector: (item: T, other: TOther) => TResult): Observable; // alias for selectMany - flatMap(selector: (value: T) => Observable): Observable; // alias for selectMany - flatMap(selector: (value: T) => IPromise): Observable; // alias for selectMany - flatMap(other: Observable): Observable; // alias for selectMany - flatMap(other: IPromise): Observable; // alias for selectMany - - selectConcat(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; - selectConcat(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; - selectConcat(selector: (value: T, index: number) => Observable): Observable; - selectConcat(selector: (value: T, index: number) => IPromise): Observable; - selectConcat(sequence: Observable): Observable; - - /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then - * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. - * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. - * @param [thisArg] Object to use as this when executing callback. - * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences - * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. - */ - selectSwitch(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; - /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then - * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. - * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. - * @param [thisArg] Object to use as this when executing callback. - * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences - * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. - */ - flatMapLatest(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch - /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then - * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. - * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. - * @param [thisArg] Object to use as this when executing callback. - * @since 2.2.28 - * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences - * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. - */ - switchMap(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch - - skip(count: number): Observable; - skipWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - take(count: number, scheduler?: IScheduler): Observable; - takeWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - where(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - filter(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; // alias for where - - /** - * Converts an existing observable sequence to an ES6 Compatible Promise - * @example - * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); - * @param promiseCtor The constructor of the promise. - * @returns An ES6 compatible promise with the last value from the observable sequence. - */ - toPromise>(promiseCtor: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): TPromise; }): TPromise; - /** - * Converts an existing observable sequence to an ES6 Compatible Promise - * @example - * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); - * - * // With config - * Rx.config.Promise = RSVP.Promise; - * var promise = Rx.Observable.return(42).toPromise(); - * @param [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. - * @returns An ES6 compatible promise with the last value from the observable sequence. - */ - toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }): IPromise; - - // Experimental Flattening - - /** - * Performs a exclusive waiting for the first to finish before subscribing to another observable. - * Observables that come in between subscriptions will be dropped on the floor. - * Can be applied on `Observable>` or `Observable>`. - * @since 2.2.28 - * @returns A exclusive observable with only the results that happen when subscribed. - */ - exclusive(): Observable; - - /** - * Performs a exclusive map waiting for the first to finish before subscribing to another observable. - * Observables that come in between subscriptions will be dropped on the floor. - * Can be applied on `Observable>` or `Observable>`. - * @since 2.2.28 - * @param selector Selector to invoke for every item in the current subscription. - * @param [thisArg] An optional context to invoke with the selector parameter. - * @returns {An exclusive observable with only the results that happen when subscribed. - */ - exclusiveMap(selector: (value: I, index: number, source: Observable) => R, thisArg?: any): Observable; - } - - interface ObservableStatic { - create(subscribe: (observer: Observer) => IDisposable): Observable; - create(subscribe: (observer: Observer) => () => void): Observable; - create(subscribe: (observer: Observer) => void): Observable; - createWithDisposable(subscribe: (observer: Observer) => IDisposable): Observable; - defer(observableFactory: () => Observable): Observable; - defer(observableFactory: () => IPromise): Observable; - empty(scheduler?: IScheduler): Observable; - fromArray(array: T[], scheduler?: IScheduler): Observable; - fromArray(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable; - - /** - * Converts an iterable into an Observable sequence - * - * @example - * var res = Rx.Observable.fromIterable(new Map()); - * var res = Rx.Observable.fromIterable(function* () { yield 42; }); - * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); - * @param generator Generator to convert from. - * @param [scheduler] Scheduler to run the enumeration of the input sequence on. - * @returns The observable sequence whose elements are pulled from the given generator sequence. - */ - fromItreable(generator: () => { next(): { done: boolean; value?: T; }; }, scheduler?: IScheduler): Observable; - - /** - * Converts an iterable into an Observable sequence - * - * @example - * var res = Rx.Observable.fromIterable(new Map()); - * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); - * @param iterable Iterable to convert from. - * @param [scheduler] Scheduler to run the enumeration of the input sequence on. - * @returns The observable sequence whose elements are pulled from the given generator sequence. - */ - fromItreable(iterable: {}, scheduler?: IScheduler): Observable; // todo: can't describe ES6 Iterable via TypeScript type system - generate(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable; - never(): Observable; - - /** - * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. - * - * @example - * var res = Rx.Observable.of(1, 2, 3); - * @since 2.2.28 - * @returns The observable sequence whose elements are pulled from the given arguments. - */ - of(...values: T[]): Observable; - - /** - * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. - * @example - * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); - * @since 2.2.28 - * @param [scheduler] A scheduler to use for scheduling the arguments. - * @returns The observable sequence whose elements are pulled from the given arguments. - */ - ofWithScheduler(scheduler?: IScheduler, ...values: T[]): Observable; - range(start: number, count: number, scheduler?: IScheduler): Observable; - repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; - return(value: T, scheduler?: IScheduler): Observable; - /** - * @since 2.2.28 - */ - just(value: T, scheduler?: IScheduler): Observable; // alias for return - returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return - throw(exception: Error, scheduler?: IScheduler): Observable; - throw(exception: any, scheduler?: IScheduler): Observable; - throwException(exception: Error, scheduler?: IScheduler): Observable; // alias for throw - throwException(exception: any, scheduler?: IScheduler): Observable; // alias for throw - - catch(sources: Observable[]): Observable; - catch(sources: IPromise[]): Observable; - catchException(sources: Observable[]): Observable; // alias for catch - catchException(sources: IPromise[]): Observable; // alias for catch - catch(...sources: Observable[]): Observable; - catch(...sources: IPromise[]): Observable; - catchException(...sources: Observable[]): Observable; // alias for catch - catchException(...sources: IPromise[]): Observable; // alias for catch - - combineLatest(first: Observable, second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: IPromise, second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; - combineLatest(first: Observable, second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; - combineLatest(souces: Observable[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; - combineLatest(souces: IPromise[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; - - concat(...sources: Observable[]): Observable; - concat(...sources: IPromise[]): Observable; - concat(sources: Observable[]): Observable; - concat(sources: IPromise[]): Observable; - merge(...sources: Observable[]): Observable; - merge(...sources: IPromise[]): Observable; - merge(sources: Observable[]): Observable; - merge(sources: IPromise[]): Observable; - merge(scheduler: IScheduler, ...sources: Observable[]): Observable; - merge(scheduler: IScheduler, ...sources: IPromise[]): Observable; - merge(scheduler: IScheduler, sources: Observable[]): Observable; - merge(scheduler: IScheduler, sources: IPromise[]): Observable; - - zip(first: Observable, sources: Observable[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable; - zip(first: Observable, sources: IPromise[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable; - zip(source1: Observable, source2: Observable, resultSelector: (item1: T1, item2: T2) => TResult): Observable; - zip(source1: Observable, source2: IPromise, resultSelector: (item1: T1, item2: T2) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: Observable, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; - zip(source1: Observable, source2: IPromise, source3: Observable, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; - zip(source1: Observable, source2: IPromise, source3: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: Observable, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: IPromise, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: IPromise, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: IPromise, source3: Observable, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: IPromise, source3: Observable, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: IPromise, source3: IPromise, source4: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: IPromise, source3: IPromise, source4: IPromise, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable; - zip(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5) => TResult): Observable; - zipArray(...sources: Observable[]): Observable; - zipArray(sources: Observable[]): Observable; - - /** - * Converts a Promise to an Observable sequence - * @param promise An ES6 Compliant promise. - * @returns An Observable sequence which wraps the existing promise success and failure. - */ - fromPromise(promise: IPromise): Observable; - } - - export var Observable: ObservableStatic; - - interface ISubject extends Observable, Observer, IDisposable { - hasObservers(): boolean; - } - - export interface Subject extends ISubject { - } - - interface SubjectStatic { - new (): Subject; - create(observer?: Observer, observable?: Observable): ISubject; - } - - export var Subject: SubjectStatic; - - export interface AsyncSubject extends Subject { - } - - interface AsyncSubjectStatic { - new (): AsyncSubject; - } - - export var AsyncSubject: AsyncSubjectStatic; -} diff --git a/rx/rx.aggregates.d.ts b/rx/rx.aggregates.d.ts deleted file mode 100644 index 001d1b993..000000000 --- a/rx/rx.aggregates.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Type definitions for RxJS-Aggregates v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module Rx { - export interface Observable { - finalValue(): Observable; - aggregate(accumulator: (acc: T, value: T) => T): Observable; - aggregate(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; - - reduce(accumulator: (acc: T, value: T) => T): Observable; - reduce(accumulator: (acc: TAcc, value: T) => TAcc, seed: TAcc): Observable; // TS0.9.5: won't work https://typescript.codeplex.com/discussions/471751 - - any(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - some(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; // alias for any - - isEmpty(): Observable; - all(predicate?: (value: T) => boolean, thisArg?: any): Observable; - every(predicate?: (value: T) => boolean, thisArg?: any): Observable; // alias for all - contains(value: T): Observable; - contains(value: TOther, comparer: (value1: T, value2: TOther) => boolean): Observable; - count(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - sum(keySelector?: (value: T, index: number, source: Observable) => number, thisArg?: any): Observable; - minBy(keySelector: (item: T) => TKey, comparer: (value1: TKey, value2: TKey) => number): Observable; - minBy(keySelector: (item: T) => number): Observable; - min(comparer?: (value1: T, value2: T) => number): Observable; - maxBy(keySelector: (item: T) => TKey, comparer: (value1: TKey, value2: TKey) => number): Observable; - maxBy(keySelector: (item: T) => number): Observable; - max(comparer?: (value1: T, value2: T) => number): Observable; - average(keySelector?: (value: T, index: number, source: Observable) => number, thisArg?: any): Observable; - - sequenceEqual(second: Observable, comparer: (value1: T, value2: TOther) => number): Observable; - sequenceEqual(second: IPromise, comparer: (value1: T, value2: TOther) => number): Observable; - sequenceEqual(second: Observable): Observable; - sequenceEqual(second: IPromise): Observable; - sequenceEqual(second: TOther[], comparer: (value1: T, value2: TOther) => number): Observable; - sequenceEqual(second: T[]): Observable; - - elementAt(index: number): Observable; - elementAtOrDefault(index: number, defaultValue?: T): Observable; - - single(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - singleOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; - - first(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - firstOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; - - last(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - lastOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; - - find(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - findIndex(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - } -} - -declare module "rx.aggregates" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.all.ts b/rx/rx.all.ts deleted file mode 100644 index c546477b8..000000000 --- a/rx/rx.all.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Type definitions for RxJS-All v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// - -declare module "rx.all" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.async-lite.d.ts b/rx/rx.async-lite.d.ts deleted file mode 100644 index be13320c2..000000000 --- a/rx/rx.async-lite.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -// DefinitelyTyped: partial - -// This file contains common part of defintions for rx.async.d.ts and rx.lite.d.ts -// Do not include the file separately. - -/// - -declare module Rx { - interface ObservableStatic { - /** - * Invokes the asynchronous function, surfacing the result through an observable sequence. - * @param functionAsync Asynchronous function which returns a Promise to run. - * @returns An observable sequence exposing the function's result value, or an exception. - */ - startAsync(functionAsync: () => IPromise): Observable; - - fromCallback: { - // with single result callback without selector - (func: (callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - // with any callback with selector - (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2, arg3: T3) => Observable; - // with any callback without selector - (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - // with any function with selector - (func: Function, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (...args: any[]) => Observable; - // with any function without selector - (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; - }; - - fromNodeCallback: { - // with single result callback without selector - (func: (callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - // with any callback with selector - (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2, arg3: T3) => Observable; - // with any callback without selector - (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - // with any function with selector - (func: Function, scheduler: IScheduler, context: any, selector: (results: TC[]) => T): (...args: any[]) => Observable; - // with any function without selector - (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; - }; - - fromEvent(element: NodeList, eventName: string, selector?: (arguments: any[]) => T): Observable; - fromEvent(element: Node, eventName: string, selector?: (arguments: any[]) => T): Observable; - fromEventPattern(addHandler: (handler: Function) => void, removeHandler: (handler: Function) => void, selector?: (arguments: any[])=>T): Observable; - } -} diff --git a/rx/rx.async-tests.ts b/rx/rx.async-tests.ts deleted file mode 100644 index 9c3bce516..000000000 --- a/rx/rx.async-tests.ts +++ /dev/null @@ -1,88 +0,0 @@ -// Tests for RxJS-Async TypeScript definitions -// Tests by Igor Oleinikov - -/// - -module Rx.Tests.Async { - - var obsNum: Rx.Observable; - var obsStr: Rx.Observable; - var sch: Rx.IScheduler; - - function start() { - obsNum = Rx.Observable.start(()=> 10, sch, obsStr); - obsNum = Rx.Observable.start(()=> 10, sch); - obsNum = Rx.Observable.start(()=> 10); - } - - function toAsync() { - obsNum = Rx.Observable.toAsync(()=> 1, sch)(); - obsNum = Rx.Observable.toAsync((a1: number)=> a1)(1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number)=> a1 + a2.toFixed(0))("", 1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date)=> a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean)=> a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); - } - - function fromCallback() { - // 0 arguments - var func0: (cb: (result: number)=> void)=> void; - obsNum = Rx.Observable.fromCallback(func0)(); - obsNum = Rx.Observable.fromCallback(func0, sch)(); - obsNum = Rx.Observable.fromCallback(func0, sch, obsStr)(); - obsNum = Rx.Observable.fromCallback(func0, sch, obsStr, (results: number[]) => results[0])(); - - // 1 argument - var func1: (a: string, cb: (result: number)=> void)=> number; - obsNum = Rx.Observable.fromCallback(func1)(""); - obsNum = Rx.Observable.fromCallback(func1, sch)(""); - obsNum = Rx.Observable.fromCallback(func1, sch, {})(""); - obsNum = Rx.Observable.fromCallback(func1, sch, {}, (results: number[]) => results[0])(""); - - // 2 arguments - var func2: (a: number, b: string, cb: (result: string) => number) => Date; - obsStr = Rx.Observable.fromCallback(func2)(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch)(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch, {})(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch, {}, (results: string[]) => results[0])(1, ""); - - // 3 arguments - var func3: (a: number, b: string, c: boolean, cb: (result: string) => number) => Date; - obsStr = Rx.Observable.fromCallback(func3)(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch)(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch, {})(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch, {}, (results: string[]) => results[0])(1, "", true); - - // multiple results - var func0m: (cb: (result1: number, result2: number, result3: number) => void) => void; - obsNum = Rx.Observable.fromCallback(func0m, sch, obsStr, (results: number[]) => results[0])(); - var func1m: (a: string, cb: (result1: number, result2: number, result3: number) => void) => void; - obsNum = Rx.Observable.fromCallback(func1m, sch, obsStr, (results: number[]) => results[0])(""); - var func2m: (a: string, b: number, cb: (result1: string, result2: string, result3: string) => void) => void; - obsStr = Rx.Observable.fromCallback(func2m, sch, obsStr, (results: string[]) => results[0])("", 10); - } - - function toPromise() { - var promiseImpl: { - new(resolver: (resolvePromise: (value: T)=> void, rejectPromise: (reason: any)=> void)=> void): Rx.IPromise; - }; - - Rx.config.Promise = promiseImpl; - - var p: IPromise = obsNum.toPromise(promiseImpl); - - p = obsNum.toPromise(); - - p = p.then(x=> x); - p = p.then(x=> p); - p = p.then(undefined, reason=> 10); - p = p.then(undefined, reason=> p); - - var ps: IPromise = p.then(undefined, reason=> "error"); - ps = p.then(x=> ""); - ps = p.then(x=> ps); - } - - function startAsync() { - var o: Rx.Observable = Rx.Observable.startAsync(() => >null); - } -} \ No newline at end of file diff --git a/rx/rx.async.d.ts b/rx/rx.async.d.ts deleted file mode 100644 index 9370c828b..000000000 --- a/rx/rx.async.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Type definitions for RxJS-Async v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: zoetrope , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module Rx { - interface ObservableStatic { - start(func: () => T, scheduler?: IScheduler, context?: any): Observable; - - toAsync(func: () => TResult, scheduler?: IScheduler, context?: any): () => Observable; - toAsync(func: (arg1: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - toAsync(func: (arg1?: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1) => Observable; - toAsync(func: (...args: T1[]) => TResult, scheduler?: IScheduler, context?: any): (...args: T1[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - toAsync(func: (arg1: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2) => Observable; - toAsync(func: (arg1: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, ...args: T2[]) => Observable; - toAsync(func: (arg1?: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, ...args: T2[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3) => Observable; - toAsync(func: (arg1: T1, arg2: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; - } -} - -declare module "rx.async" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.backpressure-lite.d.ts b/rx/rx.backpressure-lite.d.ts deleted file mode 100644 index d1c244195..000000000 --- a/rx/rx.backpressure-lite.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -// DefinitelyTyped: partial - -// This file contains common part of defintions for rx.backpressure.d.ts and rx.lite.d.ts -// Do not include the file separately. - -/// - -declare module Rx { - export interface Observable { - /** - * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. - * @example - * var pauser = new Rx.Subject(); - * var source = Rx.Observable.interval(100).pausable(pauser); - * @param pauser The observable sequence used to pause the underlying sequence. - * @returns The observable sequence which is paused based upon the pauser. - */ - pausable(pauser: Observable): Observable; - pausable(pauser?: ISubject): PausableObservable; - - /** - * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, - * and yields the values that were buffered while paused. - * @example - * var pauser = new Rx.Subject(); - * var source = Rx.Observable.interval(100).pausableBuffered(pauser); - * @param pauser The observable sequence used to pause the underlying sequence. - * @returns The observable sequence which is paused based upon the pauser. - */ - pausableBuffered(pauser?: ISubject): PausableObservable; - - /** - * Attaches a controller to the observable sequence with the ability to queue. - * @example - * var source = Rx.Observable.interval(100).controlled(); - * source.request(3); // Reads 3 values - */ - controlled(enableQueue?: boolean): ControlledObservable; - } - - export interface ControlledObservable extends Observable { - request(numberOfItems?: number): IDisposable; - } - - export interface PausableObservable extends Observable { - pause(): void; - resume(): void; - } -} diff --git a/rx/rx.backpressure-tests.ts b/rx/rx.backpressure-tests.ts deleted file mode 100644 index f036a1dc3..000000000 --- a/rx/rx.backpressure-tests.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Tests for RxJS-BackPressure TypeScript definitions -// Tests by Igor Oleinikov - -/// -/// - -function testPausable() { - var o: Rx.Observable; - - var pauser = new Rx.Subject(); - - var p = o.pausable(pauser); - p = o.pausableBuffered(pauser); -} - -function testControlled() { - var o: Rx.Observable; - var c = o.controlled(); - - var d: Rx.IDisposable = c.request(); - d = c.request(5); -} diff --git a/rx/rx.backpressure.d.ts b/rx/rx.backpressure.d.ts deleted file mode 100644 index 9c5e8abd5..000000000 --- a/rx/rx.backpressure.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Type definitions for RxJS-BackPressure v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module "rx.backpressure" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.binding-lite.d.ts b/rx/rx.binding-lite.d.ts deleted file mode 100644 index f896e260d..000000000 --- a/rx/rx.binding-lite.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -// DefinitelyTyped: partial - -// This file contains common part of defintions for rx.binding.d.ts and rx.lite.d.ts -// Do not include the file separately. - -/// - -declare module Rx { - export interface BehaviorSubject extends Subject { - } - - interface BehaviorSubjectStatic { - new (initialValue: T): BehaviorSubject; - } - - export var BehaviorSubject: BehaviorSubjectStatic; - - export interface ReplaySubject extends Subject { - } - - interface ReplaySubjectStatic { - new (bufferSize?: number, window?: number, scheduler?: IScheduler): ReplaySubject; - } - - export var ReplaySubject: ReplaySubjectStatic; - - interface ConnectableObservable extends Observable { - connect(): IDisposable; - refCount(): Observable; - } - - interface ConnectableObservableStatic { - new (): ConnectableObservable; - } - - export var ConnectableObservable: ConnectableObservableStatic; - - export interface Observable { - multicast(subject: Observable): ConnectableObservable; - multicast(subjectSelector: () => ISubject, selector: (source: ConnectableObservable) => Observable): Observable; - publish(): ConnectableObservable; - publish(selector: (source: ConnectableObservable) => Observable): Observable; - /** - * Returns an observable sequence that shares a single subscription to the underlying sequence. - * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * - * @example - * var res = source.share(); - * - * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. - */ - share(): Observable; - publishLast(): ConnectableObservable; - publishLast(selector: (source: ConnectableObservable) => Observable): Observable; - publishValue(initialValue: T): ConnectableObservable; - publishValue(selector: (source: ConnectableObservable) => Observable, initialValue: T): Observable; - /** - * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. - * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * - * @example - * var res = source.shareValue(42); - * - * @param initialValue Initial value received by observers upon subscription. - * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. - */ - shareValue(initialValue: T): Observable; - replay(selector?: boolean, bufferSize?: number, window?: number, scheduler?: IScheduler): ConnectableObservable; // hack to catch first omitted parameter - replay(selector: (source: ConnectableObservable) => Observable, bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; - shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; - } -} diff --git a/rx/rx.binding.d.ts b/rx/rx.binding.d.ts deleted file mode 100644 index b93411a52..000000000 --- a/rx/rx.binding.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Type definitions for RxJS-Binding v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module "rx.binding" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.coincidence-lite.d.ts b/rx/rx.coincidence-lite.d.ts deleted file mode 100644 index 801e42168..000000000 --- a/rx/rx.coincidence-lite.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -// DefinitelyTyped: partial - -// This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts -// Do not include the file separately. - -/// - -declare module Rx { - - interface Observable { - /** - * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. - * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. - * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. - * @returns An observable that triggers on successive pairs of observations from the input observable as an array. - */ - pairwise(): Observable; - - /** - * Returns two observables which partition the observations of the source by the given function. - * The first will trigger observations for those values for which the predicate returns true. - * The second will trigger observations for those values where the predicate returns false. - * The predicate is executed once for each subscribed observer. - * Both also propagate all error observations arising from the source and each completes - * when the source completes. - * @param predicate - * The function to determine which output Observable will trigger a particular observation. - * @returns - * An array of observables. The first triggers when the predicate returns true, - * and the second triggers when the predicate returns false. - */ - partition(predicate: (value: T, index: number, source: Observable) => boolean, thisArg: any): Observable[]; - } -} diff --git a/rx/rx.coincidence.d.ts b/rx/rx.coincidence.d.ts deleted file mode 100644 index 87fa6a55b..000000000 --- a/rx/rx.coincidence.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Type definitions for RxJS-Coincidence v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module Rx { - - interface Observable { - join( - right: Observable, - leftDurationSelector: (leftItem: T) => Observable, - rightDurationSelector: (rightItem: TRight) => Observable, - resultSelector: (leftItem: T, rightItem: TRight) => TResult): Observable; - - groupJoin( - right: Observable, - leftDurationSelector: (leftItem: T) => Observable, - rightDurationSelector: (rightItem: TRight) => Observable, - resultSelector: (leftItem: T, rightItem: Observable) => TResult): Observable; - - window(windowOpenings: Observable): Observable>; - window(windowClosingSelector: () => Observable): Observable>; - window(windowOpenings: Observable, windowClosingSelector: () => Observable): Observable>; - - buffer(bufferOpenings: Observable): Observable; - buffer(bufferClosingSelector: () => Observable): Observable; - buffer(bufferOpenings: Observable, bufferClosingSelector: () => Observable): Observable; - } -} - -declare module "rx.coincidence" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.d.ts b/rx/rx.d.ts deleted file mode 100644 index 1f26a94a9..000000000 --- a/rx/rx.d.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Type definitions for RxJS v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: gsino , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module Rx { - export interface IScheduler { - catch(handler: (exception: any) => boolean): IScheduler; - catchException(handler: (exception: any) => boolean): IScheduler; - } - - export class Scheduler implements IScheduler { - constructor( - now: () => number, - schedule: (state: any, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, - scheduleRelative: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, - scheduleAbsolute: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable); - - static normalize(timeSpan: number): number; - - static immediate: IScheduler; - static currentThread: ICurrentThreadScheduler; - static timeout: IScheduler; - - now(): number; - catch(handler: (exception: any) => boolean): IScheduler; - catchException(handler: (exception: any) => boolean): IScheduler; - - schedule(action: () => void): IDisposable; - scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; - scheduleWithAbsoluteAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - scheduleWithRelative(dueTime: number, action: () => void): IDisposable; - scheduleWithRelativeAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - - scheduleRecursive(action: (action: () => void) => void): IDisposable; - scheduleRecursiveWithState(state: TState, action: (state: TState, action: (state: TState) => void) => void): IDisposable; - scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithAbsoluteAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithRelativeAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; - - schedulePeriodic(period: number, action: () => void): IDisposable; - schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; - } - - // Observer - export interface Observer { - checked(): Observer; - } - - interface ObserverStatic { - /** - * Schedules the invocation of observer methods on the given scheduler. - * @param scheduler Scheduler to schedule observer messages on. - * @returns Observer whose messages are scheduled on the given scheduler. - */ - notifyOn(scheduler: IScheduler): Observer; - } - - export interface Observable { - observeOn(scheduler: IScheduler): Observable; - subscribeOn(scheduler: IScheduler): Observable; - - amb(rightSource: Observable): Observable; - amb(rightSource: IPromise): Observable; - onErrorResumeNext(second: Observable): Observable; - onErrorResumeNext(second: IPromise): Observable; - bufferWithCount(count: number, skip?: number): Observable; - windowWithCount(count: number, skip?: number): Observable>; - defaultIfEmpty(defaultValue?: T): Observable; - distinct(skipParameter: boolean, valueSerializer: (value: T) => string): Observable; - distinct(keySelector?: (value: T) => TKey, keySerializer?: (key: TKey) => string): Observable; - groupBy(keySelector: (value: T) => TKey, skipElementSelector?: boolean, keySerializer?: (key: TKey) => string): Observable>; - groupBy(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, keySerializer?: (key: TKey) => string): Observable>; - groupByUntil(keySelector: (value: T) => TKey, skipElementSelector: boolean, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; - groupByUntil(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; - } - - interface ObservableStatic { - using(resourceFactory: () => TResource, observableFactory: (resource: TResource) => Observable): Observable; - amb(...sources: Observable[]): Observable; - amb(...sources: IPromise[]): Observable; - amb(sources: Observable[]): Observable; - amb(sources: IPromise[]): Observable; - onErrorResumeNext(...sources: Observable[]): Observable; - onErrorResumeNext(...sources: IPromise[]): Observable; - onErrorResumeNext(sources: Observable[]): Observable; - onErrorResumeNext(sources: IPromise[]): Observable; - } - - interface GroupedObservable extends Observable { - key: TKey; - underlyingObservable: Observable; - } -} - -declare module "rx" { - export = Rx -} diff --git a/rx/rx.experimental.d.ts b/rx/rx.experimental.d.ts deleted file mode 100644 index 60aec86e1..000000000 --- a/rx/rx.experimental.d.ts +++ /dev/null @@ -1,321 +0,0 @@ -// Type definitions for RxJS-Experimental v2.2.28 -// Project: https://github.com/Reactive-Extensions/RxJS/ -// Definitions by: Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module Rx { - - interface Observable { - /** - * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. - * This operator allows for a fluent style of writing queries that use the same sequence multiple times. - * - * @param selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. - * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - let(selector: (source: Observable) => Observable): Observable; - - /** - * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. - * This operator allows for a fluent style of writing queries that use the same sequence multiple times. - * - * @param selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. - * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - letBind(selector: (source: Observable) => Observable): Observable; - - /** - * Repeats source as long as condition holds emulating a do while loop. - * @param condition The condition which determines if the source will be repeated. - * @returns An observable sequence which is repeated as long as the condition holds. - */ - doWhile(condition: () => boolean): Observable; - - /** - * Expands an observable sequence by recursively invoking selector. - * - * @param selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. - * @param [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. - * @returns An observable sequence containing all the elements produced by the recursive expansion. - */ - expand(selector: (item: T) => Observable, scheduler?: IScheduler): Observable; - - /** - * Runs two observable sequences in parallel and combines their last elemenets. - * - * @param second Second observable sequence or promise. - * @param resultSelector Result selector function to invoke with the last elements of both sequences. - * @returns An observable sequence with the result of calling the selector function with the last elements of both input sequences. - */ - forkJoin(second: Observable, resultSelector: (left: T, right: TSecond) => TResult): Observable; - forkJoin(second: IPromise, resultSelector: (left: T, right: TSecond) => TResult): Observable; - - /** - * Comonadic bind operator. - * @param selector A transform function to apply to each element. - * @param [scheduler] Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. - * @returns An observable sequence which results from the comonadic bind operation. - */ - manySelect(selector: (item: Observable, index: number, source: Observable) => TResult, scheduler?: IScheduler): Observable; - } - - interface ObservableStatic { - /** - * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, elseSource: Observable): Observable; - if(condition: () => boolean, thenSource: Observable, elseSource: IPromise): Observable; - if(condition: () => boolean, thenSource: IPromise, elseSource: Observable): Observable; - if(condition: () => boolean, thenSource: IPromise, elseSource: IPromise): Observable; - - /** - * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, scheduler?: IScheduler): Observable; - if(condition: () => boolean, thenSource: IPromise, scheduler?: IScheduler): Observable; - - /** - * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, elseSource: Observable): Observable; - ifThen(condition: () => boolean, thenSource: Observable, elseSource: IPromise): Observable; - ifThen(condition: () => boolean, thenSource: IPromise, elseSource: Observable): Observable; - ifThen(condition: () => boolean, thenSource: IPromise, elseSource: IPromise): Observable; - - /** - * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (condition: () => boolean, thenSource: Observable, scheduler?: IScheduler): Observable; - ifThen(condition: () => boolean, thenSource: IPromise, scheduler?: IScheduler): Observable; - - /** - * Concatenates the observable sequences obtained by running the specified result selector for each element in source. - * There is an alias for this method called 'forIn' for browsers (sources: T[], resultSelector: (item: T) => Observable): Observable; - - /** - * Concatenates the observable sequences obtained by running the specified result selector for each element in source. - * There is an alias for this method called 'forIn' for browsers (sources: T[], resultSelector: (item: T) => Observable): Observable; - - /** - * Repeats source as long as condition holds emulating a while loop. - * There is an alias for this method called 'whileDo' for browsers (condition: () => boolean, source: Observable): Observable; - while(condition: () => boolean, source: IPromise): Observable; - - /** - * Repeats source as long as condition holds emulating a while loop. - * There is an alias for this method called 'whileDo' for browsers (condition: () => boolean, source: Observable): Observable; - whileDo(condition: () => boolean, source: IPromise): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, elseSource: Observable): Observable; - case(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: Observable): Observable; - case(selector: () => string, sources: { [key: string]: Observable; }, elseSource: IPromise): Observable; - case(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: IPromise): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, scheduler?: IScheduler): Observable; - case(selector: () => string, sources: { [key: string]: IPromise; }, scheduler?: IScheduler): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, elseSource: Observable): Observable; - case(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: Observable): Observable; - case(selector: () => number, sources: { [key: number]: Observable; }, elseSource: IPromise): Observable; - case(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: IPromise): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, scheduler?: IScheduler): Observable; - case(selector: () => number, sources: { [key: number]: IPromise; }, scheduler?: IScheduler): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, elseSource: Observable): Observable; - switchCase(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: Observable): Observable; - switchCase(selector: () => string, sources: { [key: string]: Observable; }, elseSource: IPromise): Observable; - switchCase(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: IPromise): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, scheduler?: IScheduler): Observable; - switchCase(selector: () => string, sources: { [key: string]: IPromise; }, scheduler?: IScheduler): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, elseSource: Observable): Observable; - switchCase(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: Observable): Observable; - switchCase(selector: () => number, sources: { [key: number]: Observable; }, elseSource: IPromise): Observable; - switchCase(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: IPromise): Observable; - - /** - * Uses selector to determine which source in sources to use. - * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, scheduler?: IScheduler): Observable; - switchCase(selector: () => number, sources: { [key: number]: IPromise; }, scheduler?: IScheduler): Observable; - - /** - * Runs all observable sequences in parallel and collect their last elements. - * - * @example - * res = Rx.Observable.forkJoin([obs1, obs2]); - * @param sources Array of source sequences or promises. - * @returns An observable sequence with an array collecting the last elements of all the input sequences. - */ - forkJoin(sources: Observable[]): Observable; - forkJoin(sources: IPromise[]): Observable; - - /** - * Runs all observable sequences in parallel and collect their last elements. - * - * @example - * res = Rx.Observable.forkJoin(obs1, obs2, ...); - * @param args Source sequences or promises. - * @returns An observable sequence with an array collecting the last elements of all the input sequences. - */ - forkJoin(...args: Observable[]): Observable; - forkJoin(...args: IPromise[]): Observable; - } -} - -declare module "rx.experimental" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.joinpatterns.d.ts b/rx/rx.joinpatterns.d.ts deleted file mode 100644 index 929c66a6f..000000000 --- a/rx/rx.joinpatterns.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Type definitions for RxJS-Join v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module Rx { - - interface Pattern1 { - and(other: Observable): Pattern2; - then(selector: (item1: T1) => TR): Plan; - } - interface Pattern2 { - and(other: Observable): Pattern3; - then(selector: (item1: T1, item2: T2) => TR): Plan; - } - interface Pattern3 { - and(other: Observable): Pattern4; - then(selector: (item1: T1, item2: T2, item3: T3) => TR): Plan; - } - interface Pattern4 { - and(other: Observable): Pattern5; - then(selector: (item1: T1, item2: T2, item3: T3, item4: T4) => TR): Plan; - } - interface Pattern5 { - and(other: Observable): Pattern6; - then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5) => TR): Plan; - } - interface Pattern6 { - and(other: Observable): Pattern7; - then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6) => TR): Plan; - } - interface Pattern7 { - and(other: Observable): Pattern8; - then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6, item7: T7) => TR): Plan; - } - interface Pattern8 { - and(other: Observable): Pattern9; - then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6, item7: T7, item8: T8) => TR): Plan; - } - interface Pattern9 { - then(selector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5, item6: T6, item7: T7, item8: T8, item9: T9) => TR): Plan; - } - - interface Plan { } - - interface Observable { - and(other: Observable): Pattern2; - then(selector: (item1: T) => TR): Plan; - } - - interface ObservableStatic { - when(plan: Plan): Observable; - } -} - -declare module "rx.joinpatterns" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.lite.d.ts b/rx/rx.lite.d.ts deleted file mode 100644 index 046ef527d..000000000 --- a/rx/rx.lite.d.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Type definitions for RxJS-Lite v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: gsino , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// -/// -/// -/// -/// - -declare module Rx { - export class Scheduler implements IScheduler { - constructor( - now: () => number, - schedule: (state: any, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, - scheduleRelative: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, - scheduleAbsolute: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable); - - static normalize(timeSpan: number): number; - - static immediate: IScheduler; - static currentThread: ICurrentThreadScheduler; - static timeout: IScheduler; - - now(): number; - - schedule(action: () => void): IDisposable; - scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; - scheduleWithAbsoluteAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - scheduleWithRelative(dueTime: number, action: () => void): IDisposable; - scheduleWithRelativeAndState(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - - scheduleRecursive(action: (action: () => void) => void): IDisposable; - scheduleRecursiveWithState(state: TState, action: (state: TState, action: (state: TState) => void) => void): IDisposable; - scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithAbsoluteAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; - scheduleRecursiveWithRelativeAndState(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; - - schedulePeriodic(period: number, action: () => void): IDisposable; - schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; - } -} - -declare module "rx.lite" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.testing.d.ts b/rx/rx.testing.d.ts deleted file mode 100644 index 0adc83e50..000000000 --- a/rx/rx.testing.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Type definitions for RxJS-Testing v2.2.28 -// Project: https://github.com/Reactive-Extensions/RxJS/ -// Definitions by: Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module Rx { - export class TestScheduler extends VirtualTimeScheduler { - constructor(); - - createColdObservable(...records: Recorded[]): Observable; - createHotObservable(...records: Recorded[]): Observable; - createObserver(): MockObserver; - - startWithTiming(create: () => Observable, createdAt: number, subscribedAt: number, disposedAt: number): MockObserver; - startWithDispose(create: () => Observable, disposedAt: number): MockObserver; - startWithCreate(create: () => Observable): MockObserver; - } - - export class Recorded { - constructor(time: number, value: any, equalityComparer?: (x: any, y: any) => boolean); - equals(other: Recorded): boolean; - toString(): string; - time: number; - value: any; - } - - export var ReactiveTest: { - created: number; - subscribed: number; - disposed: number; - - onNext(ticks: number, value: any): Recorded; - onNext(ticks: number, predicate: (value: any) => boolean): Recorded; - onError(ticks: number, exception: any): Recorded; - onError(ticks: number, predicate: (exception: any) => boolean): Recorded; - onCompleted(ticks: number): Recorded; - - subscribe(subscribeAt: number, unsubscribeAt?: number): Subscription; - }; - - export class Subscription { - constructor(subscribeAt: number, unsubscribeAt?: number); - equals(other: Subscription): boolean; - } - - export interface MockObserver extends Observer { - messages: Recorded[]; - } - - interface MockObserverStatic extends ObserverStatic { - new (scheduler: IScheduler): MockObserver; - } - - export var MockObserver: MockObserverStatic; -} - -declare module "rx.testing" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.time-lite.d.ts b/rx/rx.time-lite.d.ts deleted file mode 100644 index a5b102827..000000000 --- a/rx/rx.time-lite.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// DefinitelyTyped: partial - -// This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts -// Do not include the file separately. - -/// - -declare module Rx { - export interface TimeInterval { - value: T; - interval: number; - } - - export interface Timestamp { - value: T; - timestamp: number; - } - - export interface Observable { - delay(dueTime: number, scheduler?: IScheduler): Observable; - throttle(dueTime: number, scheduler?: IScheduler): Observable; - timeInterval(scheduler?: IScheduler): Observable>; - timestamp(scheduler?: IScheduler): Observable>; - sample(interval: number, scheduler?: IScheduler): Observable; - sample(sampler: Observable, scheduler?: IScheduler): Observable; - timeout(dueTime: Date, other?: Observable, scheduler?: IScheduler): Observable; - timeout(dueTime: number, other?: Observable, scheduler?: IScheduler): Observable; - - delaySubscription(dueTime: number, scheduler?: IScheduler): Observable; - delayWithSelector(delayDurationSelector: (item: T) => number): Observable; - delayWithSelector(subscriptionDelay: number, delayDurationSelector: (item: T) => number): Observable; - - timeoutWithSelector(firstTimeout: Observable, timeoutdurationSelector?: (item: T) => Observable, other?: Observable): Observable; - throttleWithSelector(throttleDurationSelector: (item: T) => Observable): Observable; - - skipLastWithTime(duration: number, scheduler?: IScheduler): Observable; - takeLastWithTime(duration: number, timerScheduler?: IScheduler, loopScheduler?: IScheduler): Observable; - - takeLastBufferWithTime(duration: number, scheduler?: IScheduler): Observable; - takeWithTime(duration: number, scheduler?: IScheduler): Observable; - skipWithTime(duration: number, scheduler?: IScheduler): Observable; - - skipUntilWithTime(startTime: Date, scheduler?: IScheduler): Observable; - skipUntilWithTime(duration: number, scheduler?: IScheduler): Observable; - takeUntilWithTime(endTime: Date, scheduler?: IScheduler): Observable; - takeUntilWithTime(duration: number, scheduler?: IScheduler): Observable; - } - - interface ObservableStatic { - interval(period: number, scheduler?: IScheduler): Observable; - interval(dutTime: number, period: number, scheduler?: IScheduler): Observable; - timer(dueTime: number, period: number, scheduler: IScheduler): Observable; - timer(dueTime: number, scheduler: IScheduler): Observable; - generateWithRelativeTime( - initialState: TState, - condition: (state: TState) => boolean, - iterate: (state: TState) => TState, - resultSelector: (state: TState) => TResult, - timeSelector: (state: TState) => number, - scheduler?: IScheduler): Observable; - } -} diff --git a/rx/rx.time.d.ts b/rx/rx.time.d.ts deleted file mode 100644 index 6efd7d9cf..000000000 --- a/rx/rx.time.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Type definitions for RxJS-Time v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module Rx { - export interface Observable { - windowWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable>; - windowWithTime(timeSpan: number, scheduler?: IScheduler): Observable>; - windowWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable>; - bufferWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable; - bufferWithTime(timeSpan: number, scheduler?: IScheduler): Observable; - bufferWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable; - } - - interface ObservableStatic { - timer(dueTime: Date, period: number, scheduler: IScheduler): Observable; - timer(dueTime: Date, scheduler: IScheduler): Observable; - - generateWithAbsoluteTime( - initialState: TState, - condition: (state: TState) => boolean, - iterate: (state: TState) => TState, - resultSelector: (state: TState) => TResult, - timeSelector: (state: TState) => Date, - scheduler?: IScheduler): Observable; - } -} - -declare module "rx.time" { - export = Rx; -} \ No newline at end of file diff --git a/rx/rx.virtualtime.d.ts b/rx/rx.virtualtime.d.ts deleted file mode 100644 index 50a1bb39b..000000000 --- a/rx/rx.virtualtime.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Type definitions for RxJS-VirtualTime v2.2.28 -// Project: http://rx.codeplex.com/ -// Definitions by: gsino , Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module Rx { - // Virtual IScheduler - export /*abstract*/ class VirtualTimeScheduler extends Scheduler { - constructor(initialClock: TAbsolute, comparer: (first: TAbsolute, second: TAbsolute) => number); - - advanceBy(time: TRelative): void; - advanceTo(time: TAbsolute): void; - scheduleAbsolute(dueTime: TAbsolute, action: () => void): IDisposable; - scheduleAbsoluteWithState(state: TState, dueTime: TAbsolute, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - scheduleRelative(dueTime: TRelative, action: () => void): IDisposable; - scheduleRelativeWithState(state: TState, dueTime: TRelative, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; - sleep(time: TRelative): void; - start(): IDisposable; - stop(): void; - - isEnabled: boolean; - - /* protected abstract */ add(from: TAbsolute, by: TRelative): TAbsolute; - /* protected abstract */ toDateTimeOffset(duetime: TAbsolute): number; - /* protected abstract */ toRelative(duetime: number): TRelative; - - /* protected */ getNext(): internals.ScheduledItem; - } - - export class HistoricalScheduler extends VirtualTimeScheduler { - constructor(initialClock: number, comparer: (first: number, second: number) => number); - } -} - -declare module "rx.virtualtime" { - export = Rx; -} \ No newline at end of file From 77615ebcf03c7da283edd182dc14704bc5f8385f Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 10:03:38 -0700 Subject: [PATCH 006/149] Added few helpers functions. --- rx-lite.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rx-lite.d.ts b/rx-lite.d.ts index c7a148137..eea3c55ce 100644 --- a/rx-lite.d.ts +++ b/rx-lite.d.ts @@ -49,6 +49,8 @@ declare module Rx { export module helpers { function noop(): void; + function notDefined(value: any): boolean; + function isScheduler(value: any): boolean; function identity(value: T): T; function defaultNow(): number; function defaultComparer(left: any, right: any): boolean; From 68b8e0481ff91f731f75e4f48ac3d81226a1272a Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 12:10:45 -0700 Subject: [PATCH 007/149] Added ObservableStatic.from definition. --- rx-lite.d.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/rx-lite.d.ts b/rx-lite.d.ts index eea3c55ce..f33193af2 100644 --- a/rx-lite.d.ts +++ b/rx-lite.d.ts @@ -396,6 +396,50 @@ declare module Rx { defer(observableFactory: () => Observable): Observable; defer(observableFactory: () => IPromise): Observable; empty(scheduler?: IScheduler): Observable; + + /** + * This method creates a new Observable sequence from an array object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param mapFn Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: T[], mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler); + /** + * This method creates a new Observable sequence from an array object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param [mapFn] Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: T[], mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler); + + /** + * This method creates a new Observable sequence from an array-like object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param mapFn Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: { length: number; [index: number]: T; }, mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler); + /** + * This method creates a new Observable sequence from an array-like object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param [mapFn] Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: { length: number; [index: number]: T; }, mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler); + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param [mapFn] Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(iterable: any, mapFn?: (value: any, index: number) => T, thisArg?: any, scheduler?: IScheduler); + fromArray(array: T[], scheduler?: IScheduler): Observable; fromArray(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable; From 0f4537ae1cc2718cf670ef186dd71d17ab9e05b5 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 12:50:51 -0700 Subject: [PATCH 008/149] Removed scheduler parameter from fromCallback and fromNodeCallback. --- rx.async-lite.d.ts | 56 +++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/rx.async-lite.d.ts b/rx.async-lite.d.ts index be13320c2..77dc23b57 100644 --- a/rx.async-lite.d.ts +++ b/rx.async-lite.d.ts @@ -16,46 +16,46 @@ declare module Rx { fromCallback: { // with single result callback without selector - (func: (callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: (result: TResult) => any) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: (result: TResult) => any) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: (result: TResult) => any) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: (result: TResult) => any) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback with selector - (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): () => Observable; + (func: (arg1: T1, callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback without selector - (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: Function) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any function with selector - (func: Function, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (...args: any[]) => Observable; + (func: Function, context: any, selector: (args: TCallbackResult[]) => TResult): (...args: any[]) => Observable; // with any function without selector - (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; + (func: Function, context?: any): (...args: any[]) => Observable; }; fromNodeCallback: { // with single result callback without selector - (func: (callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: (err: any, result: T) => any) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: (err: any, result: T) => any) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: (err: any, result: T) => any) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: T) => any) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback with selector - (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context: any, selector: (results: TC[]) => TR): () => Observable; + (func: (arg1: T1, callback: Function) => any, context: any, selector: (results: TC[]) => TR): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback without selector - (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: Function) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any function with selector - (func: Function, scheduler: IScheduler, context: any, selector: (results: TC[]) => T): (...args: any[]) => Observable; + (func: Function, context: any, selector: (results: TC[]) => T): (...args: any[]) => Observable; // with any function without selector - (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; + (func: Function, context?: any): (...args: any[]) => Observable; }; fromEvent(element: NodeList, eventName: string, selector?: (arguments: any[]) => T): Observable; From 4c9e9782a7618445da97362529608d38716cba60 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 12:57:09 -0700 Subject: [PATCH 009/149] Exchanged parameters scheduler and context in ObservableStatic.start. --- rx.async.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rx.async.d.ts b/rx.async.d.ts index 9370c828b..fd85bcd7d 100644 --- a/rx.async.d.ts +++ b/rx.async.d.ts @@ -8,7 +8,7 @@ declare module Rx { interface ObservableStatic { - start(func: () => T, scheduler?: IScheduler, context?: any): Observable; + start(func: () => T, context?: any, scheduler?: IScheduler): Observable; toAsync(func: () => TResult, scheduler?: IScheduler, context?: any): () => Observable; toAsync(func: (arg1: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; From 60a7a1e19bbe21efa50011c93cee170154e3faf9 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 13:00:08 -0700 Subject: [PATCH 010/149] Exchanged parameters scheduler and context in ObservableStatic.toAsync. --- rx.async.d.ts | 50 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/rx.async.d.ts b/rx.async.d.ts index fd85bcd7d..783f31d52 100644 --- a/rx.async.d.ts +++ b/rx.async.d.ts @@ -10,31 +10,31 @@ declare module Rx { interface ObservableStatic { start(func: () => T, context?: any, scheduler?: IScheduler): Observable; - toAsync(func: () => TResult, scheduler?: IScheduler, context?: any): () => Observable; - toAsync(func: (arg1: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - toAsync(func: (arg1?: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1) => Observable; - toAsync(func: (...args: T1[]) => TResult, scheduler?: IScheduler, context?: any): (...args: T1[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - toAsync(func: (arg1: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2) => Observable; - toAsync(func: (arg1: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, ...args: T2[]) => Observable; - toAsync(func: (arg1?: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, ...args: T2[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3) => Observable; - toAsync(func: (arg1: T1, arg2: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: () => TResult, context?: any, scheduler?: IScheduler): () => Observable; + toAsync(func: (arg1: T1) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1) => Observable; + toAsync(func: (arg1?: T1) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1) => Observable; + toAsync(func: (...args: T1[]) => TResult, context?: any, scheduler?: IScheduler): (...args: T1[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2) => Observable; + toAsync(func: (arg1: T1, arg2?: T2) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2) => Observable; + toAsync(func: (arg1: T1, ...args: T2[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, ...args: T2[]) => Observable; + toAsync(func: (arg1?: T1, ...args: T2[]) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, ...args: T2[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3?: T3) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, arg3?: T3) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, arg3?: T3) => Observable; + toAsync(func: (arg1: T1, arg2: T2, ...args: T3[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, ...args: T3[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, ...args: T3[]) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; } } From f3910a041c316523ef5e4fedb37f771c4f77a1dd Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 13:19:13 -0700 Subject: [PATCH 011/149] Added return type annotation in ObservableStatic.from. --- rx-lite.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/rx-lite.d.ts b/rx-lite.d.ts index f33193af2..4b5acb81d 100644 --- a/rx-lite.d.ts +++ b/rx-lite.d.ts @@ -404,7 +404,7 @@ declare module Rx { * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ - from(array: T[], mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler); + from(array: T[], mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable; /** * This method creates a new Observable sequence from an array object. * @param array An array-like or iterable object to convert to an Observable sequence. @@ -412,7 +412,7 @@ declare module Rx { * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ - from(array: T[], mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler); + from(array: T[], mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable; /** * This method creates a new Observable sequence from an array-like object. @@ -421,7 +421,7 @@ declare module Rx { * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ - from(array: { length: number; [index: number]: T; }, mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler); + from(array: { length: number;[index: number]: T; }, mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable; /** * This method creates a new Observable sequence from an array-like object. * @param array An array-like or iterable object to convert to an Observable sequence. @@ -429,7 +429,7 @@ declare module Rx { * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ - from(array: { length: number; [index: number]: T; }, mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler); + from(array: { length: number;[index: number]: T; }, mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable; /** * This method creates a new Observable sequence from an array-like or iterable object. @@ -438,7 +438,7 @@ declare module Rx { * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ - from(iterable: any, mapFn?: (value: any, index: number) => T, thisArg?: any, scheduler?: IScheduler); + from(iterable: any, mapFn?: (value: any, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable; fromArray(array: T[], scheduler?: IScheduler): Observable; fromArray(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable; From 8da4768d8f99c40d5c80fa818720f4fe7e5846ff Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 22 Jul 2014 14:41:11 -0700 Subject: [PATCH 012/149] Fixed rx.async-tests.ts. --- rx.async-tests.ts | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/rx.async-tests.ts b/rx.async-tests.ts index 9c3bce516..4f8c102c4 100644 --- a/rx.async-tests.ts +++ b/rx.async-tests.ts @@ -10,8 +10,8 @@ module Rx.Tests.Async { var sch: Rx.IScheduler; function start() { - obsNum = Rx.Observable.start(()=> 10, sch, obsStr); - obsNum = Rx.Observable.start(()=> 10, sch); + obsNum = Rx.Observable.start(()=> 10, obsStr, sch); + obsNum = Rx.Observable.start(() => 10, obsStr); obsNum = Rx.Observable.start(()=> 10); } @@ -27,38 +27,34 @@ module Rx.Tests.Async { // 0 arguments var func0: (cb: (result: number)=> void)=> void; obsNum = Rx.Observable.fromCallback(func0)(); - obsNum = Rx.Observable.fromCallback(func0, sch)(); - obsNum = Rx.Observable.fromCallback(func0, sch, obsStr)(); - obsNum = Rx.Observable.fromCallback(func0, sch, obsStr, (results: number[]) => results[0])(); + obsNum = Rx.Observable.fromCallback(func0, obsStr)(); + obsNum = Rx.Observable.fromCallback(func0, obsStr, (results: number[]) => results[0])(); // 1 argument var func1: (a: string, cb: (result: number)=> void)=> number; obsNum = Rx.Observable.fromCallback(func1)(""); - obsNum = Rx.Observable.fromCallback(func1, sch)(""); - obsNum = Rx.Observable.fromCallback(func1, sch, {})(""); - obsNum = Rx.Observable.fromCallback(func1, sch, {}, (results: number[]) => results[0])(""); + obsNum = Rx.Observable.fromCallback(func1, {})(""); + obsNum = Rx.Observable.fromCallback(func1, {}, (results: number[]) => results[0])(""); // 2 arguments var func2: (a: number, b: string, cb: (result: string) => number) => Date; obsStr = Rx.Observable.fromCallback(func2)(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch)(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch, {})(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch, {}, (results: string[]) => results[0])(1, ""); + obsStr = Rx.Observable.fromCallback(func2, {})(1, ""); + obsStr = Rx.Observable.fromCallback(func2, {}, (results: string[]) => results[0])(1, ""); // 3 arguments var func3: (a: number, b: string, c: boolean, cb: (result: string) => number) => Date; obsStr = Rx.Observable.fromCallback(func3)(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch)(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch, {})(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch, {}, (results: string[]) => results[0])(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, {})(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, {}, (results: string[]) => results[0])(1, "", true); // multiple results var func0m: (cb: (result1: number, result2: number, result3: number) => void) => void; - obsNum = Rx.Observable.fromCallback(func0m, sch, obsStr, (results: number[]) => results[0])(); + obsNum = Rx.Observable.fromCallback(func0m, obsStr, (results: number[]) => results[0])(); var func1m: (a: string, cb: (result1: number, result2: number, result3: number) => void) => void; - obsNum = Rx.Observable.fromCallback(func1m, sch, obsStr, (results: number[]) => results[0])(""); + obsNum = Rx.Observable.fromCallback(func1m, obsStr, (results: number[]) => results[0])(""); var func2m: (a: string, b: number, cb: (result1: string, result2: string, result3: string) => void) => void; - obsStr = Rx.Observable.fromCallback(func2m, sch, obsStr, (results: string[]) => results[0])("", 10); + obsStr = Rx.Observable.fromCallback(func2m, obsStr, (results: string[]) => results[0])("", 10); } function toPromise() { From 2b4eb035ffad1fe950ad008e72784f870279071c Mon Sep 17 00:00:00 2001 From: HowardRichards Date: Fri, 29 Aug 2014 14:02:20 +0100 Subject: [PATCH 013/149] Knockout: amended components.register to overloads supported by 3.2 KO Version 3.2 added components. The .register method in the current code is incorrect and does not support the correct overloads permitted. --- knockout/knockout.d.ts | 52 +++++++++++++++++++++++++++++++- knockout/tests/knockout-tests.ts | 45 +++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 48f550dfe..494b6f844 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -556,7 +556,13 @@ interface KnockoutBindingProvider { } interface KnockoutComponents { - register(componentName: string, definition: KnockoutComponentDefinition): void; + // overloads for register method: + register(componentName: string, config: KnockoutComponentRegister): void; + register(componentName: string, config: KnockoutComponentRegisterStringTemplate): void; + register(componentName: string, config: KnockoutComponentRegisterFnViewModel): void; + register(componentName: string, config: KnockoutComponentRegisterStringTemplateFnViewModel): void; + register(componentName: string, config: KnockoutComponentRegisterAMD): void; + isRegistered(componentName: string): boolean; unregister(componentName: string): void; get(componentName: string, callback: (definition: KnockoutComponentDefinition) => void): void; @@ -566,6 +572,50 @@ interface KnockoutComponents { getComponentNameForNode(node: Node): string; } +/* interfaces for register overloads*/ + +interface KnockoutComponentRegister { + template: KnockoutComponentTemplate; + viewModel?: KnockoutComponentConfigViewModel; +} + +interface KnockoutComponentRegisterAMD { + // load self-describing module using AMD module name + require: string; +} + +interface KnockoutComponentRegisterFnViewModel { + template: KnockoutComponentTemplate; + viewModel?: (params: any) => any; +} + +interface KnockoutComponentRegisterStringTemplate { + template: string; + viewModel?: KnockoutComponentConfigViewModel; +} + +interface KnockoutComponentRegisterStringTemplateFnViewModel { + template: string; + viewModel?: (params: any) => any; +} + +interface KnockoutComponentConfigViewModel { + instance?: any; + createViewModel? (params?: any, componentInfo?: KnockoutComponentInfo): any; + require?: string; +} + +interface KnockoutComponentTemplate { + // specify element id (string) or a node + element?: any; + // AMD module load + require?: string; +} + +interface KnockoutComponentInfo { + element: any; +} +/* end register overloads */ interface KnockoutComponentDefinition { template: Node[]; createViewModel?(params: any, options: { element: Node; }): any; diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 6d4c9e25d..82b5aa25c 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -602,4 +602,49 @@ function test_allBindingsAccessor() { var fnAccessorBinding = allBindingsAccessor().myBindingName; } }; +} + +function test_Components() { + + function test_Register() { + // test all possible ko.components.register() overloads + var nodeArray = [new Node, new Node]; + var singleNode = new Node; + + // ------- string-templates with different viewmodel overloads: + + // string template and inline function (commonly used in examples) + ko.components.register("name", { template: "string-template", viewModel: function (params) { return null; } }); + + // string template and instance vm + ko.components.register("name", { template: "string-template", viewModel: { instance: null } }); + + // string template and createViewModel factory method + ko.components.register("name", { template: "string-template", viewModel: { createViewModel: function (params: any, componentInfo: KnockoutComponentInfo) { return null; } } }); + + // string template and require module vm + ko.components.register("name", { template: "string-template", viewModel: { require: "module" } }); + + // ------- non-string templates + + // viewmodel as function and four types of template + ko.components.register("name", { template: { element: "elementID" }, viewModel: function (params) { return null; } }); + // Node template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { element: singleNode }, viewModel: function (params) { return null; } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: nodeArray, viewModel: function (params) { return null; } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { require: "module" }, viewModel: function (params) { return null; } }); + + // viewmodel as object, and four types of non-string tempalte + ko.components.register("name", { template: { element: "elementID" }, viewModel: { instance: null } }); + // Node template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { element: singleNode }, viewModel: { instance: null } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: nodeArray, viewModel: { instance: null } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { require: "module" }, viewModel: { instance: null } }); + + // + } } \ No newline at end of file From 7878659ee9875b6b2ed49509b262bd63a84ca0eb Mon Sep 17 00:00:00 2001 From: HowardRichards Date: Fri, 29 Aug 2014 14:22:34 +0100 Subject: [PATCH 014/149] Fixed valerie.d.ts re-added missing reference for knockout --- valerie/valerie.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/valerie/valerie.d.ts b/valerie/valerie.d.ts index 1514f3a4d..d22227ecc 100644 --- a/valerie/valerie.d.ts +++ b/valerie/valerie.d.ts @@ -1,9 +1,10 @@ + // Type definitions for valerie // Project: https://github.com/davewatts/valerie // Definitions by: Howard Richards // Definitions: https://github.com/borisyankov/DefinitelyTyped - +/// /** * From 5b4566963904b30f0e09a638f0ec128896d04e80 Mon Sep 17 00:00:00 2001 From: Howard Richards Date: Fri, 29 Aug 2014 14:28:38 +0100 Subject: [PATCH 015/149] Removed blank line 1 --- valerie/valerie.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/valerie/valerie.d.ts b/valerie/valerie.d.ts index d22227ecc..8e9d12988 100644 --- a/valerie/valerie.d.ts +++ b/valerie/valerie.d.ts @@ -1,4 +1,3 @@ - // Type definitions for valerie // Project: https://github.com/davewatts/valerie // Definitions by: Howard Richards @@ -725,4 +724,4 @@ declare module Valerie.Rules { Todo: add classes in valerie.rules namespace */ -} \ No newline at end of file +} From dade09fe9d0b5205c4c2f5de9f185f64e59c701c Mon Sep 17 00:00:00 2001 From: HowardRichards Date: Fri, 29 Aug 2014 14:33:47 +0100 Subject: [PATCH 016/149] added any to options type Fixed failing run --- valerie/valerie.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/valerie/valerie.d.ts b/valerie/valerie.d.ts index 8e9d12988..abe5aea28 100644 --- a/valerie/valerie.d.ts +++ b/valerie/valerie.d.ts @@ -316,7 +316,7 @@ declare module Valerie { // - either parameter can be omitted and a clone of the other parameter will be returned // - the merge is shallow // - array properties are shallow cloned - mergeOptions(defaultOptions: ValidationOptions, options): ValidationOptions; + mergeOptions(defaultOptions: ValidationOptions, options:any): ValidationOptions; } From 0ea44c6c0a505d4bb3a61b152ccafc9006f47c9e Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Tue, 2 Sep 2014 21:02:39 +0200 Subject: [PATCH 017/149] Added HowlerJS Definitions https://github.com/goldfire/howler.js --- howlerjs/howler-tests.ts | 35 +++++++++++++++++++ howlerjs/howler.d.ts | 73 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 howlerjs/howler-tests.ts create mode 100644 howlerjs/howler.d.ts diff --git a/howlerjs/howler-tests.ts b/howlerjs/howler-tests.ts new file mode 100644 index 000000000..aff0df926 --- /dev/null +++ b/howlerjs/howler-tests.ts @@ -0,0 +1,35 @@ +/** + * howler-tests.ts + * Created by xperiments on 02/09/14. + */ +/// + + +Howler.codecs('ogg'); +Howler.iOSAutoEnable = true; +var sound = new Howl({ + urls: ['sound.mp3'] +}).play(); + + +var sound = new Howl({ + urls: ['sound.mp3', 'sound.ogg', 'sound.wav'], + autoplay: true, + loop: true, + volume: 0.5, + onend: function() { + console.log('Finished!'); + } +}); + +var sound = new Howl({ + urls: ['sounds.mp3', 'sounds.ogg'], + sprite: { + blast: [0, 1000], + laser: [2000, 3000], + winner: [4000, 7500] + } +}); + +// shoot the laser! +sound.play('laser'); \ No newline at end of file diff --git a/howlerjs/howler.d.ts b/howlerjs/howler.d.ts new file mode 100644 index 000000000..577c9fd78 --- /dev/null +++ b/howlerjs/howler.d.ts @@ -0,0 +1,73 @@ +// Type definitions for howler.js v1.1.25 +// Project: https://github.com/goldfire/howler.js +// Definitions by: Pedro Casaubon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare class HowlerGlobal { + mute(): HowlerGlobal; + unmute(): HowlerGlobal; + volume(): number; + volume(volume: number): HowlerGlobal; + codecs(extension: string): boolean; + iOSAutoEnable: boolean; +} + +declare var Howler: HowlerGlobal; + + +interface IHowlCallback { + (): void; +} +interface IHowlSoundSpriteDefinition { + [name: string]: number[] +} +interface IHowlProperties { + autoplay?: boolean; + buffer?: boolean; + format?: string; + loop?: boolean; + sprite?: IHowlSoundSpriteDefinition; + volume?: number; + urls?: string[]; + onend?: IHowlCallback; + onload?: IHowlCallback; + onloaderror?: IHowlCallback; + onpause?: IHowlCallback; + onplay?: IHowlCallback; +} + + +declare class Howl { + + autoplay: Boolean; + buffer: Boolean; + format: string; + rate: number; + model: string; + onend: IHowlCallback; + onload: IHowlCallback; + onloaderror: IHowlCallback; + onpause: IHowlCallback; + onplay: IHowlCallback; + constructor(properties: IHowlProperties); + play(sprite?: string, callback?: (soundId: number) => void): Howl; + pause(soundId?: number): Howl; + stop(soundId?: number): Howl; + mute(soundId?: number): Howl; + unmute(soundId?: number): Howl; + fade(from: number, to: number, duration: number, callback?: IHowlCallback, soundId?: number): Howl; + loop(): boolean; + loop(loop: boolean): Howl; + pos(position?: number, soundId?: number): number; + pos3d(x: number, y: number, z: number, soundId?: number): any; + sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition; + volume(): number; + volume(volume?: number, soundId?: number): Howl; + urls(): string[]; + urls(urls: string[]): Howl; + on(event: string, listener?: () => void): Howl; + off(event: string, listener?: () => void): Howl; + unload(): void; +} + From 4f8425580accc61defad55e2abb3f8ffd0773f91 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sat, 6 Sep 2014 19:12:08 -0700 Subject: [PATCH 018/149] Change highlight.js test for v8.x.x interface --- highlightjs/highlightjs-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/highlightjs/highlightjs-tests.ts b/highlightjs/highlightjs-tests.ts index 749be67cc..178687451 100644 --- a/highlightjs/highlightjs-tests.ts +++ b/highlightjs/highlightjs-tests.ts @@ -12,7 +12,7 @@ import hljs = require("highlight.js"); var code = "using System;\npublic class Test\n{\npublic static void Main()\n{\n// your code goes here\n}\n}"; var lang = "cs"; -hljs.tabReplace = " "; // 4 spaces +hljs.configure({ tabReplace: " " }) // 4 spaces var hl = hljs.highlight(lang, code).value; -hl = hljs.highlightAuto(code).value; \ No newline at end of file +hl = hljs.highlightAuto(code).value; From 0350affc37a4214b043d37a89ca75e2ef927e516 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sat, 6 Sep 2014 19:16:57 -0700 Subject: [PATCH 019/149] Move default highlight definition to 7.5.0 --- highlightjs/{highlightjs.d.ts => highlightjs-7.5.0.d.ts} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename highlightjs/{highlightjs.d.ts => highlightjs-7.5.0.d.ts} (98%) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs-7.5.0.d.ts similarity index 98% rename from highlightjs/highlightjs.d.ts rename to highlightjs/highlightjs-7.5.0.d.ts index d730029b5..725f78fbc 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs-7.5.0.d.ts @@ -1,4 +1,4 @@ -// Type definitions for highlight.js +// Type definitions for highlight.js v7.5.0 // Project: https://github.com/isagalaev/highlight.js // Definitions by: Niklas Mollenhauer // Definitions: https://github.com/borisyankov/DefinitelyTyped From 2382d22067c346c9f9e2a586a65a74f33c3a8401 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sat, 6 Sep 2014 19:42:10 -0700 Subject: [PATCH 020/149] Add definition for latest version of highlightjs --- highlightjs/highlightjs.d.ts | 125 +++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 highlightjs/highlightjs.d.ts diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts new file mode 100644 index 000000000..a4500bd95 --- /dev/null +++ b/highlightjs/highlightjs.d.ts @@ -0,0 +1,125 @@ +// Type definitions for highlight.js v8.2.0 +// Project: https://github.com/isagalaev/highlight.js +// Definitions by: Niklas Mollenhauer , Jeremy Hull +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "highlight.js" +{ + module hljs + { + export function highlight( + name: string, + value: string, + ignore_illegals?: boolean, + continuation?: boolean) : IHighlightResult + export function highlightAuto( + value: string, + languageSubset?: string[]) : IAutoHighlightResult + + export function fixMarkup(value: string) : string; + + export function highlightBlock(block: Node) : void; + + export function configure(options: IOptions): void; + + export function initHighlighting(): void; + export function initHighlightingOnLoad(): void; + + export function registerLanguage( + name: string, + language: IModeBase): void; + export function listLanguages(): string[]; + export function getLanguage(name: string): IMode; + + export function inherit(parent: Object, obj: Object): Object; + + // Common regexps + export var IDENT_RE: string; + export var UNDERSCORE_IDENT_RE: string; + export var NUMBER_RE: string; + export var C_NUMBER_RE: string; + export var BINARY_NUMBER_RE: string; + export var RE_STARTERS_RE: string; + + // Common modes + export var BACKSLASH_ESCAPE : IMode; + export var APOS_STRING_MODE : IMode; + export var QUOTE_STRING_MODE : IMode; + export var PHRASAL_WORDS_MODE : IMode; + export var C_LINE_COMMENT_MODE : IMode; + export var C_BLOCK_COMMENT_MODE : IMode; + export var HASH_COMMENT_MODE : IMode; + export var NUMBER_MODE : IMode; + export var C_NUMBER_MODE : IMode; + export var BINARY_NUMBER_MODE : IMode; + export var CSS_NUMBER_MODE : IMode; + export var REGEX_MODE : IMode; + export var TITLE_MODE : IMode; + export var UNDERSCORE_TITLE_MODE : IMode; + + export interface IHighlightResult + { + relevance: number; + language: string; + top: ICompiledMode; + value: string; + } + + export interface IAutoHighlightResult extends IHighlightResult + { + second_best?: IAutoHighlightResult; + } + + // Reference: + // https://github.com/isagalaev/highlight.js/blob/master/docs/reference.rst + export interface IModeBase + { + className?: string; + aliases?: string[]; + begin: string; + end?: string; + case_insensitive?: boolean; + beginKeyword?: string; + endsWithParent?: boolean; + lexems?: string; + illegal?: string; + excludeBegin?: boolean; + excludeEnd?: boolean; + returnBegin?: boolean; + returnEnd?: boolean; + starts?: string; + subLanguage?: string; + subLanguageMode?: string; + relevance?: number; + variants?: IMode[]; + } + + export interface IMode extends IModeBase + { + keywords?: string; + contains?: IMode[]; + } + + export interface ICompiledMode extends IModeBase + { + compiled: boolean; + contains?: ICompiledMode[]; + keywords?: Object[]; + beginRe: RegExp; + endRe?: RegExp; + lexemesRe?: RegExp; + illegalRe?: RegExp; + terminators: RegExp; + terminator_end?: string; + } + + export interface IOptions + { + classPrefix?: string; + tabReplace?: string; + useBR?: boolean; + languages?: string[]; + } + } + export = hljs; +} From 41f207409664fc7b1f6c887c14da17c43b6f0557 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sat, 6 Sep 2014 19:42:31 -0700 Subject: [PATCH 021/149] Add myself to CONTRIBUTORS --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ec2eec5d8..d358b42ce 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -127,7 +127,7 @@ All definitions files include a header with the author and editors, so at some p * [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) * [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) * [Highland](http://highlandjs.org/) (by [Bart van der Schoor](https://github.com/Bartvds/)) -* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) +* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee) and [Jeremy Hull](https://github.com/sourrust)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) * [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction)) From 226d9e8344761a081b2c88ccb4b90d7ad9b7a198 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sun, 7 Sep 2014 21:26:48 -0700 Subject: [PATCH 022/149] Add missing semicolon in test --- highlightjs/highlightjs-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highlightjs/highlightjs-tests.ts b/highlightjs/highlightjs-tests.ts index 178687451..233d1fa3e 100644 --- a/highlightjs/highlightjs-tests.ts +++ b/highlightjs/highlightjs-tests.ts @@ -12,7 +12,7 @@ import hljs = require("highlight.js"); var code = "using System;\npublic class Test\n{\npublic static void Main()\n{\n// your code goes here\n}\n}"; var lang = "cs"; -hljs.configure({ tabReplace: " " }) // 4 spaces +hljs.configure({ tabReplace: " " }); // 4 spaces var hl = hljs.highlight(lang, code).value; hl = hljs.highlightAuto(code).value; From 7f64b066967e45bdf8fffc45c3236159a07787da Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sun, 7 Sep 2014 21:28:20 -0700 Subject: [PATCH 023/149] Fix indention for highlightAuto parameters --- highlightjs/highlightjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index a4500bd95..90a364d5b 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -13,8 +13,8 @@ declare module "highlight.js" ignore_illegals?: boolean, continuation?: boolean) : IHighlightResult export function highlightAuto( - value: string, - languageSubset?: string[]) : IAutoHighlightResult + value: string, + languageSubset?: string[]) : IAutoHighlightResult export function fixMarkup(value: string) : string; From f2a4d8eed4364a95efc3faa2976979447e805ed5 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Sun, 7 Sep 2014 21:35:14 -0700 Subject: [PATCH 024/149] Add missing semicolons in definition --- highlightjs/highlightjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index 90a364d5b..f200d6e99 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -11,10 +11,10 @@ declare module "highlight.js" name: string, value: string, ignore_illegals?: boolean, - continuation?: boolean) : IHighlightResult + continuation?: boolean) : IHighlightResult; export function highlightAuto( value: string, - languageSubset?: string[]) : IAutoHighlightResult + languageSubset?: string[]) : IAutoHighlightResult; export function fixMarkup(value: string) : string; From 40c1185fd2c93824c3fc70b91dcf46d981579f89 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Thu, 11 Sep 2014 12:33:11 -0700 Subject: [PATCH 025/149] Remove private RegExp vars --- highlightjs/highlightjs.d.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index f200d6e99..e832d8273 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -105,10 +105,6 @@ declare module "highlight.js" compiled: boolean; contains?: ICompiledMode[]; keywords?: Object[]; - beginRe: RegExp; - endRe?: RegExp; - lexemesRe?: RegExp; - illegalRe?: RegExp; terminators: RegExp; terminator_end?: string; } From 86e0dfb68f1bf5a3280d46ffebc5502a01a7534c Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Thu, 11 Sep 2014 12:34:36 -0700 Subject: [PATCH 026/149] Change ICompiledMode keyword to Object --- highlightjs/highlightjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index e832d8273..58ea7688b 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -104,7 +104,7 @@ declare module "highlight.js" { compiled: boolean; contains?: ICompiledMode[]; - keywords?: Object[]; + keywords?: Object; terminators: RegExp; terminator_end?: string; } From 327079de90a24ac11747cf1dd921bef44d6fa651 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Thu, 11 Sep 2014 13:22:50 -0700 Subject: [PATCH 027/149] Change keywords in IMode to any The keywords key can be represented by either a string or an object, see: http://highlightjs.readthedocs.org/en/latest/language-guide.html#keywords --- highlightjs/highlightjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index 58ea7688b..97db22d7c 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -96,7 +96,7 @@ declare module "highlight.js" export interface IMode extends IModeBase { - keywords?: string; + keywords?: any; contains?: IMode[]; } From 4acd5163e84777da848c8dace3cbe121b6244c8c Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Thu, 11 Sep 2014 13:24:09 -0700 Subject: [PATCH 028/149] Add HLJSStatic for registerLanguage use --- highlightjs/highlightjs.d.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index 97db22d7c..c782f7bc7 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -70,6 +70,35 @@ declare module "highlight.js" second_best?: IAutoHighlightResult; } + export interface HLJSStatic + { + inherit(parent: Object, obj: Object): Object; + + // Common regexps + IDENT_RE: string; + UNDERSCORE_IDENT_RE: string; + NUMBER_RE: string; + C_NUMBER_RE: string; + BINARY_NUMBER_RE: string; + RE_STARTERS_RE: string; + + // Common modes + BACKSLASH_ESCAPE : IMode; + APOS_STRING_MODE : IMode; + QUOTE_STRING_MODE : IMode; + PHRASAL_WORDS_MODE : IMode; + C_LINE_COMMENT_MODE : IMode; + C_BLOCK_COMMENT_MODE : IMode; + HASH_COMMENT_MODE : IMode; + NUMBER_MODE : IMode; + C_NUMBER_MODE : IMode; + BINARY_NUMBER_MODE : IMode; + CSS_NUMBER_MODE : IMode; + REGEX_MODE : IMode; + TITLE_MODE : IMode; + UNDERSCORE_TITLE_MODE : IMode; + } + // Reference: // https://github.com/isagalaev/highlight.js/blob/master/docs/reference.rst export interface IModeBase From e70ce374bad09523508b5b3f2bc4cace033a9745 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Thu, 11 Sep 2014 13:24:50 -0700 Subject: [PATCH 029/149] Change registerLanguage definition to a function --- highlightjs/highlightjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index c782f7bc7..b34d69508 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -27,7 +27,7 @@ declare module "highlight.js" export function registerLanguage( name: string, - language: IModeBase): void; + language: (hljs?: HLJSStatic) => IModeBase): void; export function listLanguages(): string[]; export function getLanguage(name: string): IMode; From 619bb1e40b86583443d947d93863b264a13dd00f Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Thu, 11 Sep 2014 13:26:28 -0700 Subject: [PATCH 030/149] No longer require begin This is so registerLanguage parameter can return the IModeBase type, with is essentually the language definition. --- highlightjs/highlightjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index b34d69508..91675cfa6 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -105,7 +105,7 @@ declare module "highlight.js" { className?: string; aliases?: string[]; - begin: string; + begin?: string; end?: string; case_insensitive?: boolean; beginKeyword?: string; From 938f6b41bc09b0398dffa8921897d189acf76b5d Mon Sep 17 00:00:00 2001 From: koresar Date: Sun, 14 Sep 2014 20:21:54 +1000 Subject: [PATCH 031/149] 'stampit' module definitions and tests. --- CONTRIBUTORS.md | 1 + stampit/stampit-tests.ts | 168 +++++++++++++++++++++++++++++++++++++++ stampit/stampit.d.ts | 140 ++++++++++++++++++++++++++++++++ 3 files changed, 309 insertions(+) create mode 100644 stampit/stampit-tests.ts create mode 100644 stampit/stampit.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..6b14eb0d1 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -342,6 +342,7 @@ All definitions files include a header with the author and editors, so at some p * [source-map](https://github.com/mozilla/source-map) (by [Morten Houston Ludvigsen](https://github.com/MortenHoustonLudvigsen)) * [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov)) * [sqlite3](https://github.com/mapbox/node-sqlite3) (by [Nick Malaguti](https://github.com/nmalaguti)) +* [stampit](https://github.com/ericelliott/stampit) (by [Vasyl Boroviak](https://github.com/koresar)) * [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame)) * [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone)) diff --git a/stampit/stampit-tests.ts b/stampit/stampit-tests.ts new file mode 100644 index 000000000..4354461b7 --- /dev/null +++ b/stampit/stampit-tests.ts @@ -0,0 +1,168 @@ +/// + +var a = stampit().enclose(() => { + var a = 'a'; + this.getA = () => { + return a; + }; +}); +a(); // Object -- so far so good. +a().getA(); // "a" + + +var b = stampit().enclose(function () { + var a = 'b'; + this.getB = function () { + return a; + }; +}); + + +var c = stampit.compose(a, b); +var foo = c(); // we won't throw this one away... +foo.getA(); // "a" +foo.getB(); // "b" + + +// Some more privileged methods, with some private data. +// Use stampit.mixIn() to make this feel declarative: +var availability = stampit().enclose(function () { + var isOpen = false; // private + + return stampit.mixIn(this, { + open: function open() { + isOpen = true; + return this; + }, + close: function close() { + isOpen = false; + return this; + }, + isOpen: function isOpenMethod() { + return isOpen; + } + }); +}); +// Hre's a mixin with public methods, and some state: +var membership = stampit({ + members: {}, + add: function (member: any) { + this.members[member.name] = member; + return this; + }, + getMember: function (name: any) { + return this.members[name]; + } + }, + { + members: {} + }); +// Let's set some defaults: +var defaults = stampit().state({ + name: 'The Saloon', + specials: 'Whisky, Gin, Tequila' +}); + +// Classical inheritance has nothing on this. No parent/child coupling. No deep inheritance hierarchies. +// Just good, clean code reusability. +var bar = stampit.compose(defaults, availability, membership); +// Note that you can override state on instantiation: +var myBar = bar({name: 'Moe\'s'}); +// Silly, but proves that everything is as it should be. +myBar.add({name: 'Homer' }).open().getMember('Homer'); + + + +var myStamp = stampit().methods({ + foo: function () { + return 'foo'; + }, + methodOverride: function () { + return false; + } +}).methods({ + bar: function () { + return 'bar' + }, + methodOverride: function () { + return true; + } +}); + +myStamp.state({ + foo: {bar: 'bar'}, + stateOverride: false +}).state({ + bar: 'bar', + stateOverride: true +}); + +myStamp.enclose(function () { + var secret = 'foo'; + + this.getSecret = function () { + return secret; + }; +}).enclose(function () { + this.a = true; +}).enclose({ + bar: function bar() { + this.b = true; + } +}, { + baz: function baz() { + this.c = true; + } +}); + +var obj = myStamp.create(); +obj.getSecret && obj.a && obj.b && obj.c; // true + +var newStamp = stampit(null, { defaultNum: 1 }).compose(myStamp); + + + +var obj1 = stampit().methods({ + a: function () { return 'a'; } +}, { + b: function () { return 'b'; } +}).create(); + +var obj2 = stampit().state({ + a: 'a' +}, { + b: 'b' +}).create(); + +var obj = defaults.compose(newStamp, membership, availability).create(); + + + +// The old constructor / class thing... +var Constructor = function Constructor() { + this.thing = 'initialized'; +}; +Constructor.prototype.foo = function foo() { return 'foo'; }; + +// The conversion +var oldskool = stampit.convertConstructor(Constructor); + +// A new stamp to compose with... +var newskool = stampit().methods({ + bar: function bar() { return 'bar'; } + // your methods here... +}).enclose(function () { + this.baz = 'baz'; +}); + +// Now you can compose those old constructors just like you could +// with any other stamp... +var myThing = stampit.compose(oldskool, newskool); + +var t = myThing(); + +t.thing; // 'initialized', + +t.foo(); // 'foo', + +t.bar(); // 'bar' \ No newline at end of file diff --git a/stampit/stampit.d.ts b/stampit/stampit.d.ts new file mode 100644 index 000000000..7cd82a6d4 --- /dev/null +++ b/stampit/stampit.d.ts @@ -0,0 +1,140 @@ +// Type definitions for stampit +// Project: https://github.com/ericelliott/stampit +// Definitions by: Vasyl Boroviak +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var stampit: stampit.Stampit; + +declare module stampit { + interface Stampit { + /** + * Return a factory function that will produce new objects using the + * prototypes that are passed in or composed. + * @param methods Object containing methods which will be part of + * the .prototype of a resulting object. + * @param state Object which properties will be copied over to + * a resulting object. + * @param enclose Function properties of these objects will be run + * once per each new object. + * */ + (methods?:{}, state?:{}, enclose?:{(...encloseArgs:any[]): void}[]):stampit.Stamp; + + /** + * Take two or more Stamps and combine them to produce a new Stamp. + * Combining overrides properties with last-in priority. + * @param stamps Stamps produced by stampit. + * @return A new Stamp made of all the given. + */ + compose(...stamps:Stamp[]): Stamp; + + /** + * Take a destination object followed by one or more source objects, + * and copy the source object properties to the destination object, + * with last in priority overrides. + * @param destination An object to copy properties to. + * @param source Objects to copy properties from. + * @return The destination object. + */ + mixIn(destination:any, ...source:any[]): any; + + /** + * Alias for mixIn. + * Take a destination object followed by one or more source objects, + * and copy the source object properties to the destination object, + * with last in priority overrides. + * @param destination An object to copy properties to. + * @param source Objects to copy properties from. + * @return The destination object. + */ + extend(destination:any, ...source:any[]): any; + + /** + * Check if an object is a Stamp. + * @param obj An object to check. + * @return true if the object is a Stamp; otherwise - false. + */ + isStamp(obj:any): boolean; + + /** + * Take an old-fashioned JS constructor and return a Stamp + * that you can freely compose with other Stamps. + * @param Constructor Old-fashioned constructor function. + * @return A new Stamp based on the given constructor. + */ + convertConstructor(Constructor:any): Stamp; + } + + /** + * A factory function that will produce new objects using the + * prototypes that are passed in or composed. + */ + export interface Stamp { + (state?:{}, ...encloseArgs:any[]): any; + + /** + * + * @param state State passed + * @param encloseArgs + * @return A new object composed of the Stamps and prototypes provided. + */ + create(state?:{}, ...encloseArgs:any[]): any; + + /** + * An object map containing the fixed prototypes. + */ + fixed: Fixed; + + /** + * Add methods to the methods prototype. Chainable. + * @param methods Object(s) containing methods which will be part of + * the .prototype of a resulting object. + * @return Self. + */ + methods(...methods:{}[]): Stamp; + + /** + * Add properties to the state prototype. Chainable. + * @param states Object(s) which properties will be copied over to + * a resulting object. + * @return Self. + */ + state(...states:{}[]): Stamp; + + /** + * Add properties to the state prototype. Chainable. + * @param functions These function will be run once per each new object. + * @return Self. + */ + enclose(...functions:{(...encloseArgs:any[]): void}[]): Stamp; + + /** + * Add properties to the state prototype. Chainable. + * @param methods Function properties of these objects will be run + * once per each new object. + * @return Self. + */ + enclose(...methods:{}[]): Stamp; + + /** + * Take one or more Stamps and + * combine them with `this` to produce and return a new factory. + * Combining overrides properties with last-in priority. + * @param stamps Stampit factories, aka Stamps. + * @return A new Stamp composed from arguments and `this`. + */ + compose(...stamps:Stamp[]): Stamp; + } + + /** + * An object map containing the fixed prototypes. + */ + interface Fixed { + methods: {}; + state: {}; + enclose: {(...encloseArgs:any[]): void}[]; + } +} + +declare module "stampit" { + export = stampit; +} \ No newline at end of file From 34da00610a3691c28364905d13a83d8a607a211f Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Sun, 14 Sep 2014 22:25:00 +0200 Subject: [PATCH 032/149] Big update of Azure SDK for Node definitions --- node-azure/azure.d.ts | 1576 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 1516 insertions(+), 60 deletions(-) diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index 95ff46c25..05cb58dea 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -1,6 +1,8 @@ -// Type definitions for Azure SDK for Node - v0.6.10 +// Type definitions for Azure SDK for Node - v0.9.16 // Project: https://github.com/WindowsAzure/azure-sdk-for-node -// Definitions by: Andrew Gaspar , Anti Veeranna +// Definitions by: Andrew Gaspar , +// Anti Veeranna , +// Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -10,6 +12,8 @@ */ declare module "azure" { import events = require("events"); + import stream = require("stream"); + import url = require("url"); //#region Services export class TableService extends BatchServiceClient { @@ -18,6 +22,8 @@ declare module "azure" { static incorrectTableQuery: string; static incorrectPartitionErr: string; + //#region Constructors + /** * Creates a new TableService object. * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. @@ -48,29 +54,42 @@ declare module "azure" { */ constructor(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string); - getServiceProperties(callback?: (error: any, servicePropertiesResult: any, response: any) => void ): void; - getServiceProperties(options: TimeoutIntervalOptions, callback?: (error: any, servicePropertiesResult: any, response: any) => void ): void; + //#endregion - setServiceProperties(serviceProperties: any, options: TimeoutIntervalOptions, callback?: Function): void; + //#region Service Methods - getTable(table: string, callback?: TableRequestCallback ): void; - getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback ): void; + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; - createTable(table: string, callback?: TableRequestCallback ): void; - createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback ): void; + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback ): void; + //#endregion + + //#region Table Methods + + getTable(table: string, callback?: TableRequestCallback): void; + getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; + + createTable(table: string, callback?: TableRequestCallback): void; + createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; + + createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback): void; createTableIfNotExists(table: string, options: TimeoutIntervalOptions, callback?: CreateTableIfNotExistsCallback): void; - deleteTable(table: string, callback?: DeleteTableCallback ): void; - deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback ): void; + deleteTable(table: string, callback?: DeleteTableCallback): void; + deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback): void; - queryTables(callback?: QueryTablesCallback ): void; - queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback ): void; + queryTables(callback?: QueryTablesCallback): void; + queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback): void; + + //#endregion + + //#region Entities Methods + + queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback): void; + queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback): void; - queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback ): void; - queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback ): void; - queryEntities(tableQuery: TableQuery, callback?: QueryEntitiesCallback): void; queryEntities(tableQuery: TableQuery, options: TimeoutIntervalOptions, callback?: QueryEntitiesCallback): void; @@ -91,14 +110,513 @@ declare module "azure" { deleteEntity(tableName: string, entityDescriptor: Entity, callback?: DeleteEntityCallback): void; deleteEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: DeleteEntityCallback): void; + + //#endregion } - export class BlobService { + export class BlobService extends StorageServiceClient { + singleBlobPutThresholdInBytes: number; + parallelOperationThreadCount: number; + SpeedSummary: typeof SpeedSummary; + + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account’s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account’s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Containers Methods + + /** + * Lists a segment containing a collection of container items under the specified account. + */ + listContainers(callback: ListContainersCallback): void; + listContainers(options: ListContainersOptions, callback: ListContainersCallback): void; + + /** + * Creates a new container under the specified account. + * If a container with the same name already exists, the operation fails. + */ + createContainer(container: string, callback: StorageCallback): void; + createContainer(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Creates a new container under the specified account if the container does not exists. + */ + createContainerIfNotExists(container: string, callback: StorageCallback): void; + createContainerIfNotExists(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Retrieves a container and its properties from a specified account. + */ + getContainerProperties(container: string, callback: StorageCallback): void; + getContainerProperties(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Returns all user-defined metadata for the container. + */ + getContainerMetadata(container: string, callback: StorageCallback): void; + getContainerMetadata(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets the container's metadata. + */ + setContainerMetadata(container: string, metadata: StorageMetadata, callback: StorageCallback): void; + setContainerMetadata(container: string, metadata: StorageMetadata, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Gets the container's ACL. + */ + getContainerAcl(container: string, callback: StorageCallback): void; + getContainerAcl(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Updates the container's ACL. + */ + setContainerAcl(container: string, publicAccessLevel: string, callback: StorageCallback): void; + setContainerAcl(container: string, publicAccessLevel: string, options: StorageAclOptions, callback: StorageCallback): void; + + /** + * Marks the specified container for deletion. + * The container and any blobs contained within it are later deleted during garbage collection. + */ + deleteContainer(container: string, callback: StorageCallbackVoid): void; + deleteContainer(container: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Blob Methods + + /** + * Lists all of the blobs in the given container. + */ + listBlobs(container: string, callback: ListBlobsCallback): void; + listBlobs(container: string, options: ListBlobsOptions, callback: ListBlobsCallback): void; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. + * It does not return or modify the content of the blob. + */ + getBlobProperties(container: string, blob: string, callback: StorageCallback): void; + getBlobProperties(container: string, blob: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined properties for the specified blob or snapshot. + * It does not return or modify the content of the blob. + */ + setBlobProperties(container: string, blob: string, callback: StorageCallback): void; + setBlobProperties(container: string, blob: string, options: SetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs + * It does not return or modify the content of the blob. + */ + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, callback: StorageCallback): void; + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Provides a stream to read from a blob. + */ + getBlob(container: string, blob: string, callback: StorageCallback): stream.Readable; + getBlob(container: string, blob: string, options: ReadBlobOptions, callback: StorageCallback): stream.Readable; + + /** + * Downloads a blob into a file. + */ + getBlobToFile(container: string, blob: string, localFileName: string, callback: StorageCallback): void; + getBlobToFile(container: string, blob: string, localFileName: string, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a stream. + */ + getBlobToStream(container: string, blob: string, stream: stream.Writable, callback: StorageCallback): void; + getBlobToStream(container: string, blob: string, stream: stream.Writable, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a text string. + */ + getBlobToText(container: string, blob: string, callback: GetBlobToTextCallback): void; + getBlobToText(container: string, blob: string, options: ReadBlobOptions, callback: GetBlobToTextCallback): void; + + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + */ + deleteBlob(container: string, blob: string, callback: StorageCallback): void; + deleteBlob(container: string, blob: string, options: DeleteBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + createBlobSnapshot(container: string, blob: string, callback: StorageCallback): void; + createBlobSnapshot(container: string, blob: string, options: BlobSnapshotOptions, callback: StorageCallback): void; + + /** + * Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. + */ + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, callback: StorageCallback): void; + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, options: CopyBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + abortCopyBlob(container: string, blob: string, copyId: string, callback: StorageCallbackVoid): void; + abortCopyBlob(container: string, blob: string, copyId: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + /** + * Retrieves a shared access signature token. + */ + generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Retrieves a blob or container URL. + */ + getBlobUrl(container: string): string; + getBlobUrl(container: string, blob: string): string; + getBlobUrl(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Uploads a blob. + */ + createBlob(container: string, blob: string, blobType: string, callback: StorageCallback): stream.Writable; + createBlob(container: string, blob: string, blobType: string, options: UploadBlockBlobOptions, callback: StorageCallback): stream.Writable; + + //#endregion + + //#region Page Blob Methods + + /** + * Creates a page blob of the specified length. + */ + createPageBlob(container: string, blob: string, length: number, callback: StorageCallbackVoid): void; + createPageBlob(container: string, blob: string, length: number, options: SetBlobPropertiesOptions, callback: StorageCallbackVoid): void; + + /** + * Updates a page blob from a stream. + */ + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Updates a page blob from a text string. + */ + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Lists page ranges. + * Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + */ + listBlobRegions(container: string, blob: string, callback: StorageCallback): void; + listBlobRegions(container: string, blob: string, options: PageRangeOptions, callback: StorageCallback): void; + + /** + * Clears a range of pages. + */ + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, callback: StorageCallbackVoid): void; + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, options: LeaseAccessConditionsOptions, callback: StorageCallbackVoid): void; + + /** + * Resizes a page blob. + */ + resizePageBlob(container: string, blob: string, size: number, callback: StorageCallback): void; + resizePageBlob(container: string, blob: string, size: number, options: LeaseAccessConditionsOptions, callback: StorageCallback): void; + + /** + * Sets the page blob's sequence number. + */ + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, callback: StorageCallback): void; + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + //#endregion + + //#region Block Blob Methods + + /** + * Uploads a block blob from file. + */ + putBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + putBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a stream. + */ + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a text string. + */ + createBlockBlobFromText(container: string, blob: string, text: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromText(container: string, blob: string, text: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, callback: StorageCallbackVoid): void; + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, callback: StorageCallbackVoid): void; + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written to the server in a prior + * createBlock operation. + */ + commitBlobBlocks(container: string, blob: string, blockList: BlockList, callback: StorageCallback): void; + commitBlobBlocks(container: string, blob: string, blockList: BlockList, options: CreateBlockOptions, callback: StorageCallback): void; + + /** + * Retrieves the list of blocks that have been uploaded as part of a block blob. + */ + listBlobBlocks(container: string, blob: string, blockListType: string, callback: StorageCallback): void; + listBlobBlocks(container: string, blob: string, blockListType: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Generate a random block id prefix. + */ + generateBlockIdPrefix(): string; + /** + * Get a block id according to prefix and block number. + */ + getBlockId(prefix: string, number: number): string; + + //#endregion + + //#region Lease Methods + + /** + * Acquires a new lease. + * If container and blob are specified, acquires a blob lease. + * Otherwise, if only container is specified and blob is null, acquires a container lease. + */ + acquireLease(container: string, blob: string, callback: StorageCallback): void; + acquireLease(container: string, blob: string, options: LeaseOptions, callback: StorageCallback): void; + + /** + * Renews an existing lease. + * If container and blob are specified, renews the blob lease. + * Otherwise, if only container is specified and blob is null, renews the container lease. + */ + renewLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + renewLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Releases the lease. + * If container and blob are specified, releases the blob lease. + * Otherwise, if only container is specified and blob is null, releases the container lease. + */ + releaseLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + releaseLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. + * If container and blob are specified, breaks the blob lease. + * Otherwise, if only container is specified and blob is null, breaks the container lease. + */ + breakLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + breakLease(container: string, blob: string, leaseId: string, options: BreakLeaseOptions, callback: StorageCallback): void; + + //#endregion } - export class QueueService { + export class QueueService extends StorageServiceClient { + authenticationProvider: SharedKey; + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account’s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account’s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Queue Methods + + /** + * Lists all queues under the given account. + */ + listQueues(callback: ListQueuesCallback): void; + listQueues(options: ListQueuesOptions, callback: ListQueuesCallback): void; + + /** + * Creates a new queue under the given account. + */ + createQueue(queue: string, callback: StorageCallback): void; + createQueue(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Creates a new queue under the given account if it doesn't exist. + */ + createQueueIfNotExists(queue: string, callback: StorageCallback): void; + createQueueIfNotExists(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Permanently deletes the specified queue. + */ + deleteQueue(queue: string, callback: StorageCallback): void; + deleteQueue(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Returns queue properties, including user-defined metadata. + */ + getQueueMetadata(queue: string, callback: StorageCallback): void; + getQueueMetadata(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. + */ + setQueueMetadata(queue: string, metadata: StorageMetadata, callback: StorageCallback): void; + setQueueMetadata(queue: string, metadata: StorageMetadata, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + //#endregion + + //#region Message Methods + + /** + * Adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message + * invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request + * with UTF-8 encoding. The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size + * for previous versions. + */ + createMessage(queue: string, messageText: string, callback: StorageCallback): void + createMessage(queue: string, messageText: string, options: CreateQueueMessageOptions, callback: StorageCallback): void + + /** + * Retrieves a message from the queue and makes it invisible to other consumers. + */ + getMessages(queue: string, callback: StorageCallback): void; + getMessages(queue: string, options: GetQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Retrieves a message from the front of the queue, without changing the message visibility. + */ + peekMessages(queue: string, callback: StorageCallback): void; + peekMessages(queue: string, options: PeekQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Deletes a specified message from the queue. + */ + deleteMessage(queue: string, messageId: string, popreceipt: string, callback: StorageCallback): void + deleteMessage(queue: string, messageId: string, popreceipt: string, options: TimeoutIntervalOptions, callback: StorageCallback): void + + /** + * Clears all messages from the queue. + */ + clearMessages(queue: string, callback: StorageCallbackVoid): void; + clearMessages(queue: string, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + /** + * Deletes a specified message from the queue. + */ + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, callback: StorageCallback): void + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, options: UpdateQueueMessagesOptions, callback: StorageCallback): void + + //#endregion } export class ServiceBusService { @@ -116,6 +634,7 @@ declare module "azure" { export class SqlManagementService { } //#endregion + //#region Service Creators export function createTableService(): TableService; export function createTableService(connectionString: string): TableService; @@ -140,25 +659,122 @@ declare module "azure" { export function createSqlManagementService(subscriptionId: string, authentication: string, hostOptions: string): SqlManagementService; //#endregion + //#region RoleEnvironment + interface RoleEnvironmentInterface extends events.EventEmitter { - getCurrentRoleInstance(callback: (error: any, instance: any) => void): void; - getDeploymentId(callback: (error: any, id:string) => void): void; - isAvailable(callback: (error: any, available: boolean) => void): void; - isEmulated(callback: (error: any, emulated: boolean) => void): void; - getRoles(callback: (error: any, roles: any) => void): void; - getConfigurationSettings(callback: (error: any, settings: any) => void): void; - getLocalResources(callback: (error: any, resources: any) => void): void; - requestRecycle(callback: (error: any) => void): void; - setStatus(roleInstanceStatus: any, expirationUtc: any, callback: (error: any) => void): void; - clearStatus(callback: (error: any) => void): void; + incorrectCallbackErr: string; + clientId: string; + VersionEndpointFixedPath: string; + EnvironmentVariables: { + [key: string]: string; + VersionEndpointEnvironmentName: string; + }; + + /** + * Returns a RoleInstance object that represents the role instance + * in which this code is currently executing. + */ + getCurrentRoleInstance(callback: SimpleCallback): void; + + /** + * Returns the deployment ID that uniquely identifies the deployment in + * which this role instance is running. + */ + getDeploymentId(callback: SimpleCallback): void; + + /** + * Indicates whether the role instance is running in the Microsoft Azure + * environment. It is good practice to enclose any code that uses + * service runtime in the isAvailable callback. + */ + isAvailable(callback: SimpleCallback): void; + + /** + * Indicates whether the role instance is running in the development fabric. + */ + isEmulated(callback: SimpleCallback): void; + + /** + * Returns the set of Role objects defined for your service. + * Roles are defined in the service definition file. + */ + getRoles(callback: SimpleCallback>): void; + + /** + * Retrieves the settings in the service configuration file. + * + * A role's configuration settings are defined in the service definition file. + * Values for configuration settings are set in the service configuration file. + * For more information on configuration settings, see the [Service Definition Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758711.aspx) + * and [Service Configuration Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758710.aspx). + */ + getConfigurationSettings(callback: SimpleCallback>): void; + + /** + * Retrieves the set of named local storage resources, along with the path. + * For example, the DiagnosticStore resource which is defined for every role + * provides a location for runtime diagnostics and logs. + */ + getLocalResources(callback: SimpleCallback>): void; + + /** + * Requests that the current role instance be stopped and restarted. + * + * Before the role instance is recycled, the Microsoft Azure load balancer takes the role instance out of rotation. + * This ensures that no new requests are routed to the instance while it is restarting. + * + * A call to `RequestRecycle` initiates the normal shutdown cycle. Microsoft Azure raises the + * `Stopping` event and calls the `OnStop` method so that you can run the necessary code to + * prepare the instance to be recycled. + */ + requestRecycle(callback: ErrorCallback): void; + + /** + * Sets the status of the role instance. + * + * An instance may indicate that it is in one of two states: Ready or Busy. If an instance's state is Ready, it is + * prepared to receive requests from the load balancer. If the instance's state is Busy, it will not receive + * requests from the load balancer. + */ + setStatus(roleInstanceStatus: string, expirationUtc: Date, callback: ErrorCallback): void; + + /** + * Clears the status of the role instance. + * An instance may indicate that it has completed communicating status by calling this method. + */ + clearStatus(callback: ErrorCallback): void; } export var RoleEnvironment: RoleEnvironmentInterface; - + + //#endregion //#region Export of internal classes export class WebResource { + rawResponse: boolean; + queryString: Dictionary; + constructor(); + + get(path: string): WebResource; + put(path: string): WebResource; + post(path: string): WebResource; + merge(path: string): WebResource; + head(path: string): WebResource; + del(path: string): WebResource; + + withProperty(name: string, value: string): WebResource; + withRawResponse(rawResponse: boolean): WebResource; + withHeadersOnly(headersOnly: boolean): WebResource; + withQueryOption(name: string, value: string, defaultValue: string): WebResource; + withQueryOptions(queryOptions: Dictionary): WebResource; + withHeader(name: string, value: string): WebResource; + withHeaders(headers: Dictionary): WebResource; + withBody(body: any): WebResource; + addOptionalMetadataHeaders(metadata: StorageMetadata): WebResource; + + validResponse(statusCode: number): boolean; + pipeInput(inputStream: stream.Stream, destStream: stream.Stream): stream.Stream; } export class ServiceClient extends events.EventEmitter { @@ -185,12 +801,27 @@ declare module "azure" { performRequest(webResource: WebResource, outputData: string, options: any, callback: Function): void; performRequestOutputStream(webResource: WebResource, outputStream: any, options: any, callback: Function): void; performRequestInputStream(webResource: WebResource, outputData: string, inputStream: any, options: any, callback: Function): void; - withFilter(newFilter: { handle: (requestOptions: any, next: Function) => void; }): ServiceClient; + withFilter(newFilter: Filter): ServiceClient; parseMetadataHeaders(headers: any): any; isEmulated(): boolean; setProxy(proxyUrl: string, proxyPort: number): void; } + export class BatchServiceClient extends StorageServiceClient { + operations: any[]; + + constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); + beginBatch(): void; + isInBatch(): boolean; + rollback(): void; + hasOperations(): boolean; + addOperation(webResource: WebResource, outputData: any): void; + commitBatch(callback: (error: any, operationResponses: any[], response: any) => void): void; + commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void): void; + processResponse(responseObject: any, requestOperations: any[]): any[]; + processOperation(webResource: WebResource, rawResponse: string): any; + } + export class ServiceManagementClient { } @@ -208,77 +839,531 @@ declare module "azure" { toPath(): string; } - export class BatchServiceClient extends StorageServiceClient { - operations: any[]; + export class BlobResult { + blob: string; + container: string; - constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); - beginBatch(): void; - isInBatch(): boolean; - rollback(): void; - hasOperations(): boolean; - addOperation(webResource: WebResource, outputData: any): void; - commitBatch(callback: (error: any, operationResponses: any[], response: any) => void ): void; - commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void ): void; - processResponse(responseObject: any, requestOperations: any[]): any[]; - processOperation(webResource: WebResource, rawResponse: string): any; + etag: string; + lastModified: Date; + contentType: string; + contentEncoding: string; + contentLanguage: string; + contentMD5: string; + cacheControl: string; + contentRange: string; + contentTypeHeader: string; + contentEncodingHeader: string; + contentLanguageHeader: string; + contentMD5Header: string; + cacheControlHeader: string; + contentLength: number; + contentLengthHeader: number; + contentDisposition: string; + contentDispositionHeader: string; + range: string; + rangeHeader: string; + getContentMd5: string; + acceptRanges: string; + blobType: string; + leaseStatus: string; + leaseId: string; + leaseDuration: string; + leaseState: string; + sequenceNumber: string; + copyStatus: string; + copyCompletionTime: string; + copyStatusDescription: string; + copyId: string; + copyProgress: number; + requestId: string; + + metadata: StorageMetadata; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + + static parse(blobXml: any): BlobResult; + static setHeadersFromBlob(webResource: WebResource, blob: BlobResult); + + getPropertiesFromHeaders(headers: any): void; + } + + export class ContainerResult { + name: string; + publicAccessLevel: string; + + etag: string; + lastModified: Date; + leaseStatus: string; + leaseDuration: string; + leaseState: string; + requestId: string; + + metadata: StorageMetadata; + signedIdentifiers: SignedIdentifier[]; + + constructor(); + constructor(name: string); + constructor(name: string, publicAccessLevel: string); + + static parse(containerXml: any): ContainerResult; + + getPropertiesFromHeaders(headers: any): void; + } + + export class LeaseResult { + container: string; + blob: string; + id: string; + time: Date; + etag: string; + lastModified: Date; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + constructor(container: string, blob: string, id: string); + constructor(container: string, blob: string, id: string, time: Date); + + getPropertiesFromHeaders(header: any): void; + } + + export class QueueResult { + name: string; + metadata: StorageMetadata; + approximatemessagecount: number; + + constructor(); + constructor(name: string); + constructor(name: string, metadata: StorageMetadata); + + static parse(messageXml: any): QueueResult; + + getPropertiesFromHeaders(headers: any): void; + } + + export class QueueMessageResult { + queue: string; + messageid: string; + popreceipt: string; + metadata: StorageMetadata; + + constructor(); + constructor(queue: string); + constructor(queue: string, messageid: string); + constructor(queue: string, messageid: string, popreceipt: string); + constructor(queue: string, messageid: string, popreceipt: string, metadata: StorageMetadata); + + static serialize(messageJs: string): string; + static parse(messageXml: any): QueueMessageResult; + + getPropertiesFromHeaders(headers: any): void; + } + + export class SpeedSummary { + name: string; + totalSize: number; + completeSize: number; + + _startTime: Date; + _timeWindowInSeconds: number; + _timeWindow: number; + _totalWindowSize: number; + _speedTracks: number[]; + _speedTrackPtr: number; + + constructor(name: string); + + /** + * Get running seconds + */ + getElapsedSeconds(): string; + getElapsedSeconds(humanReadable: boolean): number; + + /** + * Get complete percentage + */ + getCompletePercent(): number; + getCompletePercent(len: number): number; + + /** + * Get average upload/download speed + */ + getAverageSpeed(): string; + getAverageSpeed(humanReadable: boolean): number; + + /** + * Get internal speed + */ + getSpeed(): string; + getSpeed(humanReadable: boolean): number; + + /** + * Get auto increment function + */ + getSpeed(size: number): (error: Error, value: any) => void; + + /** + * Get total size + */ + getTotalSize(): string; + getTotalSize(humanReadable: boolean): number; + + /** + * Get completed data size + */ + getCompleteSize(): string; + getCompleteSize(humanReadable: boolean): number; } export module Constants { } - export class LinearRetryPolicyFilter { + export interface Filter { + handle(requestOptions: any, next: Function): void; + } + + export class LinearRetryPolicyFilter implements Filter { constructor(retryCount?: number, retryInterval?: number); retryCount: number; retryInterval: number; + handle(requestOptions: any, next: Function): void; } - export class ExponentialRetryPolicyFilter { + export class ExponentialRetryPolicyFilter implements Filter { constructor(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number); retryCount: number; retryInterval: number; minRetryInterval: number; maxRetryInterval: number; + handle(requestOptions: any, next: Function): void; + } + + export class HmacSha256Sign { + } export class SharedAccessSignature { + storageAccount: string; + storageAccessKey: string; + permissionSet: string[]; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, permissionSet: string[]) + + /** + * Generates the query string for a shared access signature signing. + */ + generateSignedQueryString(path: string, queryString: Dictionary, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): Dictionary; + + /** + * Signs a request with the signature header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Generates the shared access signature for a resource. + */ + _generateSignature(path: string, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Generates the query string for a shared access signature signing. + */ + _permissionMatchesRequest(sharedAccessSignature: string, webResource: WebResource, resourceType: string, requiredPermissions: string[]): string; } export class SharedKey { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; } export class SharedKeyLite { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; } export class SharedKeyTable { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; } export class SharedKeyLiteTable { + torageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; } export module ISO8061Date { + /** + * Formats a date into an iso 8061 string. + */ + export function format(date: Date): string; + /** + * Parses an ISO 8061 date string into a date object. + */ + export function parse(stringDateTime: string): Date; } export class Logger { + level: string; + loggerFunction: (level: string, message: string) => void; + static LogLevels: { + EMERGENCY: string; + ALERT: string; + CRITICAL: string; + ERROR: string; + WARNING: string; + NOTICE: string; + INFO: string; + DEBUG: string; + }; + static logPriority: string[]; + + log(level: string, message: string): void; + emergency(message: string): void; + alert(message: string): void; + critical(message: string): void; + error(message: string): void; + warning(message: string): void; + notice(message: string): void; + info(message: string): void; + debug(message: string): void; + + defaultLoggerFunction(level: string, message: string): void; } export class ConnectionStringParser { + _value: string; + _pos: number; + _state: string; + constructor(connectionString: string); + + _parse(options: ConnectionStringParseOptions): Dictionary; + + _extractKey(): string; + _extractString(quote: string): string; + _extractValue(): string; + + _skipWhitespaces(): void; + _skipOperator(operator: string): void; + + static parse(connectionString: string): Dictionary; } export module ServiceSettings { + export var DEFAULT_PROTOCOL: string; + export class NoMatchError implements Error { + name: string; + message: string; + constr: any; + + constructor(); + constructor(message: string); + constructor(message: string, constr: any); + } + + /** + * Throws an exception if the connection string format does not match any of the + * available formats. + */ + export function noMatchConnectionString(connectionString: string): void; + + /** + * Throws an exception if the settings dont match any of the available formats. + */ + export function noMatchSettings(settings: any): void; + + /** + * Parses the connection string and then validate that the parsed keys belong to + * the validSettingKeys + */ + export function parseAndValidateKeys(connectionString: string, validKeys: string[]): string[]; + + /** + * Creates an anonymous function that acts as predicate to perform a validation. + */ + export function getValidator(requirements: Dictionary, isRequired: boolean, atLeastOne: boolean): ValidatorFunction; + + /** + * Creates a setting value condition that validates it is one of the passed valid values. + */ + export function setting(name: string): string[]; + + /** + * Creates an "at least one" predicate for the provided list of requirements. + */ + export function atLeastOne(...args: any[]): ValidatorFunction; + + /** + * Creates an optional predicate for the provided list of requirements. + */ + export function optional(...args: any[]): ValidatorFunction; + + /** + * Creates an required predicate for the provided list of requirements. + */ + export function allRequired(...args: any[]): ValidatorFunction; + + /** + * Creates a setting value condition using the passed predicate. + */ + export function settingWithFunc(name: string, predicate: Function): Requirement[]; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function matchedSpecification(settings: Dictionary): boolean; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function parseHost(uri: string): url.Url; } export class StorageServiceSettings { + _name: string; + _key: string; + _blobEndpointUri: string; + _queueEndpointUri: string; + _tableEndpointUri: string; + _usePathStyleUri: boolean; + constructor(name: string, key: string, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string, usePathStyleUri: boolean); + + /** + * Returns a StorageServiceSettings with development storage credentials using + * the specified proxy Uri. + */ + static _getDevelopmentStorageAccount(): StorageServiceSettings; + static _getDevelopmentStorageAccount(proxy: string): StorageServiceSettings; + + /** + * Gets a StorageServiceSettings object that references the development storage + * account. + */ + static getDevelopmentStorageAccountSettings(): StorageServiceSettings; + + /** + * Gets the default service endpoint using the specified protocol and account + * name. + */ + static _getDefaultServiceEndpoint(settings: Dictionary, dns: string): string; + + /** + * Creates StorageServiceSettings object given endpoints uri. + */ + static _createStorageServiceSettings(settings: Dictionary, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string): StorageServiceSettings; + + /** + * Creates a ServiceBusSettings object from a set of settings. + */ + static createFromSettings(settings: Dictionary): StorageServiceSettings; + + /** + * Creates a StorageServiceSettings object from the given connection string. + */ + static createFromConnectionString(connectionString: string): StorageServiceSettings; + + static createExplicitlyOrFromEnvironment(storageAccount: string, storageAccessKey: string, host: string): StorageServiceSettings; + + static isDevelopmentStorage(storageAccount: string, storageAccessKey: string, parsedHost: string): boolean; + + static createFromConfig(config: any): StorageServiceSettings; + + static customizeConfig(config: any): void; } export class ServiceBusSettings { @@ -290,11 +1375,87 @@ declare module "azure" { } export module Validate { + /** + * Checks if the given uri is valid or not. + */ + export function isValidUri(uri: string): boolean; + /** + * Validates that a clusterCreationObject is properly formed. + */ + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions): void; + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions, callback: ErrorCallback): void; + + export function isValidUuid(uuid: string): void; + export function isValidUuid(uuid: string, callback: ErrorCallback): void; + + /** + * Creates a anonymous function that check if a given key is base 64 encoded. + */ + export function isBase64Encoded(key: string): boolean; + + /** + * Validates a function. + */ + export function isValidFunction(functionObject: any, functionName: string): void; + + /** + * Validates that a Service Bus namespace name + * is legally allowable. Does not check availability. + */ + export function namespaceNameIsValid(name: string): boolean; + export function namespaceNameIsValid(name: string, callback: ErrorCallback): boolean; + + /** + * Validates a container name. + */ + export function containerNameIsValid(containerName: string): boolean; + export function containerNameIsValid(containerName: string, callback: ErrorCallback): boolean; + + /** + * Validates a blob name. + */ + export function blobNameIsValid(containerName: string, blob: string): boolean; + export function blobNameIsValid(containerName: string, blob: string, callback: ErrorCallback): boolean; + + /** + * Validates a table name. + */ + export function tableNameIsValid(tableName: string): boolean; + export function tableNameIsValid(tableName: string, callback: ErrorCallback): boolean; + + /** + * Validates a queue name. + */ + export function queueNameIsValid(queueName: string): boolean; + export function queueNameIsValid(queueName: string, callback: ErrorCallback): boolean; + + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number): boolean; + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback: ErrorCallback): boolean; + + export function validateArgs(functionName: string, validationRules: Function): boolean; } export module date { + /** + * Generates a Date object which is in the given days from now. + */ + export function daysFromNow(days: number): Date; + /** + * Generates a Date object which is in the given hours from now. + */ + export function hoursFromNow(hours: number): Date; + + /** + * Generates a Date object which is in the given minutes from now. + */ + export function minutesFromNow(minutes: number): Date; + + /** + * Generates a Date object which is in the given seconds from now. + */ + export function secondsFromNow(seconds: number): Date; } //#endregion @@ -302,28 +1463,104 @@ declare module "azure" { export interface WebResponse { isSuccessful: boolean; statusCode: number; - body: { - entry: { - id: string; - title: any; - updated: string; - author: { - name: any; - }; - link: any; - category: any; - content: any; - }; + body: { + entry: { + id: string; + title: any; + updated: string; + author: { + name: any; + }; + link: any; + category: any; + content: any; + }; }; headers: any; md5: any; } + //#region Common Interfaces + export interface SimpleCallback { + (error: Error, result: T): void; + } + export interface ErrorCallback { + (error: Error): void; + } + export interface StorageCallbackVoid { + (err: Error, response: WebResponse): void; + } + export interface StorageCallback { + (err: Error, result: T, response: WebResponse): void; + } + export interface StorageServiceStatsCallback extends StorageCallback { } + export interface StorageServicePropertiesCallback extends StorageCallback { } + export interface TimeoutIntervalOptions { + locationMode?: string; timeoutIntervalInMs?: number; + maximumExecutionTimeInMs?: number; + } + export interface MetadataOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; + } + export interface StorageAclOptions extends TimeoutIntervalOptions { + leaseId?: string; + signedIdentifiers: SignedIdentifier[] } - ///#region TableService Callbacks + export interface Dictionary { + [key: string]: T; + } + export interface StorageServiceProperties { + Logging: { + Version: number; + Delete: boolean; + Read: boolean; + Write: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + Metrics: { + Version: number; + Enabled: boolean; + IncludeAPIs: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + DefaultServiceVersion: string; + } + export interface StorageServiceStats { + GeoReplication: { + Status: string; + LastSyncTime: Date; + } + } + export interface SignedIdentifier { + Id: string; + AccessPolicy: SharedAccessPolicy; + } + export interface StorageMetadata { + [key: string]: string; + } + export interface ContinuationToken { + nextMarker: string; + targetLocation: string; + } + export interface SharedAccessPolicy { + Id?: string; + AccessPolicy: { + Start?: Date; + Expiry: Date; + Permission?: string; + } + } + //#endregion + //#region TableService Interfaces export interface TableRequestCallback { (error: Error, tableResult: { TableName: string; }, response: WebResponse): void; } @@ -387,13 +1624,233 @@ declare module "azure" { etag?: string; } //#endregion + //#region BlobService Interfaces + export interface LeaseIdOptions extends TimeoutIntervalOptions { + leaseId?: string; + } + export interface AccessConditionsOptions extends TimeoutIntervalOptions { + accessConditions?: StorageAccessCondition; + } + export interface LeaseAccessConditionsOptions extends LeaseIdOptions { + accessConditions?: StorageAccessCondition; + } + + export interface ListContainersOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; + } + export interface ListContainersCallback { + (err: Error, containers: ContainerResult[], continuationToken: ContinuationToken, response: WebResponse): void; + } + export interface CreateContainerOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; + publicAccessLevel?: string; + } + export interface GetContainerPropertiesOptions extends TimeoutIntervalOptions { + leaseId?: string; + } + export interface GetContainerMetadataOptions extends GetContainerPropertiesOptions { + accessConditions?: StorageAccessCondition; + } + + export interface ListBlobsOptions extends ListContainersOptions { + prefix?: string; + delimiter?: string; + } + export interface ListBlobsCallback { + (err: Error, blobs: BlobResult[], continuationToken: ContinuationToken, response: WebResponse): void; + } + export interface GetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + snapshotId?: string; + } + export interface SetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; + } + export interface ReadBlobOptions extends GetBlobPropertiesOptions { + rangeStart?: string; + rangeEnd?: string; + useTransactionalMD5?: boolean; + disableContentMD5Validation?: boolean; + } + export interface GetBlobToTextCallback { + (err: Error, text: string, result: BlobResult, response: WebResponse): void; + } + export interface DeleteBlobOptions extends GetBlobPropertiesOptions { + deleteSnapshots?: string; + } + export interface BlobSnapshotOptions extends GetBlobPropertiesOptions { + metadata?: StorageMetadata; + } + export interface CopyBlobOptions extends BlobSnapshotOptions { + sourceLeaseId?: string; + sourceAccessConditions: StorageAccessCondition; + } + + export interface UploadBlobOptions extends SetBlobPropertiesOptions { + metadata?: StorageMetadata; + speedSummary?: SpeedSummary; + parallelOperationThreadCount?: number; + storeBlobContentMD5?: boolean; + useTransactionalMD5?: boolean; + } + export interface CreatePagesOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; + } + export interface PageRangeOptions extends LeaseIdOptions { + snapshotId?: string; + rangeStart?: number; + rangeEnd?: number; + } + + export interface UploadBlockBlobOptions extends UploadBlobOptions { + blockIdPrefix?: string; + } + export interface CreateBlockOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; + } + + export interface LeaseOptions extends AccessConditionsOptions { + leaseDuration?: string; + proposedLeaseId?: string; + } + export interface BreakLeaseOptions extends AccessConditionsOptions { + leaseBreakPeriod?: number; + } + + export interface BlobHeaders { + cacheControl?: string; + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentDisposition?: string; + } + export interface PageRange { + start: number; + end: number; + } + export interface BlockList { + LatestBlocks: string[]; + CommittedBlocks: string[]; + UncommittedBlocks: string[]; + } + export interface StorageAccessCondition { + "If-Modified-Since": Date; + "If-Unmodified-Since": Date; + "If-Match": string; + "If-None-Match": string; + } + //#endregion + //#region QueueService Interfaces + export interface ListQueuesOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; + } + export interface ListQueuesCallback { + (err: Error, queues: QueueResult[], continuationToken: ContinuationToken, response: WebResponse): void; + } + + export interface CreateQueueMessageOptions extends TimeoutIntervalOptions { + messagettl?: number; + visibilitytimeout?: number; + } + export interface PeekQueueMessagesOptions extends TimeoutIntervalOptions { + numofmessages?: number; + } + export interface GetQueueMessagesOptions extends PeekQueueMessagesOptions { + peekonly?: boolean; + visibilitytimeout?: number; + } + export interface UpdateQueueMessagesOptions extends TimeoutIntervalOptions { + messagetext?: string; + } + //#endregion + + //#region RoleEnvironment Interfaces + export interface Role { + name: string; + instances: { + [instanceId: string]: RoleInstance; + }; + } + export interface RoleInstance { + id: string; + faultDomain: string; + updateDomain: string; + endpoints: { + [endpoint: string]: RoleInstanceEndpoint + }; + } + export interface RoleInstanceEndpoint { + protocol: string; + address: string; + port: number; + } + export interface RoleLocalResource { + name: string; + path: string; + maximumSizeInMegabytes: number; + } + //#endregion + //#region ConnectionStringParser Interfaces + export interface ConnectionStringParseOptions { + skipLowerCase: boolean; + } + //#endregion + //#region Validate Interfaces + export interface ClusterCreationOptions { + name: string; + location: string; + defaultStorageAccountName: string; + defaultStorageAccountKey: string; + defaultStorageContainer: string; + user: string; + password: string; + nodes: number; + additionalStorageAccounts?: { + name: string; + key: string; + }[]; + oozieMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; + hiveMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; + } + //#endregion + //#region ServiceSettings Interfaces + export interface Requirement { + SettingName: string; + SettingPredicate: Function; + } + export interface ValidatorFunction { + (userSettings: Dictionary): any; + } + //#endregion //#endregion //#region Un-exported internal classes class StorageServiceClient extends ServiceClient { static incorrectStorageAccountErr: string; static incorrectStorageAccessKeyErr: string; - static getStorageSettings(connectionString: string) : StorageServiceSettings; + static getStorageSettings(connectionString: string): StorageServiceSettings; static getStorageSettings(storageAccount?: string, storageAccessKey?: string, host?: string): StorageServiceSettings; apiVersion: string; @@ -404,5 +1861,4 @@ declare module "azure" { //#endregion export function isEmulated(): boolean; - } From 55d4d520411475d04d13b72688f33c6a7dc94113 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Sun, 14 Sep 2014 23:00:53 +0200 Subject: [PATCH 033/149] Add i18n-node definitions --- i18n-node/i18n-node.d.ts | 240 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 i18n-node/i18n-node.d.ts diff --git a/i18n-node/i18n-node.d.ts b/i18n-node/i18n-node.d.ts new file mode 100644 index 000000000..5eb5043da --- /dev/null +++ b/i18n-node/i18n-node.d.ts @@ -0,0 +1,240 @@ +// Type definitions for i18n-node 0.5.0 +// Project: https://github.com/mashpie/i18n-node +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module i18n { + export interface ConfigurationOptions { + /** Setup some locales - other locales default to en silently */ + locales?: string[]; + /** Alter a site wide default locale */ + defaultLocale?: string; + + /** + * Sets a custom cookie name to parse locale settings from + * @default null + */ + cookie?: string; + /** + * Where to store json files, relative to modules directory + * @default "./locales" + */ + directory?: string; + + /** + * whether to write new locale information to disk + * @default true + */ + updateFiles?: boolean; + + /** + * What to use as the indentation unit + * @default "\t" + */ + indent?: string; + + /** + * Setting extension of json files (you might want to set this to '.js' according to webtranslateit) + * @default ".json" + */ + extension?: string; + + /** + * Enable object notation + * @default false + */ + objectNotation?: boolean; + } + export interface PluralOptions { + singular: string; + plural: string; + count: number; + } + + export interface LocaleCatalog { + [key: string]: string; + } + export interface GlobalCatalog { + [key: string]: LocaleCatalog; + } + + /** + * Configure current i18n instance + * @param {ConfigurationOptions} options - configuration options for i18n + */ + function configure(options: ConfigurationOptions): void; + + /** + * Initialize i18n middleware for express + * @param {Express.Request} request - Current express request + * @param {Express.Response} response - Current express response + * @param {Function} next - Callback to continue process + */ + function init(request: Express.Request, response: Express.Response, next?: Function): void; + + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @returns {string} The translated phrase + */ + function __(phrase: string, ...replace: string[]): string; + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @returns {string} The translated phrase + */ + function __n(options: PluralOptions): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + function __n(singular: string, plural: string, count: number): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {string} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + function __n(singular: string, plural: string, count: string): string; + + /** + * Change the current active locale + * @param {string} locale - The locale to set as default + */ + function setLocale(locale: string): void; + /** + * Change the current active locale for specified request + * @param {Express.Request} request - The request to change locale on + * @param {string} locale - The locale to set as default + */ + function setLocale(request: Express.Request, locale: string): void; + + /** + * Get the current active locale + * @returns {string} The current locale in request + */ + function getLocale(): string; + /** + * Get the current active locale for specified request + * @param {Express.Request} request - The request to get locale for + * @returns {string} The current locale in request + */ + function getLocale(request: Express.Request): string; + + /** + * Get the current global catalog + * @returns {GlobalCatalog} The current global catalog + */ + function getCatalog(): GlobalCatalog; + /** + * Get the catalog for the given locale + * @param {string} locale - The locale to get catalog for + * @returns {LocaleCatalog} The specified locale catalog + */ + function getCatalog(locale: string): LocaleCatalog; + /** + * Get the current active locale catalog for specified request + * @param {Express.Request} request - The request to get locale catalog for + * @returns {LocaleCatalog} The current locale catalog for the specified request + */ + function getCatalog(request: Express.Request): LocaleCatalog; + /** + * Get the current locale catalog for specified request and specified locale + * @param {Express.Request} request - The request to get locale catalog for + * @param {string} locale - The locale to get catalog for + * @returns {LocaleCatalog} The specified locale catalog + */ + function getCatalog(request: Express.Request, locale: string): LocaleCatalog; + + /** + * Override the current request locale by using the query param (?locale=en) + * @param {Express.Request} [request] - The request to override locale for + */ + function overrideLocaleFromQuery(request?: Express.Request): void; + + /** + * Get current i18n-node version + * @member {string} + */ + var version: string; +} + +interface i18nAPI { + locale: string; + + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @returns {string} The translated phrase + */ + __(phrase: string, ...replace: string[]): string; + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @returns {string} The translated phrase + */ + __n(options: i18n.PluralOptions): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + __n(singular: string, plural: string, count: number): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {string} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + __n(singular: string, plural: string, count: string): string; + + + /** + * Get the current active locale + * @returns {string} The current locale in request + */ + getLocale(): string; + /** + * Change the current active locale + * @param {string} locale - The locale to set as default + */ + setLocale(locale: string): void; + + /** + * Get the current global catalog + * @returns {GlobalCatalog} The current global catalog + */ + getCatalog(): i18n.GlobalCatalog; + /** + * Get the catalog for the given locale + * @param {string} locale - The locale to get catalog for + * @returns {LocaleCatalog} The specified locale catalog + */ + getCatalog(locale: string): i18n.LocaleCatalog; +} + +declare module "i18n" { + export = i18n; +} + +declare module Express { + export interface Request extends i18nAPI { + languages: string[]; + regions: string[]; + language: string; + region: string; + } + export interface Response extends i18nAPI { + locals: i18nAPI + } +} From a7cee68fdf8d91403e1b0fe1e18e9c6aff22c8cf Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Sun, 14 Sep 2014 23:04:50 +0200 Subject: [PATCH 034/149] Add jsonwebtoken node module definitions --- jsonwebtoken/jsonwebtoken.d.ts | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 jsonwebtoken/jsonwebtoken.d.ts diff --git a/jsonwebtoken/jsonwebtoken.d.ts b/jsonwebtoken/jsonwebtoken.d.ts new file mode 100644 index 000000000..16256c24a --- /dev/null +++ b/jsonwebtoken/jsonwebtoken.d.ts @@ -0,0 +1,66 @@ +// Type definitions for jsonwebtoken 0.4.0 +// Project: https://github.com/auth0/node-jsonwebtoken +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "jsonwebtoken" { + + interface SignOptions { + /** + * Signature algorithm. Could be one of these values : + * - HS256: HMAC using SHA-256 hash algorithm + * - 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; + /** @member {number} - Lifetime for the token in minutes */ + expiresInMinutes?: number; + audience?: string; + subject?: string; + issuer?: string; + } + + interface VerifyOptions { + audience?: string; + issuer?: string; + } + + /** + * Sign the given payload into a JSON Web Token string + * @param {string|object|buffer} payload - Payload to sign, could be an literal, buffer or string + * @param {string|buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * @param {SignOptions} options - Options for the signature + * @returns The JSON Web Token string + */ + function sign(payload: any, secretOrPrivateKey: any, options?: SignOptions): string; + + /** + * Verify given token using a secret or a public key to get a decoded token + * @param {string} token - JWT string to verify + * @param {string|buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * @param {Function} callback - Callback to get the decoded token on + */ + function verify(token: string, secretOrPublicKey: any, callback: (err: Error, decoded: {}) => void): void; + /** + * Verify given token using a secret or a public key to get a decoded token + * @param {string} token - JWT string to verify + * @param {string|buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * @param {VerifyOptions} options - Options for the verification + * @param {Function} callback - Callback to get the decoded token on + */ + function verify(token: string, secretOrPublicKey: any, options: VerifyOptions, callback: (err: Error, decoded: {}) => void): void; + + /** + * Returns the decoded payload without verifying if the signature is valid. + * @param {string} token - JWT string to decode + * @returns The decoded Token + */ + function decode(token: string): {}; +} From d0227b9c72434c32139a8b8ad19cf79391fb8bd3 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 00:03:57 +0200 Subject: [PATCH 035/149] Add definitions for passport-local module --- passport-local/passport-local.d.ts | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 passport-local/passport-local.d.ts diff --git a/passport-local/passport-local.d.ts b/passport-local/passport-local.d.ts new file mode 100644 index 000000000..6b3cbef38 --- /dev/null +++ b/passport-local/passport-local.d.ts @@ -0,0 +1,33 @@ +// Type definitions for passport-local 1.0.0 +// Project: https://github.com/jaredhanson/passport-local +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'passport-local' { + + import passport = require('passport'); + import express = require('express'); + + interface IStrategyOptions { + usernameField?: string; + passwordField?: string; + } + + interface IVerifyOptions { + message: string; + } + + interface VerifyFunction { + (username: string, password: string, done: (error: any, user?: any, options?: IVerifyOptions) => void): void; + } + + class Strategy implements passport.Strategy { + constructor(options: IStrategyOptions, verify: VerifyFunction); + constructor(verify: VerifyFunction); + + name: string; + authenticate: (req: express.Request, options?: Object) => void; + } +} From e49c09a129662daf97e7964257fac64a3906178d Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 00:09:11 +0200 Subject: [PATCH 036/149] Add definitions for sendgrid sdk for node --- sendgrid/sendgrid.d.ts | 122 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 sendgrid/sendgrid.d.ts diff --git a/sendgrid/sendgrid.d.ts b/sendgrid/sendgrid.d.ts new file mode 100644 index 000000000..96d52601e --- /dev/null +++ b/sendgrid/sendgrid.d.ts @@ -0,0 +1,122 @@ +// Type definitions for sendgrid 1.1.0 +// Project: https://github.com/sendgrid/sendgrid-nodejs +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface SendgridUriParts { + protocol: string; + host: string; + port: string; + endpoint: string; +} + +interface SendgridOptions { + protocol?: string; + host?: string; + port?: string; + endpoint?: string; + uri?: string; +} + +interface SendgridOptionsExport { + uriParts: SendgridUriParts; + uri: string; +} + +interface SendgridEmailOptions { + to?: any; + toname?: string; + from?: string; + fromname?: string; + subject?: string; + text?: string; + html?: string; + bcc?: any; + replyto?: string; + date?: Date; + headers?: { [key: string]: string }; + files?: SendgridEmailFileOptions[]; + smtpapi?: any; +} + +declare class PrivateSendgridEmail { + to: any; + toname: string; + from: string; + fromname: string; + subject: string; + text: string; + html: string; + bcc: any; + replyto: string; + date: Date; + headers: { [key: string]: string }; + files: PrivateSendgridFile[]; + smtpapi: any; + + constructor(); + constructor(options: SendgridEmailOptions); + + addTo(address: string): void; + addHeader(type: string, value: string): void; + addSubstitution(type: string, value: string): void; + addSubstitution(type: string, value: string[]): void; + addSection(section: { [key: string]: string }): void; + addUniqueArg(uarg: { [key: string]: string }): void; + addCategory(category: string): void; + addFilter(filter: string, command: string, value: number): void; + addFilter(filter: string, command: string, value: string): void; + addFile(file: SendgridEmailFileOptions): void; + + setFrom(address: string): void; + setSubject(subject: string): void; + setText(text: string): void; + setHtml(html: string): void; + setHeaders(headers: { [key: string]: string }): void; + setSubstitutions(substitutions: { [key: string]: string[] }): void; + setSections(sections: { [key: string]: string }): void; + setUniqueArgs(uargs: { [key: string]: string }): void; + setCategories(categories: string[]): void; + setFilters(filters: any): void; +} + +interface SendgridEmailFileOptions { + filename?: string; + contentType?: string; + cid?: string; + path?: string; + url?: string; + content?: any; +} + +declare class PrivateSendgridFile { + filename: string; + contentType: string; + cid: string; + + type: string; + content: string; + path: string; + url: string; + + loadContent(callback: (hasError: boolean, error: Error) => any): void; +} + +interface Sendgrid { + version: string; + api_user: string; + api_key: string; + options: SendgridOptionsExport; + Email: typeof PrivateSendgridEmail; + + send(email: PrivateSendgridEmail, callback: (err: Error, json: any) => any): void; +} + +declare module "sendgrid" { + interface SendgridConstructor { + (api_user: string, api_key: string, options?: SendgridOptions): Sendgrid; + new (api_user: string, api_key: string, options?: SendgridOptions): Sendgrid; + } + + export = SendgridConstructor; +} \ No newline at end of file From 760bacb86c2a8221dd196f7e48f1675a14f087c9 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 04:18:49 +0200 Subject: [PATCH 037/149] Add stylus definitions --- stylus/stylus.d.ts | 1416 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1416 insertions(+) create mode 100644 stylus/stylus.d.ts diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts new file mode 100644 index 000000000..b4c54b361 --- /dev/null +++ b/stylus/stylus.d.ts @@ -0,0 +1,1416 @@ +// Type definitions for stylus 0.48.1 +// Project: https://github.com/LearnBoost/stylus +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface StylusStatic { + /** + * Return a new `Renderer` for the given `str` and `options`. + */ + (str: string, options: StylusRenderOptions): StylusRenderer; + + /** + * Library version. + */ + version: string; + + /** + * Expose nodes. + */ + nodes: StylusNodeStatic; + + /** + * Expose BIFs. + */ + functions: StylusFunctions; + + /** + * Expose utils. + */ + utils: StylusUtils; + + Visitor: typeof StylusVisitor; + Parser: typeof StylusParser; + Evaluator: typeof StylusEvaluator; + Compiler: typeof StylusCompiler; + + /** + * Expose middleware. + */ + middleware(dir: string): StylusMiddleware; + + /** + * Convert the given `css` to `stylus` source. + */ + convertCSS(css: string): string; + + /** + * Render the given `str` with `options` and callback `fn(err, css)`. + */ + render(str: string, callback: StylusRenderCallback): string; + render(str: string, options: StylusRenderOptions, callback: StylusRenderCallback): string; + + /** + * Return a url() function with the given `options`. + */ + url: StylusUrl; + + /** + * Return a url() function with the given `options`. + */ + resolver(options): StylusLiteralFunction; +} + +//#region Internal Modules + +interface StylusNodeStatic { + Node: typeof StylusNode; + Root: typeof StylusNodeRoot; + Null: typeof StylusNodeNull; + Each: typeof StylusNodeEach; + If: typeof StylusNodeIf; + Call: typeof StylusNodeCall; + UnaryOp: typeof StylusNodeUnaryOp; + BinOp: typeof StylusNodeBinOp; + Ternary: typeof StylusNodeTernary; + Block: typeof StylusNodeBlock; + Unit: typeof StylusNodeUnit; + String: typeof StylusNodeString; + HSLA: typeof StylusNodeHSLA; + RGBA: typeof StylusNodeRGBA; + Ident: typeof StylusNodeIdent; + Group: typeof StylusNodeGroup; + Literal: typeof StylusNodeLiteral; + Boolean: typeof StylusNodeBoolean; + Return: typeof StylusNodeReturn; + Media: typeof StylusNodeMedia; + QueryList: typeof StylusNodeQueryList; + Query: typeof StylusNodeQuery; + QueryExpr: typeof StylusNodeQueryExpr; + Params: typeof StylusNodeParams; + Comment: typeof StylusNodeComment; + Keyframes: typeof StylusNodeKeyframes; + Member: typeof StylusNodeMember; + Charset: typeof StylusNodeCharset; + Namespace: typeof StylusNodeNamespace; + Import: typeof StylusNodeImport; + Extend: typeof StylusNodeExtend; + Object: typeof StylusNodeObject; + Function: typeof StylusNodeFunction; + Property: typeof StylusNodeProperty; + Selector: typeof StylusNodeSelector; + Expression: typeof StylusNodeExpression; + Arguments: typeof StylusNodeArguments; + Atblock: typeof StylusNodeAtblock; + Atrule: typeof StylusNodeAtrule; + + true: StylusNodeBoolean; + false: StylusNodeBoolean; + null: StylusNodeNull; +} + +interface StylusFunctions { + /** + * Convert the given `color` to an `HSLA` node, + * or h,s,l,a component values. + */ + hsla(rgba: StylusNodeRGBA): StylusNodeHSLA; + hsla(hsla: StylusNodeHSLA): StylusNodeHSLA; + hsla(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit, alpha: StylusNodeUnit): StylusNodeHSLA; + + /** + * Convert the given `color` to an `HSLA` node, + * or h,s,l component values. + */ + hsl(rgba: StylusNodeRGBA): StylusNodeHSLA; + hsl(hsla: StylusNodeHSLA): StylusNodeHSLA; + hsl(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit): StylusNodeHSLA; + + /** + * Return type of `node`. + */ + type(node: StylusNode): string; + /** + * Return type of `node`. + */ + typeof(node: StylusNode): string; + /** + * Return type of `node`. + */ + "type-of"(node: StylusNode): string; + + /** + * Return component `name` for the given `color`. + */ + component(color: StylusNodeRGBA, name: StylusNodeString): StylusNodeUnit; + component(color: StylusNodeHSLA, name: StylusNodeString): StylusNodeUnit; + + /** + * Return component `name` for the given `color`. + */ + basename(path: StylusNodeString): string; + basename(path: StylusNodeString, ext: StylusNodeString): string; + + /** + * Return the dirname of `path`. + */ + dirname(path: StylusNodeString): string; + + /** + * Return the extension of `path`. + */ + extname(path: StylusNodeString): string; + + /** + * Joins given paths + */ + pathjoin(...paths: StylusNodeString[]): string; + + /** + * Return the red component of the given `color`, + * or set the red component to the optional second `value` argument. + */ + red(color: StylusNodeRGBA): StylusNodeUnit; + red(color: StylusNodeHSLA): StylusNodeUnit; + red(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + red(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return the green component of the given `color`, + * or set the green component to the optional second `value` argument. + */ + green(color: StylusNodeRGBA): StylusNodeUnit; + green(color: StylusNodeHSLA): StylusNodeUnit; + green(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + green(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return the blue component of the given `color`, + * or set the blue component to the optional second `value` argument. + */ + blue(color: StylusNodeRGBA): StylusNodeUnit; + blue(color: StylusNodeHSLA): StylusNodeUnit; + blue(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + blue(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return the alpha component of the given `color`, + * or set the alpha component to the optional second `value` argument. + */ + alpha(color: StylusNodeRGBA): StylusNodeUnit; + alpha(color: StylusNodeHSLA): StylusNodeUnit; + alpha(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + alpha(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return the hue component of the given `color`, + * or set the hue component to the optional second `value` argument. + */ + hue(color: StylusNodeRGBA): StylusNodeUnit; + hue(color: StylusNodeHSLA): StylusNodeUnit; + hue(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + hue(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return the saturation component of the given `color`, + * or set the saturation component to the optional second `value` argument. + */ + saturation(color: StylusNodeRGBA): StylusNodeUnit; + saturation(color: StylusNodeHSLA): StylusNodeUnit; + saturation(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + saturation(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return the lightness component of the given `color`, + * or set the lightness component to the optional second `value` argument. + */ + lightness(color: StylusNodeRGBA): StylusNodeUnit; + lightness(color: StylusNodeHSLA): StylusNodeUnit; + lightness(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; + lightness(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return a `RGBA` from the r,g,b,a channels. + */ + rgba(rgba: StylusNodeRGBA): StylusNodeRGBA; + rgba(hsla: StylusNodeHSLA): StylusNodeRGBA; + rgba(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit, alpha: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return a `RGBA` from the r,g,b channels. + */ + rgb(rgba: StylusNodeRGBA): StylusNodeRGBA; + rgb(hsla: StylusNodeHSLA): StylusNodeRGBA; + rgb(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit, alpha: StylusNodeUnit): StylusNodeRGBA; + + /** + * Blend the `top` color over the `bottom` + */ + blend(top: StylusNodeRGBA): StylusNodeRGBA; + blend(top: StylusNodeRGBA, bottom: StylusNodeRGBA): StylusNodeRGBA; + blend(top: StylusNodeRGBA, bottom: StylusNodeHSLA): StylusNodeRGBA; + blend(top: StylusNodeHSLA): StylusNodeRGBA; + blend(top: StylusNodeHSLA, bottom: StylusNodeRGBA): StylusNodeRGBA; + blend(top: StylusNodeHSLA, bottom: StylusNodeHSLA): StylusNodeRGBA; + + /** + * Returns the relative luminance of the given `color`, + * see http://www.w3.org/TR/WCAG20/#relativeluminancedef + */ + luminosity(rgba: StylusNodeRGBA): StylusNodeUnit; + luminosity(rgba: StylusNodeHSLA): StylusNodeUnit; + + /** + * Returns the contrast ratio object between `top` and `bottom` colors, + * based on http://leaverou.github.io/contrast-ratio/ + * and https://github.com/LeaVerou/contrast-ratio/blob/gh-pages/color.js#L108 + */ + contrast(top: StylusNodeRGBA): StylusNodeObject; + contrast(top: StylusNodeRGBA, bottom: StylusNodeRGBA): StylusNodeObject; + contrast(top: StylusNodeRGBA, bottom: StylusNodeHSLA): StylusNodeObject; + contrast(top: StylusNodeHSLA): StylusNodeObject; + contrast(top: StylusNodeHSLA, bottom: StylusNodeRGBA): StylusNodeObject; + contrast(top: StylusNodeHSLA, bottom: StylusNodeHSLA): StylusNodeObject; + + /** + * Returns the transparent version of the given `top` color, + * as if it was blend over the given `bottom` color. + */ + transparentify(top: StylusNodeRGBA): StylusNodeObject; + transparentify(top: StylusNodeRGBA, bottom: StylusNodeRGBA, alpha?: StylusNodeUnit): StylusNodeObject; + transparentify(top: StylusNodeRGBA, bottom: StylusNodeHSLA, alpha?: StylusNodeUnit): StylusNodeObject; + transparentify(top: StylusNodeHSLA): StylusNodeObject; + transparentify(top: StylusNodeHSLA, bottom: StylusNodeRGBA, alpha?: StylusNodeUnit): StylusNodeObject; + transparentify(top: StylusNodeHSLA, bottom: StylusNodeHSLA, alpha?: StylusNodeUnit): StylusNodeObject; + + /** + * Convert a .json file into stylus variables or object. + * Nested variable object keys are joined with a dash (-) + * + * Given this sample media-queries.json file: + * { + * "small": "screen and (max-width:400px)", + * "tablet": { + * "landscape": "screen and (min-width:600px) and (orientation:landscape)", + * "portrait": "screen and (min-width:600px) and (orientation:portrait)" + * } + * } + */ + json(path: StylusNodeString, local: StylusNodeBoolean, namePrefix: StylusNodeString): any; + + /** + * Use the given `plugin`. + */ + use(plugin: StylusNodeString): void; + use(plugin: StylusNodeString, options: any): void; + + /** + * Unquote the given `string`. + */ + unquote(str: StylusNodeString): StylusNodeLiteral; + + /** + * Like `unquote` but tries to convert the given `str` to a Stylus node. + */ + convert(str: StylusNodeString): StylusNode; + + /** + * Assign `type` to the given `unit` or return `unit`'s type. + */ + unit(unit: StylusNodeUnit, type: StylusNodeString): StylusNodeUnit; + + /** + * Lookup variable `name` or return Null. + */ + lookup(name: StylusNodeString): StylusNode; + + /** + * Set a variable `name` on current scope. + */ + define(name: StylusNodeString, expr: StylusNodeExpression): StylusNode; + + /** + * Perform `op` on the `left` and `right` operands. + */ + operate(op: StylusNodeString, left: StylusNode, right: StylusNode): StylusNode; + + /** + * Test if `val` matches the given `pattern`. + */ + match(pattern: StylusNodeString, val: StylusNodeString): StylusNodeBoolean; + match(pattern: StylusNodeString, val: StylusNodeIdent): StylusNodeBoolean; + + /** + * Returns substring of the given `val`. + */ + substr(val: StylusNodeString, start: StylusNodeNumber, length: StylusNodeNumber): StylusNodeString; + substr(val: StylusNodeIdent, start: StylusNodeNumber, length: StylusNodeNumber): StylusNodeIdent; + + /** + * Returns string with all matches of `pattern` replaced by `replacement` in given `val` + */ + replace(pattern: StylusNodeString, replacement: StylusNodeString, val: StylusNodeString): StylusNodeString; + replace(pattern: StylusNodeString, replacement: StylusNodeString, val: StylusNodeIdent): StylusNodeIdent; + + /** + * Splits the given `val` by `delim` + */ + split(pattern: StylusNodeString, val: StylusNodeString): StylusNodeExpression; + split(pattern: StylusNodeString, val: StylusNodeIdent): StylusNodeExpression; + + /** + * Return length of the given `expr`. + */ + length(expr: StylusNodeExpression): StylusNodeUnit; + + /** + * Inspect the given `expr`. + */ + length(...expr: StylusNodeExpression[]): StylusNodeNull; + + /** + * Throw an error with the given `msg`. + */ + error(msg: StylusNodeString): void; + + /** + * Warn with the given `msg` prefixed by "Warning: ". + */ + warn(msg: StylusNodeString): StylusNodeNull; + + /** + * Output stack trace. + */ + trace(): StylusNodeNull; + + /** + * Push the given args to `expr`. + */ + push(expr: StylusNodeExpression, ...nodes: StylusNode[]): StylusNodeUnit; + + /** + * Pop a value from `expr`. + */ + pop(expr: StylusNodeExpression): StylusNode; + + /** + * Unshift the given args to `expr`. + */ + unshift(expr: StylusNodeExpression, ...nodes: StylusNode[]): StylusNodeUnit; + + /** + * Unshift the given args to `expr`.. + */ + prepend(expr: StylusNodeExpression, ...nodes: StylusNode[]): StylusNodeUnit; + + /** + * Shift a value from `expr`. + */ + shift(expr: StylusNodeExpression): StylusNode; + + /** + * Return a `Literal` with the given `fmt`, and variable number of arguments. + */ + s(fmt: StylusNodeString, ...nodes: StylusNode[]): StylusNodeLiteral; + + /** + * Return a `Literal` `num` converted to the provided `base`, padded to `width` + * with zeroes (default width is 2) + */ + "base-convert"(num: StylusNodeNumber, base: StylusNodeNumber, width: StylusNodeNumber): StylusNodeLiteral; + + /** + * Return the opposites of the given `positions`. + */ + "opposite-position"(positions: StylusNodeExpression): StylusNodeExpression; + + /** + * Return the width and height of the given `img` path. + */ + "image-size"(img: StylusNodeString, ignoreErr: StylusNodeBoolean): StylusNodeExpression; + + /** + * Return the tangent of the given `angle`. + */ + tan(angle: StylusNodeUnit): StylusNodeUnit; + + /** + * Return the tangent of the given `angle`. + */ + math(n: StylusNodeUnit, fn: StylusNodeString): StylusNodeUnit; + + /** + * Return the opposites of the given `positions`. + */ + "-math-prop"(prop: StylusNodeString): StylusNodeUnit; + + /** + * Adjust HSL `color` `prop` by `amount`. + */ + adjust(rgba: StylusNodeRGBA, prop: StylusNodeString, amount: StylusNodeUnit): StylusNodeRGBA; + adjust(hsla: StylusNodeHSLA, prop: StylusNodeString, amount: StylusNodeUnit): StylusNodeRGBA; + + /** + * Return a clone of the given `expr`. + */ + clone(expr: StylusNodeExpression): StylusNodeExpression; + + /** + * Add property `name` with the given `expr` to the mixin-able block. + */ + "add-property"(name: StylusNodeString, expr: StylusNodeExpression): StylusNodeProperty; + + /** + * Merge the object `dest` with the given args. + */ + merge(dest: StylusNodeObject, ...objs: StylusNodeObject[]): StylusNodeObject; + + /** + * Merge the object `dest` with the given args. + */ + extend(dest: StylusNodeObject, ...objs: StylusNodeObject[]): StylusNodeObject; + + /** + * Return the current selector or compile `sel` selector. + */ + selector(): string; + selector(sel: StylusNodeString): string; + + /** + * Prefix css classes in a block + */ + "-prefix-classes"(prefix: StylusNodeString, block: StylusNodeBlock): StylusNodeBlock; + + /** + * Returns the @media string for the current block + */ + "current-media"(): StylusNodeString; + + /** + * Return the separator of the given `list`. + */ + "list-separator"(list: StylusNodeExpression): StylusNodeString; +} + +interface StylusUtils { + /** + * Check if `path` looks absolute. + */ + absolute(path: string): boolean; + + /** + * Attempt to lookup `path` within `paths` from tail to head. + * Optionally a path to `ignore` may be passed. + */ + lookup(path: string, paths: string, ignore: string, resolveURL: boolean): string; + + /** + * Attempt to lookup `path` within `paths` from tail to head. + * Optionally a path to `ignore` may be passed. + */ + lookupIndex(path: string, paths: string, filename: string): string[]; + + /** + * Like `utils.lookup` but uses `glob` to find files. + */ + find(path: string, paths: string, ignore: string): string[]; + + /** + * Format the given `err` with the given `options`. + */ + formatException(err: Error, options: StylusExceptionOptions): Error; + + /** + * Assert that `node` is of the given `type`, or throw. + */ + assertType(node: StylusNode, type: string, param: string): void; + + /** + * Assert that `node` is a `String` or `Ident`. + */ + assertString(node: StylusNode, param: string): void; + + /** + * Assert that `node` is a `RGBA` or `HSLA`. + */ + assertColor(node: StylusNode, param: string): void; + + /** + * Assert that param `name` is given, aka the `node` is passed. + */ + assertPresent(node: StylusNode, name: string): void; + + /** + * Unwrap `expr`. + * + * Takes an expressions with length of 1 + * such as `((1 2 3))` and unwraps it to `(1 2 3)`. + */ + unwrap(expr: StylusNodeExpression): StylusNode; + + /** + * Coerce JavaScript values to their Stylus equivalents. + */ + coerce(val: any): StylusNode; + coerce(val: any, raw: boolean): StylusNode; + + /** + * Coerce a javascript `Array` to a Stylus `Expression`. + */ + coerceArray(val: any): StylusNodeExpression; + coerceArray(val: any, raw: boolean): StylusNodeExpression; + + /** + * Coerce a javascript object to a Stylus `Expression` or `Object`. + * + * For example `{ foo: 'bar', bar: 'baz' }` would become + * the expression `(foo 'bar') (bar 'baz')`. If `raw` is true + * given `obj` would become a Stylus hash object. + */ + coerceObject(obj: any): StylusNodeExpression; + coerceObject(obj: any, raw: boolean): StylusNodeExpression; + + /** + * Return param names for `fn`. + */ + params(fn: Function): string[]; + + /** + * Merge object `b` with `a`. + */ + merge(a: any, b: any): any; + + /** + * Returns an array with unique values. + */ + uniq(arr: any[]): any[]; + + /** + * Compile selector strings in `arr` from the bottom-up + * to produce the selector combinations. For example + * the following Stylus: + */ + compileSelectors(arr: string[], leaveHidden: boolean): string[]; +} + +interface StylusUrl { + (options: StylusUrlOptions): StylusLiteralFunction; + + mimes: { + ".gif": string; + ".png": string; + ".jpg": string; + ".jpeg": string; + ".svg": string; + ".ttf": string; + ".eot": string; + ".woff": string; + }; +} + +interface StylusMiddleware { + (req, res, next: Function): void; +} + +//#endregion + +//#region Internal Classes + +declare class StylusVisitor { +} + +declare class StylusParser { +} + +declare class StylusEvaluator { +} + +declare class StylusCompiler { +} + +declare class StylusRenderer { //extends events.EventEmitter { + options: StylusRenderOptions; + str: string; + events: any; + + constructor(str: string); + constructor(str: string, options: StylusRenderOptions); + + /** + * Parse and evaluate AST, then callback `fn(err, css, js)`. + */ + render(callback: StylusRenderCallback): void; + + /** + * Get dependencies of the compiled file. + */ + deps(filename: string): string[]; + + /** + * Set option `key` to `val`. + */ + set(key: string, val: any): StylusRenderer; + + /** + * Get option `key`. + */ + get(key: string): any; + + /** + * Include the given `path` to the lookup paths array. + */ + include(path: string): StylusRenderer; + + /** + * Use the given `fn`. + * + * This allows for plugins to alter the renderer in + * any way they wish, exposing paths etc. + */ + use(fn: Function): StylusRenderer; + + /** + * Define function or global var with the given `name`. Optionally + * the function may accept full expressions, by setting `raw` + * to `true`. + */ + define(name: string, fn: Function): StylusRenderer; + define(name: string, node: StylusNode): StylusRenderer; + define(name: string, fn: Function, raw: boolean): StylusRenderer; + define(name: string, node: StylusNode, raw: boolean): StylusRenderer; + + /** + * Import the given `file`. + */ + import(file: string): StylusRenderer; +} + +//#endregion + +//#region Nodes Classes + +declare class StylusNode { + lineno: number; + column: number; + filename: string; + + first: StylusNode; + hash: string; + nodeName: string; + + constructor(); + + /** + * Return a clone of this node. + */ + clone(): StylusNode; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { lineno: number; column: number; filename: string }; + + /** + * Nodes by default evaluate to themselves. + */ + eval(): StylusNode; + + /** + * Return true. + */ + toBoolean(): StylusNodeBoolean; + + /** + * Return the expression, or wrap this node in an expression. + */ + toExpression(): StylusNodeExpression; + + /** + * Return false if `op` is generally not coerced. + */ + shouldCoerce(op: string): boolean; + + /** + * Operate on `right` with the given `op`. + */ + operate(op: string, right: StylusNode): StylusNode; + + /** + * Default coercion throws. + */ + coerce(other: StylusNode): StylusNode; +} + +declare class StylusNodeRoot extends StylusNode { + nodes: StylusNode[]; + + /** + * Push a `node` to this block. + */ + push(node: StylusNode): void; + + /** + * Unshift a `node` to this block. + */ + unshift(node: StylusNode): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { nodes: StylusNode[]; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeString extends StylusNode { + val: string; + string: string; + prefixed: boolean; + quote: string; + + constructor(val: string, quote: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { val: string; quote: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeNumber extends StylusNode { + +} + +declare class StylusNodeBoolean extends StylusNode { + val: boolean; + isTrue: boolean; + isFalse: boolean; + + constructor(); + constructor(val: boolean); + + /** + * Negate the value. + */ + negate(): StylusNodeBoolean; + + /** + * Return 'Boolean'. + */ + inspect(): StylusNodeBoolean; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeObject extends StylusNode { + vals: StylusDictionary; + length: number; + + constructor(); + + /** + * Set `key` to `val`. + */ + set(key: string, value: StylusNode): StylusNodeObject; + + /** + * Get `key`. + */ + get(key: string): StylusNode; + + /** + * Has `key`? + */ + has(key: string): boolean; + + /** + * Convert object to string with properties. + */ + toBlock(): string; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; vals: StylusDictionary; lineno: number; column: number; filename: string };} + +declare class StylusNodeNull extends StylusNode { + isNull: boolean; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeIdent extends StylusNode { + name: string; + string: string; + val: StylusNode; + mixin: boolean; + + isEmpty: boolean; + + constructor(name: string, val: StylusNode); + constructor(name: string, val: StylusNode, mixin: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; val: StylusNode; mixin: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeLiteral extends StylusNode { + val: string; + string: string; + prefixed: boolean; + + constructor(str: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; string: string; val: string; prefixed: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeUnit extends StylusNode { + val: number; + type: string; + + constructor(val: number, type: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: number; type: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeRGBA extends StylusNode { + r: number; + g: number; + b: number; + a: number; + rgba: StylusNodeRGBA; + hsla: StylusNodeHSLA; + + constructor(r: number, g: number, b: number, a: number); + + /** + * Return an `RGBA` without clamping values. + */ + static withoutClamping(r: number, g: number, b: number, a: number): StylusNodeRGBA; + + /** + * Return a `RGBA` from the given `hsla`. + */ + static fromHSLA(hsla: StylusNodeHSLA): StylusNodeRGBA; + + /** + * Add r,g,b,a to the current component values + */ + add(r: number, g: number, b: number, a: number): StylusNodeRGBA; + + /** + * Subtract r,g,b,a from the current component values + */ + substract(r: number, g: number, b: number, a: number): StylusNodeRGBA; + + /** + * Multiply rgb components by `n`. + */ + multiply(n: number): StylusNodeRGBA; + + /** + * Divide rgb components by `n`. + */ + divide(n: number): StylusNodeRGBA; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; r: number; g: number; b: number; a: number; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeHSLA extends StylusNode { + h: number; + s: number; + l: number; + a: number; + hsla: StylusNodeHSLA; + rgba: StylusNodeRGBA; + + constructor(h: number, s: number, l: number, a: number); + + /** + * Return a `HSLA` from the given `hsla`. + */ + static fromRGBA(rgba: StylusNodeRGBA): StylusNodeHSLA; + + /** + * Add h,s,l to the current component values + */ + add(h: number, s: number, l: number): StylusNodeHSLA; + + /** + * Subtract h,s,l from the current component values + */ + substract(h: number, s: number, l: number): StylusNodeHSLA; + + /** + * Adjust lightness by `percent`. + */ + adjustLightness(percent: number): StylusNodeHSLA; + + /** + * djust hue by `deg`. + */ + adjustHue(deg: number): StylusNodeHSLA; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; h: number; s: number; l: number; a: number; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeBlock extends StylusNode { + nodes: StylusNode[]; + parent: StylusNodeBlock; + node: StylusNode; + scope: boolean; + + hasProperties: boolean; + hasMedia: boolean; + isEmpty: boolean; + + constructor(parent: StylusNodeBlock); + constructor(parent: StylusNodeBlock, node: StylusNode); + + /** + * Push a `node` to this block. + */ + push(node: StylusNode): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: StylusNode[]; scope: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeGroup extends StylusNode { + nodes: StylusNode[]; + block: StylusNodeBlock; + + hasOnlyPlaceholders: boolean; + + constructor(); + + /** + * Push the given `selector` node. + */ + push(node: StylusNode): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: StylusNode[]; block: StylusNodeBlock; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeExpression extends StylusNode { + nodes: StylusNode[]; + isList: boolean; + + isEmpty: boolean; + first: StylusNode; + + constructor(isList: boolean); + + /** + * Push the given node. + */ + push(node: StylusNode): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: StylusNode[]; isList: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeProperty extends StylusNode { + segments: StylusNode[]; + expr: StylusNodeExpression; + + constructor(segs: StylusNode[], expr: StylusNodeExpression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: StylusNode[]; name: string; expr?: StylusNodeExpression; literal?: StylusNodeLiteral; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeEach extends StylusNode { + val: string; + key: string; + expr: StylusNodeExpression; + block: StylusNodeBlock; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; key: string; expr: StylusNodeExpression; block: StylusNodeBlock; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeIf extends StylusNode { + cond: StylusNodeExpression; + elses: StylusNodeExpression[]; + block: StylusNodeBlock; + negate: boolean; + + constructor(cond: StylusNodeExpression, negate: boolean); + constructor(cond: StylusNodeExpression, block: StylusNodeBlock); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; cond: StylusNodeExpression; elses: StylusNodeExpression[]; block: StylusNodeBlock; negate: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeCall extends StylusNode { + name: string; + args: StylusNodeExpression; + + constructor(name: string, args: StylusNodeExpression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; args: StylusNodeExpression; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeUnaryOp extends StylusNode { + op: string; + expr: StylusNodeExpression; + + constructor(op: string, expr: StylusNodeExpression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; expr: StylusNodeExpression; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeBinOp extends StylusNode { + op: string; + left: StylusNodeExpression; + right: StylusNodeExpression; + + constructor(op: string, left: StylusNodeExpression, right: StylusNodeExpression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; left: StylusNodeExpression; right: StylusNodeExpression; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeTernary extends StylusNode { + op: string; + trueExpr: StylusNodeExpression; + falseExpr: StylusNodeExpression; + + constructor(op: string, trueExpr: StylusNodeExpression, falseExpr: StylusNodeExpression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; trueExpr: StylusNodeExpression; falseExpr: StylusNodeExpression; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeReturn extends StylusNode { + expr: StylusNodeExpression; + + constructor(expr: StylusNodeExpression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; expr: StylusNodeExpression; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeMedia extends StylusNode { + val: string; + + constructor(val: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeQueryList extends StylusNode { + nodes: StylusNode[]; + + constructor(); + + /** + * Push the given `node`. + */ + push(node: StylusNode): void; + + /** + * Merges this query list with the `other`. + */ + merge(other: MediaQueryList): MediaQueryList; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: StylusNode[]; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeQuery extends StylusNode { + nodes: StylusNodeQueryExpr[]; + type: string; + predicate: string; + + resolvedType: string; + resolvedPredicate: string; + + constructor(); + + /** + * Push the given `expr`. + */ + push(expr: StylusNodeQueryExpr): void; + + /** + * Merges this query with the `other`. + */ + merge(other: StylusNodeQuery): StylusNodeQuery; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: StylusNodeQueryExpr[]; predicate: string; type: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeQueryExpr extends StylusNode { + segments: StylusNode[]; + expr: StylusNodeExpression; + + constructor(segs: StylusNode[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: StylusNode[]; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeParams extends StylusNode { + nodes: StylusNode[]; + + length: number; + + /** + * Push the given `node`. + */ + push(node: StylusNode): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: StylusNode[]; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeComment extends StylusNode { + str: string; + suppress: boolean; + inline: boolean; + + constructor(str: string, suppress: boolean, inline: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; str: string; suppress: boolean; inline: boolean; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeKeyframes extends StylusNode { + segments: StylusNode[]; + prefix: string; + + constructor(segs: StylusNode[]); + constructor(segs: StylusNode[], prefix: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: StylusNode[]; prefix: string; block: StylusNodeBlock; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeMember extends StylusNode { + left: StylusNode; + right: StylusNode; + + constructor(left: StylusNode, right: StylusNode); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; left: StylusNode; right: StylusNode; val?: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeCharset extends StylusNode { + val: string; + + constructor(val: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeNamespace extends StylusNode { + val: string; + prefix: string; + + constructor(val: string, prefix: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; prefix: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeImport extends StylusNode { + path: StylusNodeExpression; + once: boolean; + + constructor(path: StylusNodeExpression); + constructor(path: StylusNodeExpression, once: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; path: StylusNodeExpression; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeExtend extends StylusNode { + selectors: StylusNodeSelector[]; + + constructor(selectors: StylusNodeSelector[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; selectors: StylusNodeSelector[]; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeFunction extends StylusNode { + name: string; + params: StylusNodeParams; + body: StylusNodeBlock; + + constructor(name: string, params: StylusNodeParams, body: StylusNodeBlock); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; params: StylusNodeParams; body: StylusNodeBlock; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeSelector extends StylusNode { + inherits: boolean; + segments: StylusNode[]; + + constructor(segs: StylusNode[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: StylusNode[]; inherits: boolean; val: string; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeArguments extends StylusNodeExpression { + map: StylusDictionary; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; map: StylusDictionary; isList: boolean; preserve: boolean; nodes: StylusNode[]; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeAtblock extends StylusNode { + block: StylusNodeBlock; + nodes: StylusNode[]; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; block: StylusNodeBlock; lineno: number; column: number; filename: string }; +} + +declare class StylusNodeAtrule extends StylusNode { + type: string; + + hasOnlyProperties: boolean; + + constructor(type: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; type: string; segments: StylusNode[]; block?: StylusNodeBlock; lineno: number; column: number; filename: string }; +} + +//#endregion + +//#region Internal Interfaces + +interface StylusDictionary { + [key: string]: T; +} + +interface StylusRenderOptions { + globals: StylusDictionary; + functions: StylusDictionary; + imports: string[]; + paths: string[]; + filename: string; + Evaluator: typeof StylusEvaluator; +} + +interface StylusRenderCallback { + (err: Error, css: string, js: string): void; +} + +interface StylusUrlOptions { + limit?: string; + path: string; +} + +interface StylusLiteralFunction { + (url: string): StylusNodeLiteral; + raw: boolean; +} + +interface StylusExceptionOptions { + filename: string; + context: number; + lineno: number; + column: number; + input: string; +} + +//#endregion + +declare module "stylus" { + export = StylusStatic; +} From ae5e62e5ee9d19fe6751e77fbb4aa0fe66c10068 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 04:25:28 +0200 Subject: [PATCH 038/149] Fix some syntax issues --- stylus/stylus.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts index b4c54b361..19531145b 100644 --- a/stylus/stylus.d.ts +++ b/stylus/stylus.d.ts @@ -60,7 +60,7 @@ interface StylusStatic { /** * Return a url() function with the given `options`. */ - resolver(options): StylusLiteralFunction; + resolver(options: any): StylusLiteralFunction; } //#region Internal Modules @@ -611,7 +611,7 @@ interface StylusUrl { } interface StylusMiddleware { - (req, res, next: Function): void; + (req: any, res: any, next: Function): void; } //#endregion From c46325e6f8d6d3013e7655e0f3414090681d6d39 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 04:27:48 +0200 Subject: [PATCH 039/149] Fix some syntax issues --- node-azure/azure.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index 05cb58dea..cb1f3b694 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -1,7 +1,7 @@ // Type definitions for Azure SDK for Node - v0.9.16 // Project: https://github.com/WindowsAzure/azure-sdk-for-node // Definitions by: Andrew Gaspar , -// Anti Veeranna , +// Anti Veeranna , // Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -884,7 +884,7 @@ declare module "azure" { constructor(container: string, blob: string); static parse(blobXml: any): BlobResult; - static setHeadersFromBlob(webResource: WebResource, blob: BlobResult); + static setHeadersFromBlob(webResource: WebResource, blob: BlobResult): void; getPropertiesFromHeaders(headers: any): void; } From 82372b3bbc0a16a82e12406d54592899473d52d7 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 17:17:03 +0200 Subject: [PATCH 040/149] Add passport-local tests suite --- passport-local/passport-local-tests.ts | 53 ++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 passport-local/passport-local-tests.ts diff --git a/passport-local/passport-local-tests.ts b/passport-local/passport-local-tests.ts new file mode 100644 index 000000000..de799a4d8 --- /dev/null +++ b/passport-local/passport-local-tests.ts @@ -0,0 +1,53 @@ +/** + * Created by Maxime LUCE . + */ + +import express = require("express"); +import passport = require('passport'); +import local = require('passport-local'); + +//#region Test Models +interface IUser { + username: string; +} + +class User implements IUser { + public username: string; + public password: string; + + static findOne(user: IUser, callback: (err: Error, user: User) => void): void { + callback(null, new User()); + } + + verifyPassword(password: string): boolean { + return true; + } +} +//#endregion + +// Sample from https://github.com/jaredhanson/passport-local#configure-strategy +passport.use(new local.Strategy(function (username, password, done) { + User.findOne({ username: username }, function (err, user) { + if (err) { + return done(err); + } + + if (!user) { + return done(null, false); + } + + if (!user.verifyPassword(password)) { + return done(null, false); + } + + return done(null, user); + }); +})); + +// Sample from https://github.com/jaredhanson/passport-local#authenticate-requests +var app = express(); +app.post('/login', + passport.authenticate('local', { failureRedirect: '/login' }), + function (req, res) { + res.redirect('/'); + }); From eb1d7786e2de5a11763e2360b25277540ebcf1f1 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 18:13:02 +0200 Subject: [PATCH 041/149] Fix issue in sendgrid send method definition --- sendgrid/sendgrid.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/sendgrid/sendgrid.d.ts b/sendgrid/sendgrid.d.ts index 96d52601e..6d4974a03 100644 --- a/sendgrid/sendgrid.d.ts +++ b/sendgrid/sendgrid.d.ts @@ -109,6 +109,7 @@ interface Sendgrid { options: SendgridOptionsExport; Email: typeof PrivateSendgridEmail; + send(email: SendgridEmailOptions, callback: (err: Error, json: any) => any): void; send(email: PrivateSendgridEmail, callback: (err: Error, json: any) => any): void; } From c4a339b149a41136addf1f82a926e3ed0dd00c11 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 18:13:16 +0200 Subject: [PATCH 042/149] Add tests suite for sendgrid --- sendgrid/sendgrid-tests.ts | 246 +++++++++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 sendgrid/sendgrid-tests.ts diff --git a/sendgrid/sendgrid-tests.ts b/sendgrid/sendgrid-tests.ts new file mode 100644 index 000000000..17a48dd99 --- /dev/null +++ b/sendgrid/sendgrid-tests.ts @@ -0,0 +1,246 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/sendgrid/sendgrid-nodejs#usage + */ + +/// +/// + +import sg = require("sendgrid"); +var sendgrid: Sendgrid = sg("api_user", "api_key"); + +/* + * Simple Usage + */ +var payload = { + to: 'to@example.com', + from: 'from@other.com', + subject: 'Saying Hi', + text: 'This is my first email through SendGrid' +}; +sendgrid.send(payload, function (err, json) { + if (err) { + console.error(err); + } + + console.log(json); +}); + +/** + * Email: + * https://github.com/sendgrid/sendgrid-nodejs#email + */ +var email = new sendgrid.Email({ + to: 'foo@bar.com', + from: 'you@yourself.com', + subject: 'Subject goes here', + text: 'Hello world' +}); + +sendgrid.send(email, function (err, json) { + if (err) { + return console.error(err); + } + console.log(json); +}); + +/** + * Setting Params + * https://github.com/sendgrid/sendgrid-nodejs#setting-params + */ +var email = new sendgrid.Email({ to: 'person@email.com' }); +email.to = "different@email.com"; +email.replyto = "reply-here@email.com"; +email.subject = "This is a subject"; + +/** + * addTo + * https://github.com/sendgrid/sendgrid-nodejs#addto + */ +var email = new sendgrid.Email(); +email.addTo('foo@bar.com'); +email.addTo('another@another.com'); +sendgrid.send(email, function (err, json) { }); + + +/** + * setFrom + * https://github.com/sendgrid/sendgrid-nodejs#setfrom + */ +var email = new sendgrid.Email(); +email.setFrom('foo@bar.com'); +sendgrid.send(email, function (err, json) { }); + +/** + * setSubject + * https://github.com/sendgrid/sendgrid-nodejs#setsubject + */ +var email = new sendgrid.Email(); +email.setSubject('Some subject'); +sendgrid.send(email, function (err, json) { }); + +/** + * setText + * https://github.com/sendgrid/sendgrid-nodejs#settext + */ +var email = new sendgrid.Email(); +email.setText('Some text'); +sendgrid.send(email, function (err, json) { }); + +/** + * setHtml + * https://github.com/sendgrid/sendgrid-nodejs#sethtml + */ +var email = new sendgrid.Email(); +email.setHtml('

Some html

'); +sendgrid.send(email, function (err, json) { }); + +/** + * addHeader + * https://github.com/sendgrid/sendgrid-nodejs#addheader + */ +var email = new sendgrid.Email(); +email.setHeaders({ full: 'hearts' }); // headers = {full: 'hearts'} +email.addHeader('spin', 'attack'); // headers = {full: 'hearts', spin: 'attack'} +email.addHeader('mask', 'salesman'); // headers = {full: 'hearts', spin: 'attack', mask: 'salesman'} +sendgrid.send(email, function (err, json) { }); + +/** + * setHeaders + * https://github.com/sendgrid/sendgrid-nodejs#setheaders + */ +var email = new sendgrid.Email(); +email.setHeaders({ full: 'hearts' }); // headers = {full: 'hearts'} +email.setHeaders({ mask: 'salesman' }); // headers = {mask: 'salesman'} +sendgrid.send(email, function (err, json) { }); + +/** + * addSubstitution + * https://github.com/sendgrid/sendgrid-nodejs#addsubstitution + */ +var email = new sendgrid.Email(); +email.addSubstitution('keep', 'secret'); // sub = {keep: ['secret']} +email.addSubstitution('other', ['one', 'two']); // sub = {keep: ['secret'], other: ['one', 'two']} + +/** + * setSubstitutions + * https://github.com/sendgrid/sendgrid-nodejs#setsubstitutions + */ +var email = new sendgrid.Email(); +email.setSubstitutions({ keep: ['secret'], other: ['one', 'two'] }); // sub = {keep: ['secret'], other: ['one', 'two']}); + +/** + * addSection + * https://github.com/sendgrid/sendgrid-nodejs#addsection + */ +var email = new sendgrid.Email(); +email.addSection({ '-charge-': 'This ship is useless.' }); // section = {'-charge-': 'This ship is useless.'} + +/** + * setSections + * https://github.com/sendgrid/sendgrid-nodejs#setsections + */ +var email = new sendgrid.Email(); +email.setSections({ '-charge-': 'This ship is useless.' }); // section = {'-charge-': 'This ship is useless.'} + +/** + * addUniqueArg + * https://github.com/sendgrid/sendgrid-nodejs#adduniquearg + */ +var email = new sendgrid.Email(); +email.setUniqueArgs({ cow: 'chicken' }); // unique_args = {cow: 'chicken'} +email.addUniqueArg({ cat: 'dog' }); // unique_args = {cow: 'chicken', cat: 'dog'} + +/** + * setUniqueArgs + * https://github.com/sendgrid/sendgrid-nodejs#setuniqueargs + */ +var email = new sendgrid.Email(); +email.setUniqueArgs({ cow: 'chicken' }); // unique_args = {cow: 'chicken'} +email.setUniqueArgs({ dad: 'proud' }); // unique_args = {dad: 'proud'} + + +/** + * addCategory + * https://github.com/sendgrid/sendgrid-nodejs#addcategory + */ +var email = new sendgrid.Email(); +email.addCategory('tactics'); // category = ['tactics'] +email.addCategory('advanced'); // category = ['tactics', 'advanced'] + +/** + * setCategories + * https://github.com/sendgrid/sendgrid-nodejs#setcategories + */ +var email = new sendgrid.Email(); +email.setCategories(['tactics']); // category = ['tactics'] +email.setCategories(['snowball-fight']); // category = ['snowball-fight'] + +/** + * addFilter + * https://github.com/sendgrid/sendgrid-nodejs#addfilter + */ +var email = new sendgrid.Email(); +email.addFilter('footer', 'enable', 1); +email.addFilter('footer', 'text/html', 'boo'); + +/** + * setFilters + * https://github.com/sendgrid/sendgrid-nodejs#setfilters + */ +var email = new sendgrid.Email(); +var email = new sendgrid.Email(); +email.setFilters({ + 'footer': { + 'setting': { + 'enable': 1, + 'text/plain': 'You can haz footers!' + } + } +}); + +/** + * addFile + * https://github.com/sendgrid/sendgrid-nodejs#addfile + */ +var email = new sendgrid.Email(); +email.addFile({ + filename: 'secret.txt', + content: new Buffer('You will never know....') +}); +// or +email.addFile({ + filename: 'icon.jpg', + url: 'http://i.imgur.com/2fDh8.jpg' +}); +// or +email.addFile({ + path: '../files/resume.txt' +}); +// or +email.addFile({ + cid: 'the_logo', // should match cid value in html + path: '../files/logo.png' +}); +email.setHtml('
Our logo:
'); + +/** + * Options - Changing URL + * https://github.com/sendgrid/sendgrid-nodejs#changing-url + */ +var sendgrid1 = sg('username', 'password', { "protocol": "http", "host": "sendgrid.org", "endpoint": "/send", "port": "80" }); +var sendgrid2 = sg('username', 'password', { "uri": "http://sendgrid.org:80/send" }); + +/** + * Options - Request + * https://github.com/sendgrid/sendgrid-nodejs#request + */ +var sendgrid3 = sg('username', 'password', { proxy: "http://localproxy:3128" }); +// or +var https = require('https'); +var agent = new https.Agent(); +agent.maxSockets = 500; // Set Max Sockets to 500 +var sendgrid4 = sg('username', 'password', { web: { pool: agent } }); + + From 9953dfefde47178442e062ff890ee2959ef30998 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 19:15:30 +0200 Subject: [PATCH 043/149] Add ghost module and fix module export issue --- sendgrid/sendgrid.d.ts | 248 ++++++++++++++++++++++++----------------- 1 file changed, 147 insertions(+), 101 deletions(-) diff --git a/sendgrid/sendgrid.d.ts b/sendgrid/sendgrid.d.ts index 6d4974a03..80b5d78ee 100644 --- a/sendgrid/sendgrid.d.ts +++ b/sendgrid/sendgrid.d.ts @@ -3,121 +3,167 @@ // Definitions by: Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface SendgridUriParts { - protocol: string; - host: string; - port: string; - endpoint: string; -} +declare module Sendgrid { + //#region Options -interface SendgridOptions { - protocol?: string; - host?: string; - port?: string; - endpoint?: string; - uri?: string; -} + export interface UriParts { + protocol: string; + host: string; + port: string; + endpoint: string; + } -interface SendgridOptionsExport { - uriParts: SendgridUriParts; - uri: string; -} + export interface Options { + protocol?: string; + host?: string; + port?: string; + endpoint?: string; + uri?: string; + proxy?: string; + web?: { + pool?: any; + } + } -interface SendgridEmailOptions { - to?: any; - toname?: string; - from?: string; - fromname?: string; - subject?: string; - text?: string; - html?: string; - bcc?: any; - replyto?: string; - date?: Date; - headers?: { [key: string]: string }; - files?: SendgridEmailFileOptions[]; - smtpapi?: any; -} + export interface OptionsExport { + uriParts: UriParts; + uri: string; -declare class PrivateSendgridEmail { - to: any; - toname: string; - from: string; - fromname: string; - subject: string; - text: string; - html: string; - bcc: any; - replyto: string; - date: Date; - headers: { [key: string]: string }; - files: PrivateSendgridFile[]; - smtpapi: any; + proxy?: string; + web?: { + pool?: any; + } + } - constructor(); - constructor(options: SendgridEmailOptions); + //#endregion - addTo(address: string): void; - addHeader(type: string, value: string): void; - addSubstitution(type: string, value: string): void; - addSubstitution(type: string, value: string[]): void; - addSection(section: { [key: string]: string }): void; - addUniqueArg(uarg: { [key: string]: string }): void; - addCategory(category: string): void; - addFilter(filter: string, command: string, value: number): void; - addFilter(filter: string, command: string, value: string): void; - addFile(file: SendgridEmailFileOptions): void; + //#region Email - setFrom(address: string): void; - setSubject(subject: string): void; - setText(text: string): void; - setHtml(html: string): void; - setHeaders(headers: { [key: string]: string }): void; - setSubstitutions(substitutions: { [key: string]: string[] }): void; - setSections(sections: { [key: string]: string }): void; - setUniqueArgs(uargs: { [key: string]: string }): void; - setCategories(categories: string[]): void; - setFilters(filters: any): void; -} + export interface EmailOptions { + to?: any; + toname?: string; + from?: string; + fromname?: string; + subject?: string; + text?: string; + html?: string; + bcc?: any; + replyto?: string; + date?: Date; + headers?: { [key: string]: string }; + files?: SendgridEmailFileOptions[]; + smtpapi?: any; + } -interface SendgridEmailFileOptions { - filename?: string; - contentType?: string; - cid?: string; - path?: string; - url?: string; - content?: any; -} + export class Email { + to: any; + toname: string; + from: string; + fromname: string; + subject: string; + text: string; + html: string; + bcc: any; + replyto: string; + date: Date; + headers: { [key: string]: string }; + files: FileHandler[]; + smtpapi: any; -declare class PrivateSendgridFile { - filename: string; - contentType: string; - cid: string; + constructor(); + constructor(options: EmailOptions); - type: string; - content: string; - path: string; - url: string; + addTo(address: string): void; + addHeader(type: string, value: string): void; + addSubstitution(type: string, value: string): void; + addSubstitution(type: string, value: string[]): void; + addSection(section: { [key: string]: string }): void; + addUniqueArg(uarg: { [key: string]: string }): void; + addCategory(category: string): void; + addFilter(filter: string, command: string, value: number): void; + addFilter(filter: string, command: string, value: string): void; + addFile(file: FileHandlerOptions): void; - loadContent(callback: (hasError: boolean, error: Error) => any): void; -} + setFrom(address: string): void; + setSubject(subject: string): void; + setText(text: string): void; + setHtml(html: string): void; + setHeaders(headers: { [key: string]: string }): void; + setSubstitutions(substitutions: { [key: string]: string[] }): void; + setSections(sections: { [key: string]: string }): void; + setUniqueArgs(uargs: { [key: string]: string }): void; + setCategories(categories: string[]): void; + setFilters(filters: any): void; + } -interface Sendgrid { - version: string; - api_user: string; - api_key: string; - options: SendgridOptionsExport; - Email: typeof PrivateSendgridEmail; + //#endregion - send(email: SendgridEmailOptions, callback: (err: Error, json: any) => any): void; - send(email: PrivateSendgridEmail, callback: (err: Error, json: any) => any): void; + //#region FileHandler + + export interface FileHandlerOptions { + filename?: string; + contentType?: string; + cid?: string; + path?: string; + url?: string; + content?: any; + } + + export class FileHandler { + filename: string; + contentType: string; + cid: string; + + type: string; + content: string; + path: string; + url: string; + + constructor(options: FileHandlerOptions); + + loadContent(callback: HandlerCallback): void; + + static handlers: { + content: Handler; + path: Handler; + url: Handler; + none: Handler; + }; + } + + export interface Handler { + (file: FileHandler, callback: HandlerCallback): void; + } + + export interface HandlerCallback { + (hasError: boolean, error: Error): void; + (hasError: boolean, error: string): void; + } + + //#endregion + + //#region Sendgrid Class + + interface Constructor { + (api_user: string, api_key: string, options?: Options): Instance; + new (api_user: string, api_key: string, options?: Options): Instance; + } + + export interface Instance { + version: string; + api_user: string; + api_key: string; + options: OptionsExport; + Email: typeof Email; + + send(email: EmailOptions, callback: (err: Error, json: any) => any): void; + send(email: Email, callback: (err: Error, json: any) => any): void; + } + + //#endregion } declare module "sendgrid" { - interface SendgridConstructor { - (api_user: string, api_key: string, options?: SendgridOptions): Sendgrid; - new (api_user: string, api_key: string, options?: SendgridOptions): Sendgrid; - } - - export = SendgridConstructor; + var ctor: Sendgrid.Constructor; + export = ctor; } \ No newline at end of file From 2f216035fd46070aa5828be445262ea6bef6f926 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 19:16:13 +0200 Subject: [PATCH 044/149] Update tests to match definitions improvements --- sendgrid/sendgrid-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sendgrid/sendgrid-tests.ts b/sendgrid/sendgrid-tests.ts index 17a48dd99..e7d34feb0 100644 --- a/sendgrid/sendgrid-tests.ts +++ b/sendgrid/sendgrid-tests.ts @@ -8,7 +8,7 @@ /// import sg = require("sendgrid"); -var sendgrid: Sendgrid = sg("api_user", "api_key"); +var sendgrid = sg("api_user", "api_key"); /* * Simple Usage @@ -238,7 +238,7 @@ var sendgrid2 = sg('username', 'password', { "uri": "http://sendgrid.org:80/send */ var sendgrid3 = sg('username', 'password', { proxy: "http://localproxy:3128" }); // or -var https = require('https'); +import https = require('https'); var agent = new https.Agent(); agent.maxSockets = 500; // Set Max Sockets to 500 var sendgrid4 = sg('username', 'password', { web: { pool: agent } }); From e9e292d20d5c865da762c1e759313ff5607971ad Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 19:17:37 +0200 Subject: [PATCH 045/149] Fix issue in sendgrid EmailOptions --- sendgrid/sendgrid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sendgrid/sendgrid.d.ts b/sendgrid/sendgrid.d.ts index 80b5d78ee..7f644b65b 100644 --- a/sendgrid/sendgrid.d.ts +++ b/sendgrid/sendgrid.d.ts @@ -51,7 +51,7 @@ declare module Sendgrid { replyto?: string; date?: Date; headers?: { [key: string]: string }; - files?: SendgridEmailFileOptions[]; + files?: FileHandlerOptions[]; smtpapi?: any; } From d6fe5776f8d135b3293e5fa2f9d01f8417ffab9d Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 19:28:51 +0200 Subject: [PATCH 046/149] Add test suite for jsonwebtoken package --- jsonwebtoken/jsonwebtoken-tests.ts | 64 ++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 jsonwebtoken/jsonwebtoken-tests.ts diff --git a/jsonwebtoken/jsonwebtoken-tests.ts b/jsonwebtoken/jsonwebtoken-tests.ts new file mode 100644 index 000000000..52f116335 --- /dev/null +++ b/jsonwebtoken/jsonwebtoken-tests.ts @@ -0,0 +1,64 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/auth0/node-jsonwebtoken. + */ + +/// +/// + +import jwt = require("jsonwebtoken"); +import fs = require("fs"); + +var token: string; +var cert: Buffer; + +/** + * jwt.sign + * https://github.com/auth0/node-jsonwebtoken#usage + */ +// sign with default (HMAC SHA256) +token = jwt.sign({ foo: 'bar' }, 'shhhhh'); + +// sign with RSA SHA256 +cert = fs.readFileSync('private.key'); // get private key +token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'}); + +/** + * jwt.verify + * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback + */ +// verify a token symmetric +jwt.verify(token, 'shhhhh', function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// invalid token +jwt.verify(token, 'wrong-secret', function(err, decoded) { + // err + // decoded undefined +}); + +// verify a token asymmetric +cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// verify audience +cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { + // if audience mismatch, err == invalid audience +}); + +// verify issuer +cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { + // if issuer mismatch, err == invalid issuer +}); + +/** + * jwt.decode + * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken + */ +var decoded = jwt.decode(token); From 3f84d98bbac155c5f641c96e7e0d42c8cdb74c96 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 19:38:14 +0200 Subject: [PATCH 047/149] Improve functions definitions --- jsonwebtoken/jsonwebtoken.d.ts | 55 +++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/jsonwebtoken/jsonwebtoken.d.ts b/jsonwebtoken/jsonwebtoken.d.ts index 16256c24a..4deaf36ce 100644 --- a/jsonwebtoken/jsonwebtoken.d.ts +++ b/jsonwebtoken/jsonwebtoken.d.ts @@ -3,9 +3,11 @@ // Definitions by: Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "jsonwebtoken" { - interface SignOptions { + export interface SignOptions { /** * Signature algorithm. Could be one of these values : * - HS256: HMAC using SHA-256 hash algorithm @@ -27,40 +29,51 @@ declare module "jsonwebtoken" { issuer?: string; } - interface VerifyOptions { + export interface VerifyOptions { audience?: string; issuer?: string; } + export interface VerifyCallbak { + (err: Error, decoded: any): void; + } + /** * Sign the given payload into a JSON Web Token string - * @param {string|object|buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {string|buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} options - Options for the signature - * @returns The JSON Web Token string + * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string + * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * @param {SignOptions} [options] - Options for the signature + * @returns {String} The JSON Web Token string */ - function sign(payload: any, secretOrPrivateKey: any, options?: SignOptions): string; + export function sign(payload: string, secretOrPrivateKey: string): string; + export function sign(payload: string, secretOrPrivateKey: Buffer): string; + export function sign(payload: Buffer, secretOrPrivateKey: string): string; + export function sign(payload: Buffer, secretOrPrivateKey: Buffer): string; + export function sign(payload: Object, secretOrPrivateKey: string): string; + export function sign(payload: Object, secretOrPrivateKey: Buffer): string; + export function sign(payload: string, secretOrPrivateKey: string, options: SignOptions): string; + export function sign(payload: string, secretOrPrivateKey: Buffer, options: SignOptions): string; + export function sign(payload: Buffer, secretOrPrivateKey: string, options: SignOptions): string; + export function sign(payload: Buffer, secretOrPrivateKey: Buffer, options: SignOptions): string; + export function sign(payload: Object, secretOrPrivateKey: string, options: SignOptions): string; + export function sign(payload: Object, secretOrPrivateKey: Buffer, options: SignOptions): string; /** * Verify given token using a secret or a public key to get a decoded token - * @param {string} token - JWT string to verify - * @param {string|buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * @param {String} token - JWT string to verify + * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * @param {VerifyOptions} [options] - Options for the verification * @param {Function} callback - Callback to get the decoded token on */ - function verify(token: string, secretOrPublicKey: any, callback: (err: Error, decoded: {}) => void): void; - /** - * Verify given token using a secret or a public key to get a decoded token - * @param {string} token - JWT string to verify - * @param {string|buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} options - Options for the verification - * @param {Function} callback - Callback to get the decoded token on - */ - function verify(token: string, secretOrPublicKey: any, options: VerifyOptions, callback: (err: Error, decoded: {}) => void): void; + function verify(token: string, secretOrPublicKey: string, callback: VerifyCallbak): void; + function verify(token: string, secretOrPublicKey: Buffer, callback: VerifyCallbak): void; + function verify(token: string, secretOrPublicKey: string, options: VerifyOptions, callback: VerifyCallbak): void; + function verify(token: string, secretOrPublicKey: Buffer, options: VerifyOptions, callback: VerifyCallbak): void; /** * Returns the decoded payload without verifying if the signature is valid. - * @param {string} token - JWT string to decode - * @returns The decoded Token + * @param {String} token - JWT string to decode + * @returns {Object} The decoded Token */ - function decode(token: string): {}; + function decode(token: string): any; } From fc1e738898b1b4ea018227b4bf74b8abd1cad62f Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 20:08:00 +0200 Subject: [PATCH 048/149] Add some overload in definitions --- i18n-node/i18n-node.d.ts | 103 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 2 deletions(-) diff --git a/i18n-node/i18n-node.d.ts b/i18n-node/i18n-node.d.ts index 5eb5043da..dbe2a2c97 100644 --- a/i18n-node/i18n-node.d.ts +++ b/i18n-node/i18n-node.d.ts @@ -46,10 +46,18 @@ declare module i18n { */ objectNotation?: boolean; } + export interface TranslateOptions { + phrase: string; + locale?: string; + } export interface PluralOptions { singular: string; plural: string; count: number; + locale?: string; + } + export interface Replacements { + [key: string]: string; } export interface LocaleCatalog { @@ -73,12 +81,44 @@ declare module i18n { */ function init(request: Express.Request, response: Express.Response, next?: Function): void; + //#region __() + /** * Translate the given phrase using locale configuration * @param {string} phrase - The phrase to translate * @returns {string} The translated phrase */ function __(phrase: string, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + function __(phrase: string, replacements: Replacements): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + function __(options: TranslateOptions): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + function __(options: TranslateOptions, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + function __(options: TranslateOptions, replacements: Replacements): string; + + //#endregion + + //#region __n() /** * Translate with plural condition the given phrase and count using locale configuration @@ -86,6 +126,14 @@ declare module i18n { * @returns {string} The translated phrase */ function __n(options: PluralOptions): string; + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + function __n(options: PluralOptions, count: number): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 @@ -98,11 +146,15 @@ declare module i18n { * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 * @param {string} plural - The plural pharse to translate if count is > 1 - * @param {string} count - The number which allow to select from plural to singular + * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ function __n(singular: string, plural: string, count: string): string; + //#endregion + + //#region Locale + /** * Change the current active locale * @param {string} locale - The locale to set as default @@ -127,6 +179,10 @@ declare module i18n { */ function getLocale(request: Express.Request): string; + //#endregion + + //#region Catalog + /** * Get the current global catalog * @returns {GlobalCatalog} The current global catalog @@ -152,6 +208,8 @@ declare module i18n { */ function getCatalog(request: Express.Request, locale: string): LocaleCatalog; + //#endregion + /** * Override the current request locale by using the query param (?locale=en) * @param {Express.Request} [request] - The request to override locale for @@ -168,12 +226,44 @@ declare module i18n { interface i18nAPI { locale: string; + //#region __() + /** * Translate the given phrase using locale configuration * @param {string} phrase - The phrase to translate * @returns {string} The translated phrase */ __(phrase: string, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + __(phrase: string, replacements: i18n.Replacements): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + __(options: i18n.TranslateOptions): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + __(options: i18n.TranslateOptions, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + __(options: i18n.TranslateOptions, replacements: i18n.Replacements): string; + + //#endregion + + //#region __n() /** * Translate with plural condition the given phrase and count using locale configuration @@ -181,6 +271,14 @@ interface i18nAPI { * @returns {string} The translated phrase */ __n(options: i18n.PluralOptions): string; + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + __n(options: i18n.PluralOptions, count: number): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 @@ -193,11 +291,12 @@ interface i18nAPI { * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 * @param {string} plural - The plural pharse to translate if count is > 1 - * @param {string} count - The number which allow to select from plural to singular + * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ __n(singular: string, plural: string, count: string): string; + //#endregion /** * Get the current active locale From 3ce55491f230c5366305d3e1d0f7d990b864f19e Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 20:08:14 +0200 Subject: [PATCH 049/149] Add test suite for i18n-node --- i18n-node/i18n-node-tests.ts | 140 +++++++++++++++++++++++++++++++++++ i18n-node/i18n-node.d.ts | 2 +- 2 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 i18n-node/i18n-node-tests.ts diff --git a/i18n-node/i18n-node-tests.ts b/i18n-node/i18n-node-tests.ts new file mode 100644 index 000000000..f4403e5c1 --- /dev/null +++ b/i18n-node/i18n-node-tests.ts @@ -0,0 +1,140 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/mashpie/i18n-node. + */ + +/// +/// +/// + +import express = require("express"); +import i18n = require("i18n"); + +var app = express(); +var req: express.Request; + +/** + * Configuration + * https://github.com/mashpie/i18n-node#configure + */ +i18n.configure({ + locales: ['en', 'de'], + directory: __dirname + '/locales' +}); + +i18n.configure({ + // setup some locales - other locales default to en silently + locales: ['en', 'de'], + + // you may alter a site wide default locale + defaultLocale: 'de', + + // sets a custom cookie name to parse locale settings from - defaults to NULL + cookie: 'yourcookiename', + + // where to store json files - defaults to './locales' relative to modules directory + directory: './mylocales', + + // whether to write new locale information to disk - defaults to true + updateFiles: false, + + // what to use as the indentation unit - defaults to "\t" + indent: "\t", + + // setting extension of json files - defaults to '.json' (you might want to set this to '.js' according to webtranslateit) + extension: '.js', + + // setting prefix of json files name - default to none '' (in case you use different locale files naming scheme (webapp-en.json), rather then just en.json) + prefix: 'webapp-', + + // enable object notation + objectNotation: false +}); + +/** + * Usage in global scope + * https://github.com/mashpie/i18n-node#example-usage-in-global-scope + */ +var greeting = i18n.__('Hello'); + +/** + * Usage in Express + * https://github.com/mashpie/i18n-node#example-usage-in-expressjs + */ +// Configuration +app.configure(function () { + // default: using 'accept-language' header to guess language settings + app.use(i18n.init); +}); + +app.get('/de', function (_req, res) { + var greeting = res.__('Hello'); +}); + +/** + * __() + * https://github.com/mashpie/i18n-node#__ + */ +// global (this.locale == 'de') +i18n.__('Hello'); // Hallo +i18n.__('Hello %s', 'Marcus'); // Hallo Marcus +i18n.__('Hello {{name}}', { name: 'Marcus' }); // Hallo Marcus + +// scoped via req object (req.locale == 'de') +req.__('Hello'); // Hallo +req.__('Hello %s', 'Marcus'); // Hallo Marcus +req.__('Hello {{name}}', { name: 'Marcus' }); // Hallo Marcus + +// passing specific locale +i18n.__({ phrase: 'Hello', locale: 'fr' }); // Salut +i18n.__({ phrase: 'Hello %s', locale: 'fr' }, 'Marcus'); // Salut Marcus +i18n.__({ phrase: 'Hello {{name}}', locale: 'fr' }, { name: 'Marcus' }); // Salut Marcus + +/** + * __n() + * https://github.com/mashpie/i18n-node#__n + */ +// global (this.locale == 'de') +i18n.__n("%s cat", "%s cats", 1); // 1 Katze +i18n.__n("%s cat", "%s cats", 3); // 3 Katzen + +// scoped via req object (req.locale == 'de') +req.__n("%s cat", "%s cats", 1); // 1 Katze +req.__n("%s cat", "%s cats", 3); // 3 Katzen + +// passing specific locale +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr" }, 1); // 1 chat +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr" }, 3); // 3 chat +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr", count: 1 }); // 1 chat +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr", count: 3 }); // 3 chat + +/** + * setLocale() + * https://github.com/mashpie/i18n-node#setlocale + */ +i18n.setLocale('de'); +i18n.setLocale(req, 'de'); +req.setLocale('de'); + +/** + * getLocale() + * https://github.com/mashpie/i18n-node#getlocale + */ +i18n.getLocale(); // --> de +i18n.getLocale(req); // --> de +req.getLocale(); // --> de + +/** + * getCatalog() + * https://github.com/mashpie/i18n-node#getcatalog + */ +i18n.getCatalog(); // returns all locales +i18n.getCatalog('de'); // returns just 'de' + +i18n.getCatalog(req); // returns all locales +i18n.getCatalog(req, 'de'); // returns just 'de' + +req.getCatalog(); // returns all locales +req.getCatalog('de'); // returns just 'de' + diff --git a/i18n-node/i18n-node.d.ts b/i18n-node/i18n-node.d.ts index dbe2a2c97..348c2f268 100644 --- a/i18n-node/i18n-node.d.ts +++ b/i18n-node/i18n-node.d.ts @@ -53,7 +53,7 @@ declare module i18n { export interface PluralOptions { singular: string; plural: string; - count: number; + count?: number; locale?: string; } export interface Replacements { From 75f23e7c4371c6835c1e6af4c5ed6e5182287a11 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 21:21:46 +0200 Subject: [PATCH 050/149] Add ghost module for stylus --- stylus/stylus.d.ts | 2802 ++++++++++++++++++++++---------------------- 1 file changed, 1407 insertions(+), 1395 deletions(-) diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts index 19531145b..dffb04cf0 100644 --- a/stylus/stylus.d.ts +++ b/stylus/stylus.d.ts @@ -5,1412 +5,1424 @@ /// -interface StylusStatic { - /** - * Return a new `Renderer` for the given `str` and `options`. - */ - (str: string, options: StylusRenderOptions): StylusRenderer; +declare module Stylus { - /** - * Library version. - */ - version: string; + export interface Static { + /** + * Return a new `Renderer` for the given `str` and `options`. + */ + (str: string): Renderer; + (str: string, options: RenderOptions): Renderer; - /** - * Expose nodes. - */ - nodes: StylusNodeStatic; + /** + * Library version. + */ + version: string; - /** - * Expose BIFs. - */ - functions: StylusFunctions; + /** + * Expose nodes. + */ + nodes: NodeStatic; - /** - * Expose utils. - */ - utils: StylusUtils; + /** + * Expose BIFs. + */ + functions: Functions; - Visitor: typeof StylusVisitor; - Parser: typeof StylusParser; - Evaluator: typeof StylusEvaluator; - Compiler: typeof StylusCompiler; + /** + * Expose utils. + */ + utils: Utils; - /** - * Expose middleware. - */ - middleware(dir: string): StylusMiddleware; + Visitor: typeof Visitor; + Parser: typeof Parser; + Evaluator: typeof Evaluator; + Compiler: typeof Compiler; - /** - * Convert the given `css` to `stylus` source. - */ - convertCSS(css: string): string; + /** + * Expose middleware. + */ + middleware(dir: string): Middleware; - /** - * Render the given `str` with `options` and callback `fn(err, css)`. - */ - render(str: string, callback: StylusRenderCallback): string; - render(str: string, options: StylusRenderOptions, callback: StylusRenderCallback): string; + /** + * Convert the given `css` to `stylus` source. + */ + convertCSS(css: string): string; - /** - * Return a url() function with the given `options`. - */ - url: StylusUrl; + /** + * Render the given `str` with `options` and callback `fn(err, css)`. + */ + render(str: string, callback: RenderCallback): void; + render(str: string, options: RenderOptions, callback: RenderCallback): void; - /** - * Return a url() function with the given `options`. - */ - resolver(options: any): StylusLiteralFunction; + /** + * Return a url() function with the given `options`. + */ + url: UrlFunction; + + /** + * Return a url() function with the given `options`. + */ + resolver(options: any): LiteralFunction; + } + + //#region Internal Modules + + export interface NodeStatic { + Node: typeof Nodes.Node; + Root: typeof Nodes.Root; + Null: typeof Nodes.Null; + Each: typeof Nodes.Each; + If: typeof Nodes.If; + Call: typeof Nodes.Call; + UnaryOp: typeof Nodes.UnaryOp; + BinOp: typeof Nodes.BinOp; + Ternary: typeof Nodes.Ternary; + Block: typeof Nodes.Block; + Unit: typeof Nodes.Unit; + String: typeof Nodes.String; + HSLA: typeof Nodes.HSLA; + RGBA: typeof Nodes.RGBA; + Ident: typeof Nodes.Ident; + Group: typeof Nodes.Group; + Literal: typeof Nodes.Literal; + Boolean: typeof Nodes.Boolean; + Return: typeof Nodes.Return; + Media: typeof Nodes.Media; + QueryList: typeof Nodes.QueryList; + Query: typeof Nodes.Query; + QueryExpr: typeof Nodes.QueryExpr; + Params: typeof Nodes.Params; + Comment: typeof Nodes.Comment; + Keyframes: typeof Nodes.Keyframes; + Member: typeof Nodes.Member; + Charset: typeof Nodes.Charset; + Namespace: typeof Nodes.Namespace; + Import: typeof Nodes.Import; + Extend: typeof Nodes.Extend; + Object: typeof Nodes.Object; + Function: typeof Nodes.Function; + Property: typeof Nodes.Property; + Selector: typeof Nodes.Selector; + Expression: typeof Nodes.Expression; + Arguments: typeof Nodes.Arguments; + Atblock: typeof Nodes.Atblock; + Atrule: typeof Nodes.Atrule; + + true: Nodes.Boolean; + false: Nodes.Boolean; + null: Nodes.Null; + } + + export interface Functions { + /** + * Convert the given `color` to an `HSLA` node, + * or h,s,l,a component values. + */ + hsla(rgba: Nodes.RGBA): Nodes.HSLA; + hsla(hsla: Nodes.HSLA): Nodes.HSLA; + hsla(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit, alpha: Nodes.Unit): Nodes.HSLA; + + /** + * Convert the given `color` to an `HSLA` node, + * or h,s,l component values. + */ + hsl(rgba: Nodes.RGBA): Nodes.HSLA; + hsl(hsla: Nodes.HSLA): Nodes.HSLA; + hsl(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit): Nodes.HSLA; + + /** + * Return type of `node`. + */ + type(node: Nodes.Node): string; + /** + * Return type of `node`. + */ + typeof(node: Nodes.Node): string; + /** + * Return type of `node`. + */ + "type-of"(node: Nodes.Node): string; + + /** + * Return component `name` for the given `color`. + */ + component(color: Nodes.RGBA, name: Nodes.String): Nodes.Unit; + component(color: Nodes.HSLA, name: Nodes.String): Nodes.Unit; + + /** + * Return component `name` for the given `color`. + */ + basename(path: Nodes.String): string; + basename(path: Nodes.String, ext: Nodes.String): string; + + /** + * Return the dirname of `path`. + */ + dirname(path: Nodes.String): string; + + /** + * Return the extension of `path`. + */ + extname(path: Nodes.String): string; + + /** + * Joins given paths + */ + pathjoin(...paths: Nodes.String[]): string; + + /** + * Return the red component of the given `color`, + * or set the red component to the optional second `value` argument. + */ + red(color: Nodes.RGBA): Nodes.Unit; + red(color: Nodes.HSLA): Nodes.Unit; + red(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + red(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the green component of the given `color`, + * or set the green component to the optional second `value` argument. + */ + green(color: Nodes.RGBA): Nodes.Unit; + green(color: Nodes.HSLA): Nodes.Unit; + green(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + green(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the blue component of the given `color`, + * or set the blue component to the optional second `value` argument. + */ + blue(color: Nodes.RGBA): Nodes.Unit; + blue(color: Nodes.HSLA): Nodes.Unit; + blue(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + blue(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the alpha component of the given `color`, + * or set the alpha component to the optional second `value` argument. + */ + alpha(color: Nodes.RGBA): Nodes.Unit; + alpha(color: Nodes.HSLA): Nodes.Unit; + alpha(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + alpha(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the hue component of the given `color`, + * or set the hue component to the optional second `value` argument. + */ + hue(color: Nodes.RGBA): Nodes.Unit; + hue(color: Nodes.HSLA): Nodes.Unit; + hue(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + hue(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the saturation component of the given `color`, + * or set the saturation component to the optional second `value` argument. + */ + saturation(color: Nodes.RGBA): Nodes.Unit; + saturation(color: Nodes.HSLA): Nodes.Unit; + saturation(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + saturation(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the lightness component of the given `color`, + * or set the lightness component to the optional second `value` argument. + */ + lightness(color: Nodes.RGBA): Nodes.Unit; + lightness(color: Nodes.HSLA): Nodes.Unit; + lightness(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + lightness(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return a `RGBA` from the r,g,b,a channels. + */ + rgba(rgba: Nodes.RGBA): Nodes.RGBA; + rgba(hsla: Nodes.HSLA): Nodes.RGBA; + rgba(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit, alpha: Nodes.Unit): Nodes.RGBA; + + /** + * Return a `RGBA` from the r,g,b channels. + */ + rgb(rgba: Nodes.RGBA): Nodes.RGBA; + rgb(hsla: Nodes.HSLA): Nodes.RGBA; + rgb(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit, alpha: Nodes.Unit): Nodes.RGBA; + + /** + * Blend the `top` color over the `bottom` + */ + blend(top: Nodes.RGBA): Nodes.RGBA; + blend(top: Nodes.RGBA, bottom: Nodes.RGBA): Nodes.RGBA; + blend(top: Nodes.RGBA, bottom: Nodes.HSLA): Nodes.RGBA; + blend(top: Nodes.HSLA): Nodes.RGBA; + blend(top: Nodes.HSLA, bottom: Nodes.RGBA): Nodes.RGBA; + blend(top: Nodes.HSLA, bottom: Nodes.HSLA): Nodes.RGBA; + + /** + * Returns the relative luminance of the given `color`, + * see http://www.w3.org/TR/WCAG20/#relativeluminancedef + */ + luminosity(rgba: Nodes.RGBA): Nodes.Unit; + luminosity(rgba: Nodes.HSLA): Nodes.Unit; + + /** + * Returns the contrast ratio object between `top` and `bottom` colors, + * based on http://leaverou.github.io/contrast-ratio/ + * and https://github.com/LeaVerou/contrast-ratio/blob/gh-pages/color.js#L108 + */ + contrast(top: Nodes.RGBA): Nodes.Object; + contrast(top: Nodes.RGBA, bottom: Nodes.RGBA): Nodes.Object; + contrast(top: Nodes.RGBA, bottom: Nodes.HSLA): Nodes.Object; + contrast(top: Nodes.HSLA): Nodes.Object; + contrast(top: Nodes.HSLA, bottom: Nodes.RGBA): Nodes.Object; + contrast(top: Nodes.HSLA, bottom: Nodes.HSLA): Nodes.Object; + + /** + * Returns the transparent version of the given `top` color, + * as if it was blend over the given `bottom` color. + */ + transparentify(top: Nodes.RGBA): Nodes.Object; + transparentify(top: Nodes.RGBA, bottom: Nodes.RGBA, alpha?: Nodes.Unit): Nodes.Object; + transparentify(top: Nodes.RGBA, bottom: Nodes.HSLA, alpha?: Nodes.Unit): Nodes.Object; + transparentify(top: Nodes.HSLA): Nodes.Object; + transparentify(top: Nodes.HSLA, bottom: Nodes.RGBA, alpha?: Nodes.Unit): Nodes.Object; + transparentify(top: Nodes.HSLA, bottom: Nodes.HSLA, alpha?: Nodes.Unit): Nodes.Object; + + /** + * Convert a .json file into stylus variables or object. + * Nested variable object keys are joined with a dash (-) + * + * Given this sample media-queries.json file: + * { + * "small": "screen and (max-width:400px)", + * "tablet": { + * "landscape": "screen and (min-width:600px) and (orientation:landscape)", + * "portrait": "screen and (min-width:600px) and (orientation:portrait)" + * } + * } + */ + json(path: Nodes.String, local: Nodes.Boolean, namePrefix: Nodes.String): any; + + /** + * Use the given `plugin`. + */ + use(plugin: Nodes.String): void; + use(plugin: Nodes.String, options: any): void; + + /** + * Unquote the given `string`. + */ + unquote(str: Nodes.String): Nodes.Literal; + + /** + * Like `unquote` but tries to convert the given `str` to a Stylus node. + */ + convert(str: Nodes.String): Nodes.Node; + + /** + * Assign `type` to the given `unit` or return `unit`'s type. + */ + unit(unit: Nodes.Unit, type: Nodes.String): Nodes.Unit; + + /** + * Lookup variable `name` or return Null. + */ + lookup(name: Nodes.String): Nodes.Node; + + /** + * Set a variable `name` on current scope. + */ + define(name: Nodes.String, expr: Nodes.Expression): Nodes.Node; + + /** + * Perform `op` on the `left` and `right` operands. + */ + operate(op: Nodes.String, left: Nodes.Node, right: Nodes.Node): Nodes.Node; + + /** + * Test if `val` matches the given `pattern`. + */ + match(pattern: Nodes.String, val: Nodes.String): Nodes.Boolean; + match(pattern: Nodes.String, val: Nodes.Ident): Nodes.Boolean; + + /** + * Returns substring of the given `val`. + */ + substr(val: Nodes.String, start: Nodes.Number, length: Nodes.Number): Nodes.String; + substr(val: Nodes.Ident, start: Nodes.Number, length: Nodes.Number): Nodes.Ident; + + /** + * Returns string with all matches of `pattern` replaced by `replacement` in given `val` + */ + replace(pattern: Nodes.String, replacement: Nodes.String, val: Nodes.String): Nodes.String; + replace(pattern: Nodes.String, replacement: Nodes.String, val: Nodes.Ident): Nodes.Ident; + + /** + * Splits the given `val` by `delim` + */ + split(pattern: Nodes.String, val: Nodes.String): Nodes.Expression; + split(pattern: Nodes.String, val: Nodes.Ident): Nodes.Expression; + + /** + * Return length of the given `expr`. + */ + length(expr: Nodes.Expression): Nodes.Unit; + + /** + * Inspect the given `expr`. + */ + length(...expr: Nodes.Expression[]): Nodes.Null; + + /** + * Throw an error with the given `msg`. + */ + error(msg: Nodes.String): void; + + /** + * Warn with the given `msg` prefixed by "Warning: ". + */ + warn(msg: Nodes.String): Nodes.Null; + + /** + * Output stack trace. + */ + trace(): Nodes.Null; + + /** + * Push the given args to `expr`. + */ + push(expr: Nodes.Expression, ...nodes: Nodes.Node[]): Nodes.Unit; + + /** + * Pop a value from `expr`. + */ + pop(expr: Nodes.Expression): Nodes.Node; + + /** + * Unshift the given args to `expr`. + */ + unshift(expr: Nodes.Expression, ...nodes: Nodes.Node[]): Nodes.Unit; + + /** + * Unshift the given args to `expr`.. + */ + prepend(expr: Nodes.Expression, ...nodes: Nodes.Node[]): Nodes.Unit; + + /** + * Shift a value from `expr`. + */ + shift(expr: Nodes.Expression): Nodes.Node; + + /** + * Return a `Literal` with the given `fmt`, and variable number of arguments. + */ + s(fmt: Nodes.String, ...nodes: Nodes.Node[]): Nodes.Literal; + + /** + * Return a `Literal` `num` converted to the provided `base`, padded to `width` + * with zeroes (default width is 2) + */ + "base-convert"(num: Nodes.Number, base: Nodes.Number, width: Nodes.Number): Nodes.Literal; + + /** + * Return the opposites of the given `positions`. + */ + "opposite-position"(positions: Nodes.Expression): Nodes.Expression; + + /** + * Return the width and height of the given `img` path. + */ + "image-size"(img: Nodes.String, ignoreErr: Nodes.Boolean): Nodes.Expression; + + /** + * Return the tangent of the given `angle`. + */ + tan(angle: Nodes.Unit): Nodes.Unit; + + /** + * Return the tangent of the given `angle`. + */ + math(n: Nodes.Unit, fn: Nodes.String): Nodes.Unit; + + /** + * Return the opposites of the given `positions`. + */ + "-math-prop"(prop: Nodes.String): Nodes.Unit; + + /** + * Adjust HSL `color` `prop` by `amount`. + */ + adjust(rgba: Nodes.RGBA, prop: Nodes.String, amount: Nodes.Unit): Nodes.RGBA; + adjust(hsla: Nodes.HSLA, prop: Nodes.String, amount: Nodes.Unit): Nodes.RGBA; + + /** + * Return a clone of the given `expr`. + */ + clone(expr: Nodes.Expression): Nodes.Expression; + + /** + * Add property `name` with the given `expr` to the mixin-able block. + */ + "add-property"(name: Nodes.String, expr: Nodes.Expression): Nodes.Property; + + /** + * Merge the object `dest` with the given args. + */ + merge(dest: Nodes.Object, ...objs: Nodes.Object[]): Nodes.Object; + + /** + * Merge the object `dest` with the given args. + */ + extend(dest: Nodes.Object, ...objs: Nodes.Object[]): Nodes.Object; + + /** + * Return the current selector or compile `sel` selector. + */ + selector(): string; + selector(sel: Nodes.String): string; + + /** + * Prefix css classes in a block + */ + "-prefix-classes"(prefix: Nodes.String, block: Nodes.Block): Nodes.Block; + + /** + * Returns the @media string for the current block + */ + "current-media"(): Nodes.String; + + /** + * Return the separator of the given `list`. + */ + "list-separator"(list: Nodes.Expression): Nodes.String; + } + + export interface Utils { + /** + * Check if `path` looks absolute. + */ + absolute(path: string): boolean; + + /** + * Attempt to lookup `path` within `paths` from tail to head. + * Optionally a path to `ignore` may be passed. + */ + lookup(path: string, paths: string, ignore: string, resolveURL: boolean): string; + + /** + * Attempt to lookup `path` within `paths` from tail to head. + * Optionally a path to `ignore` may be passed. + */ + lookupIndex(path: string, paths: string, filename: string): string[]; + + /** + * Like `utils.lookup` but uses `glob` to find files. + */ + find(path: string, paths: string, ignore: string): string[]; + + /** + * Format the given `err` with the given `options`. + */ + formatException(err: Error, options: ExceptionOptions): Error; + + /** + * Assert that `node` is of the given `type`, or throw. + */ + assertType(node: Nodes.Node, type: string, param: string): void; + + /** + * Assert that `node` is a `String` or `Ident`. + */ + assertString(node: Nodes.Node, param: string): void; + + /** + * Assert that `node` is a `RGBA` or `HSLA`. + */ + assertColor(node: Nodes.Node, param: string): void; + + /** + * Assert that param `name` is given, aka the `node` is passed. + */ + assertPresent(node: Nodes.Node, name: string): void; + + /** + * Unwrap `expr`. + * + * Takes an expressions with length of 1 + * such as `((1 2 3))` and unwraps it to `(1 2 3)`. + */ + unwrap(expr: Nodes.Expression): Nodes.Node; + + /** + * Coerce JavaScript values to their Stylus equivalents. + */ + coerce(val: any): Nodes.Node; + coerce(val: any, raw: boolean): Nodes.Node; + + /** + * Coerce a javascript `Array` to a Stylus `Expression`. + */ + coerceArray(val: any): Nodes.Expression; + coerceArray(val: any, raw: boolean): Nodes.Expression; + + /** + * Coerce a javascript object to a Stylus `Expression` or `Object`. + * + * For example `{ foo: 'bar', bar: 'baz' }` would become + * the expression `(foo 'bar') (bar 'baz')`. If `raw` is true + * given `obj` would become a Stylus hash object. + */ + coerceObject(obj: any): Nodes.Expression; + coerceObject(obj: any, raw: boolean): Nodes.Expression; + + /** + * Return param names for `fn`. + */ + params(fn: Function): string[]; + + /** + * Merge object `b` with `a`. + */ + merge(a: any, b: any): any; + + /** + * Returns an array with unique values. + */ + uniq(arr: any[]): any[]; + + /** + * Compile selector strings in `arr` from the bottom-up + * to produce the selector combinations. For example + * the following Stylus: + */ + compileSelectors(arr: string[], leaveHidden: boolean): string[]; + } + + export interface UrlFunction { + (options: UrlOptions): LiteralFunction; + + mimes: { + ".gif": string; + ".png": string; + ".jpg": string; + ".jpeg": string; + ".svg": string; + ".ttf": string; + ".eot": string; + ".woff": string; + }; + } + + export interface Middleware { + (req: any, res: any, next: Function): void; + } + + //#endregion + + //#region Internal Classes + + export class Visitor { + } + + export class Parser { + } + + export class Evaluator { + } + + export class Compiler { + } + + export class Renderer { //extends events.EventEmitter { + options: RenderOptions; + str: string; + events: any; + + constructor(str: string); + constructor(str: string, options: RenderOptions); + + /** + * Parse and evaluate AST, then callback `fn(err, css, js)`. + */ + render(callback: RenderCallback): void; + + /** + * Get dependencies of the compiled file. + */ + deps(filename: string): string[]; + + /** + * Set option `key` to `val`. + */ + set(key: string, val: any): Renderer; + + /** + * Get option `key`. + */ + get(key: string): any; + + /** + * Include the given `path` to the lookup paths array. + */ + include(path: string): Renderer; + + /** + * Use the given `fn`. + * + * This allows for plugins to alter the renderer in + * any way they wish, exposing paths etc. + */ + use(fn: (renderer: Renderer) => any): Renderer; + + /** + * Define function or global var with the given `name`. Optionally + * the function may accept full expressions, by setting `raw` + * to `true`. + */ + define(name: string, fn: Function): Renderer; + define(name: string, node: Nodes.Node): Renderer; + define(name: string, val: any): Renderer; + define(name: string, fn: Function, raw: boolean): Renderer; + define(name: string, node: Nodes.Node, raw: boolean): Renderer; + define(name: string, val: any, raw: boolean): Renderer; + + /** + * Import the given `file`. + */ + import(file: string): Renderer; + } + + //#endregion + + //#region Nodes Classes + + export module Nodes { + + export class Node { + lineno: number; + column: number; + filename: string; + + first: Node; + hash: string; + nodeName: string; + + constructor(); + + /** + * Return a clone of this node. + */ + clone(): Node; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { lineno: number; column: number; filename: string }; + + /** + * Nodes by default evaluate to themselves. + */ + eval(): Node; + + /** + * Return true. + */ + toBoolean(): Boolean; + + /** + * Return the expression, or wrap this node in an expression. + */ + toExpression(): Expression; + + /** + * Return false if `op` is generally not coerced. + */ + shouldCoerce(op: string): boolean; + + /** + * Operate on `right` with the given `op`. + */ + operate(op: string, right: Node): Node; + + /** + * Default coercion throws. + */ + coerce(other: Node): Node; + } + + export class Root extends Node { + nodes: Node[]; + + /** + * Push a `node` to this block. + */ + push(node: Node): void; + + /** + * Unshift a `node` to this block. + */ + unshift(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class String extends Node { + val: string; + string: string; + prefixed: boolean; + quote: string; + + constructor(val: string); + constructor(val: string, quote: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { val: string; quote: string; lineno: number; column: number; filename: string }; + } + + export class Number extends Node { + + } + + export class Boolean extends Node { + val: boolean; + isTrue: boolean; + isFalse: boolean; + + constructor(); + constructor(val: boolean); + + /** + * Negate the value. + */ + negate(): Boolean; + + /** + * Return 'Boolean'. + */ + inspect(): Boolean; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: boolean; lineno: number; column: number; filename: string }; + } + + export class Object extends Node { + vals: Dictionary; + length: number; + + constructor(); + + /** + * Set `key` to `val`. + */ + set(key: string, value: Node): Object; + + /** + * Get `key`. + */ + get(key: string): Node; + + /** + * Has `key`? + */ + has(key: string): boolean; + + /** + * Convert object to string with properties. + */ + toBlock(): string; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; vals: Dictionary; lineno: number; column: number; filename: string }; + } + + export class Null extends Node { + isNull: boolean; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; lineno: number; column: number; filename: string }; + } + + export class Ident extends Node { + name: string; + string: string; + val: Node; + mixin: boolean; + + isEmpty: boolean; + + constructor(name: string, val: Node); + constructor(name: string, val: Node, mixin: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; val: Node; mixin: boolean; lineno: number; column: number; filename: string }; + } + + export class Literal extends Node { + val: string; + string: string; + prefixed: boolean; + + constructor(str: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; string: string; val: string; prefixed: boolean; lineno: number; column: number; filename: string }; + } + + export class Unit extends Node { + val: number; + type: string; + + constructor(val: number, type: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: number; type: string; lineno: number; column: number; filename: string }; + } + + export class RGBA extends Node { + r: number; + g: number; + b: number; + a: number; + rgba: RGBA; + hsla: HSLA; + + constructor(r: number, g: number, b: number, a: number); + + /** + * Return an `RGBA` without clamping values. + */ + static withoutClamping(r: number, g: number, b: number, a: number): RGBA; + + /** + * Return a `RGBA` from the given `hsla`. + */ + static fromHSLA(hsla: HSLA): RGBA; + + /** + * Add r,g,b,a to the current component values + */ + add(r: number, g: number, b: number, a: number): RGBA; + + /** + * Subtract r,g,b,a from the current component values + */ + substract(r: number, g: number, b: number, a: number): RGBA; + + /** + * Multiply rgb components by `n`. + */ + multiply(n: number): RGBA; + + /** + * Divide rgb components by `n`. + */ + divide(n: number): RGBA; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; r: number; g: number; b: number; a: number; lineno: number; column: number; filename: string }; + } + + export class HSLA extends Node { + h: number; + s: number; + l: number; + a: number; + hsla: HSLA; + rgba: RGBA; + + constructor(h: number, s: number, l: number, a: number); + + /** + * Return a `HSLA` from the given `hsla`. + */ + static fromRGBA(rgba: RGBA): HSLA; + + /** + * Add h,s,l to the current component values + */ + add(h: number, s: number, l: number): HSLA; + + /** + * Subtract h,s,l from the current component values + */ + substract(h: number, s: number, l: number): HSLA; + + /** + * Adjust lightness by `percent`. + */ + adjustLightness(percent: number): HSLA; + + /** + * djust hue by `deg`. + */ + adjustHue(deg: number): HSLA; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; h: number; s: number; l: number; a: number; lineno: number; column: number; filename: string }; + } + + export class Block extends Node { + nodes: Node[]; + parent: Block; + node: Node; + scope: boolean; + + hasProperties: boolean; + hasMedia: boolean; + isEmpty: boolean; + + constructor(parent: Block); + constructor(parent: Block, node: Node); + + /** + * Push a `node` to this block. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; scope: boolean; lineno: number; column: number; filename: string }; + } + + export class Group extends Node { + nodes: Node[]; + block: Block; + + hasOnlyPlaceholders: boolean; + + constructor(); + + /** + * Push the given `selector` node. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; block: Block; lineno: number; column: number; filename: string }; + } + + export class Expression extends Node { + nodes: Node[]; + isList: boolean; + + isEmpty: boolean; + first: Node; + + constructor(isList: boolean); + + /** + * Push the given node. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; isList: boolean; lineno: number; column: number; filename: string }; + } + + export class Property extends Node { + segments: Node[]; + expr: Expression; + + constructor(segs: Node[], expr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; name: string; expr?: Expression; literal?: Literal; lineno: number; column: number; filename: string }; + } + + export class Each extends Node { + val: string; + key: string; + expr: Expression; + block: Block; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; key: string; expr: Expression; block: Block; lineno: number; column: number; filename: string }; + } + + export class If extends Node { + cond: Expression; + elses: Expression[]; + block: Block; + negate: boolean; + + constructor(cond: Expression, negate: boolean); + constructor(cond: Expression, block: Block); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; cond: Expression; elses: Expression[]; block: Block; negate: boolean; lineno: number; column: number; filename: string }; + } + + export class Call extends Node { + name: string; + args: Expression; + + constructor(name: string, args: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; args: Expression; lineno: number; column: number; filename: string }; + } + + export class UnaryOp extends Node { + op: string; + expr: Expression; + + constructor(op: string, expr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; expr: Expression; lineno: number; column: number; filename: string }; + } + + export class BinOp extends Node { + op: string; + left: Expression; + right: Expression; + + constructor(op: string, left: Expression, right: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; left: Expression; right: Expression; lineno: number; column: number; filename: string }; + } + + export class Ternary extends Node { + op: string; + trueExpr: Expression; + falseExpr: Expression; + + constructor(op: string, trueExpr: Expression, falseExpr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; trueExpr: Expression; falseExpr: Expression; lineno: number; column: number; filename: string }; + } + + export class Return extends Node { + expr: Expression; + + constructor(expr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; expr: Expression; lineno: number; column: number; filename: string }; + } + + export class Media extends Node { + val: string; + + constructor(val: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; + } + + export class QueryList extends Node { + nodes: Node[]; + + constructor(); + + /** + * Push the given `node`. + */ + push(node: Node): void; + + /** + * Merges this query list with the `other`. + */ + merge(other: MediaQueryList): MediaQueryList; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class Query extends Node { + nodes: QueryExpr[]; + type: string; + predicate: string; + + resolvedType: string; + resolvedPredicate: string; + + constructor(); + + /** + * Push the given `expr`. + */ + push(expr: QueryExpr): void; + + /** + * Merges this query with the `other`. + */ + merge(other: Query): Query; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: QueryExpr[]; predicate: string; type: string; lineno: number; column: number; filename: string }; + } + + export class QueryExpr extends Node { + segments: Node[]; + expr: Expression; + + constructor(segs: Node[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; lineno: number; column: number; filename: string }; + } + + export class Params extends Node { + nodes: Node[]; + + length: number; + + /** + * Push the given `node`. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class Comment extends Node { + str: string; + suppress: boolean; + inline: boolean; + + constructor(str: string, suppress: boolean, inline: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; str: string; suppress: boolean; inline: boolean; lineno: number; column: number; filename: string }; + } + + export class Keyframes extends Node { + segments: Node[]; + prefix: string; + + constructor(segs: Node[]); + constructor(segs: Node[], prefix: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; prefix: string; block: Block; lineno: number; column: number; filename: string }; + } + + export class Member extends Node { + left: Node; + right: Node; + + constructor(left: Node, right: Node); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; left: Node; right: Node; val?: string; lineno: number; column: number; filename: string }; + } + + export class Charset extends Node { + val: string; + + constructor(val: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; + } + + export class Namespace extends Node { + val: string; + prefix: string; + + constructor(val: string, prefix: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; prefix: string; lineno: number; column: number; filename: string }; + } + + export class Import extends Node { + path: Expression; + once: boolean; + + constructor(path: Expression); + constructor(path: Expression, once: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; path: Expression; lineno: number; column: number; filename: string }; + } + + export class Extend extends Node { + selectors: Selector[]; + + constructor(selectors: Selector[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; selectors: Selector[]; lineno: number; column: number; filename: string }; + } + + export class Function extends Node { + name: string; + params: Params; + body: Block; + + constructor(name: string, params: Params, body: Block); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; params: Params; body: Block; lineno: number; column: number; filename: string }; + } + + export class Selector extends Node { + inherits: boolean; + segments: Node[]; + + constructor(segs: Node[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; inherits: boolean; val: string; lineno: number; column: number; filename: string }; + } + + export class Arguments extends Expression { + map: Dictionary; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; map: Dictionary; isList: boolean; preserve: boolean; nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class Atblock extends Node { + block: Block; + nodes: Node[]; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; block: Block; lineno: number; column: number; filename: string }; + } + + export class Atrule extends Node { + type: string; + + hasOnlyProperties: boolean; + + constructor(type: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; type: string; segments: Node[]; block?: Block; lineno: number; column: number; filename: string }; + } + } + + //#endregion + + //#region Internal Interfaces + + export interface Dictionary { + [key: string]: T; + } + + export interface RenderOptions { + globals?: Dictionary; + functions?: Dictionary; + imports?: string[]; + paths?: string[]; + filename?: string; + Evaluator?: typeof Evaluator; + } + + export interface RenderCallback { + (err: Error, css: string, js: string): void; + } + + export interface UrlOptions { + limit?: string; + path: string; + } + + export interface LiteralFunction { + (url: string): Nodes.Literal; + raw: boolean; + } + + export interface ExceptionOptions { + filename: string; + context: number; + lineno: number; + column: number; + input: string; + } + + //#endregion } -//#region Internal Modules - -interface StylusNodeStatic { - Node: typeof StylusNode; - Root: typeof StylusNodeRoot; - Null: typeof StylusNodeNull; - Each: typeof StylusNodeEach; - If: typeof StylusNodeIf; - Call: typeof StylusNodeCall; - UnaryOp: typeof StylusNodeUnaryOp; - BinOp: typeof StylusNodeBinOp; - Ternary: typeof StylusNodeTernary; - Block: typeof StylusNodeBlock; - Unit: typeof StylusNodeUnit; - String: typeof StylusNodeString; - HSLA: typeof StylusNodeHSLA; - RGBA: typeof StylusNodeRGBA; - Ident: typeof StylusNodeIdent; - Group: typeof StylusNodeGroup; - Literal: typeof StylusNodeLiteral; - Boolean: typeof StylusNodeBoolean; - Return: typeof StylusNodeReturn; - Media: typeof StylusNodeMedia; - QueryList: typeof StylusNodeQueryList; - Query: typeof StylusNodeQuery; - QueryExpr: typeof StylusNodeQueryExpr; - Params: typeof StylusNodeParams; - Comment: typeof StylusNodeComment; - Keyframes: typeof StylusNodeKeyframes; - Member: typeof StylusNodeMember; - Charset: typeof StylusNodeCharset; - Namespace: typeof StylusNodeNamespace; - Import: typeof StylusNodeImport; - Extend: typeof StylusNodeExtend; - Object: typeof StylusNodeObject; - Function: typeof StylusNodeFunction; - Property: typeof StylusNodeProperty; - Selector: typeof StylusNodeSelector; - Expression: typeof StylusNodeExpression; - Arguments: typeof StylusNodeArguments; - Atblock: typeof StylusNodeAtblock; - Atrule: typeof StylusNodeAtrule; - - true: StylusNodeBoolean; - false: StylusNodeBoolean; - null: StylusNodeNull; -} - -interface StylusFunctions { - /** - * Convert the given `color` to an `HSLA` node, - * or h,s,l,a component values. - */ - hsla(rgba: StylusNodeRGBA): StylusNodeHSLA; - hsla(hsla: StylusNodeHSLA): StylusNodeHSLA; - hsla(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit, alpha: StylusNodeUnit): StylusNodeHSLA; - - /** - * Convert the given `color` to an `HSLA` node, - * or h,s,l component values. - */ - hsl(rgba: StylusNodeRGBA): StylusNodeHSLA; - hsl(hsla: StylusNodeHSLA): StylusNodeHSLA; - hsl(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit): StylusNodeHSLA; - - /** - * Return type of `node`. - */ - type(node: StylusNode): string; - /** - * Return type of `node`. - */ - typeof(node: StylusNode): string; - /** - * Return type of `node`. - */ - "type-of"(node: StylusNode): string; - - /** - * Return component `name` for the given `color`. - */ - component(color: StylusNodeRGBA, name: StylusNodeString): StylusNodeUnit; - component(color: StylusNodeHSLA, name: StylusNodeString): StylusNodeUnit; - - /** - * Return component `name` for the given `color`. - */ - basename(path: StylusNodeString): string; - basename(path: StylusNodeString, ext: StylusNodeString): string; - - /** - * Return the dirname of `path`. - */ - dirname(path: StylusNodeString): string; - - /** - * Return the extension of `path`. - */ - extname(path: StylusNodeString): string; - - /** - * Joins given paths - */ - pathjoin(...paths: StylusNodeString[]): string; - - /** - * Return the red component of the given `color`, - * or set the red component to the optional second `value` argument. - */ - red(color: StylusNodeRGBA): StylusNodeUnit; - red(color: StylusNodeHSLA): StylusNodeUnit; - red(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - red(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return the green component of the given `color`, - * or set the green component to the optional second `value` argument. - */ - green(color: StylusNodeRGBA): StylusNodeUnit; - green(color: StylusNodeHSLA): StylusNodeUnit; - green(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - green(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return the blue component of the given `color`, - * or set the blue component to the optional second `value` argument. - */ - blue(color: StylusNodeRGBA): StylusNodeUnit; - blue(color: StylusNodeHSLA): StylusNodeUnit; - blue(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - blue(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return the alpha component of the given `color`, - * or set the alpha component to the optional second `value` argument. - */ - alpha(color: StylusNodeRGBA): StylusNodeUnit; - alpha(color: StylusNodeHSLA): StylusNodeUnit; - alpha(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - alpha(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return the hue component of the given `color`, - * or set the hue component to the optional second `value` argument. - */ - hue(color: StylusNodeRGBA): StylusNodeUnit; - hue(color: StylusNodeHSLA): StylusNodeUnit; - hue(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - hue(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return the saturation component of the given `color`, - * or set the saturation component to the optional second `value` argument. - */ - saturation(color: StylusNodeRGBA): StylusNodeUnit; - saturation(color: StylusNodeHSLA): StylusNodeUnit; - saturation(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - saturation(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return the lightness component of the given `color`, - * or set the lightness component to the optional second `value` argument. - */ - lightness(color: StylusNodeRGBA): StylusNodeUnit; - lightness(color: StylusNodeHSLA): StylusNodeUnit; - lightness(color: StylusNodeRGBA, value: StylusNodeUnit): StylusNodeRGBA; - lightness(color: StylusNodeHSLA, value: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return a `RGBA` from the r,g,b,a channels. - */ - rgba(rgba: StylusNodeRGBA): StylusNodeRGBA; - rgba(hsla: StylusNodeHSLA): StylusNodeRGBA; - rgba(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit, alpha: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return a `RGBA` from the r,g,b channels. - */ - rgb(rgba: StylusNodeRGBA): StylusNodeRGBA; - rgb(hsla: StylusNodeHSLA): StylusNodeRGBA; - rgb(hue: StylusNodeUnit, saturation: StylusNodeUnit, lightness: StylusNodeUnit, alpha: StylusNodeUnit): StylusNodeRGBA; - - /** - * Blend the `top` color over the `bottom` - */ - blend(top: StylusNodeRGBA): StylusNodeRGBA; - blend(top: StylusNodeRGBA, bottom: StylusNodeRGBA): StylusNodeRGBA; - blend(top: StylusNodeRGBA, bottom: StylusNodeHSLA): StylusNodeRGBA; - blend(top: StylusNodeHSLA): StylusNodeRGBA; - blend(top: StylusNodeHSLA, bottom: StylusNodeRGBA): StylusNodeRGBA; - blend(top: StylusNodeHSLA, bottom: StylusNodeHSLA): StylusNodeRGBA; - - /** - * Returns the relative luminance of the given `color`, - * see http://www.w3.org/TR/WCAG20/#relativeluminancedef - */ - luminosity(rgba: StylusNodeRGBA): StylusNodeUnit; - luminosity(rgba: StylusNodeHSLA): StylusNodeUnit; - - /** - * Returns the contrast ratio object between `top` and `bottom` colors, - * based on http://leaverou.github.io/contrast-ratio/ - * and https://github.com/LeaVerou/contrast-ratio/blob/gh-pages/color.js#L108 - */ - contrast(top: StylusNodeRGBA): StylusNodeObject; - contrast(top: StylusNodeRGBA, bottom: StylusNodeRGBA): StylusNodeObject; - contrast(top: StylusNodeRGBA, bottom: StylusNodeHSLA): StylusNodeObject; - contrast(top: StylusNodeHSLA): StylusNodeObject; - contrast(top: StylusNodeHSLA, bottom: StylusNodeRGBA): StylusNodeObject; - contrast(top: StylusNodeHSLA, bottom: StylusNodeHSLA): StylusNodeObject; - - /** - * Returns the transparent version of the given `top` color, - * as if it was blend over the given `bottom` color. - */ - transparentify(top: StylusNodeRGBA): StylusNodeObject; - transparentify(top: StylusNodeRGBA, bottom: StylusNodeRGBA, alpha?: StylusNodeUnit): StylusNodeObject; - transparentify(top: StylusNodeRGBA, bottom: StylusNodeHSLA, alpha?: StylusNodeUnit): StylusNodeObject; - transparentify(top: StylusNodeHSLA): StylusNodeObject; - transparentify(top: StylusNodeHSLA, bottom: StylusNodeRGBA, alpha?: StylusNodeUnit): StylusNodeObject; - transparentify(top: StylusNodeHSLA, bottom: StylusNodeHSLA, alpha?: StylusNodeUnit): StylusNodeObject; - - /** - * Convert a .json file into stylus variables or object. - * Nested variable object keys are joined with a dash (-) - * - * Given this sample media-queries.json file: - * { - * "small": "screen and (max-width:400px)", - * "tablet": { - * "landscape": "screen and (min-width:600px) and (orientation:landscape)", - * "portrait": "screen and (min-width:600px) and (orientation:portrait)" - * } - * } - */ - json(path: StylusNodeString, local: StylusNodeBoolean, namePrefix: StylusNodeString): any; - - /** - * Use the given `plugin`. - */ - use(plugin: StylusNodeString): void; - use(plugin: StylusNodeString, options: any): void; - - /** - * Unquote the given `string`. - */ - unquote(str: StylusNodeString): StylusNodeLiteral; - - /** - * Like `unquote` but tries to convert the given `str` to a Stylus node. - */ - convert(str: StylusNodeString): StylusNode; - - /** - * Assign `type` to the given `unit` or return `unit`'s type. - */ - unit(unit: StylusNodeUnit, type: StylusNodeString): StylusNodeUnit; - - /** - * Lookup variable `name` or return Null. - */ - lookup(name: StylusNodeString): StylusNode; - - /** - * Set a variable `name` on current scope. - */ - define(name: StylusNodeString, expr: StylusNodeExpression): StylusNode; - - /** - * Perform `op` on the `left` and `right` operands. - */ - operate(op: StylusNodeString, left: StylusNode, right: StylusNode): StylusNode; - - /** - * Test if `val` matches the given `pattern`. - */ - match(pattern: StylusNodeString, val: StylusNodeString): StylusNodeBoolean; - match(pattern: StylusNodeString, val: StylusNodeIdent): StylusNodeBoolean; - - /** - * Returns substring of the given `val`. - */ - substr(val: StylusNodeString, start: StylusNodeNumber, length: StylusNodeNumber): StylusNodeString; - substr(val: StylusNodeIdent, start: StylusNodeNumber, length: StylusNodeNumber): StylusNodeIdent; - - /** - * Returns string with all matches of `pattern` replaced by `replacement` in given `val` - */ - replace(pattern: StylusNodeString, replacement: StylusNodeString, val: StylusNodeString): StylusNodeString; - replace(pattern: StylusNodeString, replacement: StylusNodeString, val: StylusNodeIdent): StylusNodeIdent; - - /** - * Splits the given `val` by `delim` - */ - split(pattern: StylusNodeString, val: StylusNodeString): StylusNodeExpression; - split(pattern: StylusNodeString, val: StylusNodeIdent): StylusNodeExpression; - - /** - * Return length of the given `expr`. - */ - length(expr: StylusNodeExpression): StylusNodeUnit; - - /** - * Inspect the given `expr`. - */ - length(...expr: StylusNodeExpression[]): StylusNodeNull; - - /** - * Throw an error with the given `msg`. - */ - error(msg: StylusNodeString): void; - - /** - * Warn with the given `msg` prefixed by "Warning: ". - */ - warn(msg: StylusNodeString): StylusNodeNull; - - /** - * Output stack trace. - */ - trace(): StylusNodeNull; - - /** - * Push the given args to `expr`. - */ - push(expr: StylusNodeExpression, ...nodes: StylusNode[]): StylusNodeUnit; - - /** - * Pop a value from `expr`. - */ - pop(expr: StylusNodeExpression): StylusNode; - - /** - * Unshift the given args to `expr`. - */ - unshift(expr: StylusNodeExpression, ...nodes: StylusNode[]): StylusNodeUnit; - - /** - * Unshift the given args to `expr`.. - */ - prepend(expr: StylusNodeExpression, ...nodes: StylusNode[]): StylusNodeUnit; - - /** - * Shift a value from `expr`. - */ - shift(expr: StylusNodeExpression): StylusNode; - - /** - * Return a `Literal` with the given `fmt`, and variable number of arguments. - */ - s(fmt: StylusNodeString, ...nodes: StylusNode[]): StylusNodeLiteral; - - /** - * Return a `Literal` `num` converted to the provided `base`, padded to `width` - * with zeroes (default width is 2) - */ - "base-convert"(num: StylusNodeNumber, base: StylusNodeNumber, width: StylusNodeNumber): StylusNodeLiteral; - - /** - * Return the opposites of the given `positions`. - */ - "opposite-position"(positions: StylusNodeExpression): StylusNodeExpression; - - /** - * Return the width and height of the given `img` path. - */ - "image-size"(img: StylusNodeString, ignoreErr: StylusNodeBoolean): StylusNodeExpression; - - /** - * Return the tangent of the given `angle`. - */ - tan(angle: StylusNodeUnit): StylusNodeUnit; - - /** - * Return the tangent of the given `angle`. - */ - math(n: StylusNodeUnit, fn: StylusNodeString): StylusNodeUnit; - - /** - * Return the opposites of the given `positions`. - */ - "-math-prop"(prop: StylusNodeString): StylusNodeUnit; - - /** - * Adjust HSL `color` `prop` by `amount`. - */ - adjust(rgba: StylusNodeRGBA, prop: StylusNodeString, amount: StylusNodeUnit): StylusNodeRGBA; - adjust(hsla: StylusNodeHSLA, prop: StylusNodeString, amount: StylusNodeUnit): StylusNodeRGBA; - - /** - * Return a clone of the given `expr`. - */ - clone(expr: StylusNodeExpression): StylusNodeExpression; - - /** - * Add property `name` with the given `expr` to the mixin-able block. - */ - "add-property"(name: StylusNodeString, expr: StylusNodeExpression): StylusNodeProperty; - - /** - * Merge the object `dest` with the given args. - */ - merge(dest: StylusNodeObject, ...objs: StylusNodeObject[]): StylusNodeObject; - - /** - * Merge the object `dest` with the given args. - */ - extend(dest: StylusNodeObject, ...objs: StylusNodeObject[]): StylusNodeObject; - - /** - * Return the current selector or compile `sel` selector. - */ - selector(): string; - selector(sel: StylusNodeString): string; - - /** - * Prefix css classes in a block - */ - "-prefix-classes"(prefix: StylusNodeString, block: StylusNodeBlock): StylusNodeBlock; - - /** - * Returns the @media string for the current block - */ - "current-media"(): StylusNodeString; - - /** - * Return the separator of the given `list`. - */ - "list-separator"(list: StylusNodeExpression): StylusNodeString; -} - -interface StylusUtils { - /** - * Check if `path` looks absolute. - */ - absolute(path: string): boolean; - - /** - * Attempt to lookup `path` within `paths` from tail to head. - * Optionally a path to `ignore` may be passed. - */ - lookup(path: string, paths: string, ignore: string, resolveURL: boolean): string; - - /** - * Attempt to lookup `path` within `paths` from tail to head. - * Optionally a path to `ignore` may be passed. - */ - lookupIndex(path: string, paths: string, filename: string): string[]; - - /** - * Like `utils.lookup` but uses `glob` to find files. - */ - find(path: string, paths: string, ignore: string): string[]; - - /** - * Format the given `err` with the given `options`. - */ - formatException(err: Error, options: StylusExceptionOptions): Error; - - /** - * Assert that `node` is of the given `type`, or throw. - */ - assertType(node: StylusNode, type: string, param: string): void; - - /** - * Assert that `node` is a `String` or `Ident`. - */ - assertString(node: StylusNode, param: string): void; - - /** - * Assert that `node` is a `RGBA` or `HSLA`. - */ - assertColor(node: StylusNode, param: string): void; - - /** - * Assert that param `name` is given, aka the `node` is passed. - */ - assertPresent(node: StylusNode, name: string): void; - - /** - * Unwrap `expr`. - * - * Takes an expressions with length of 1 - * such as `((1 2 3))` and unwraps it to `(1 2 3)`. - */ - unwrap(expr: StylusNodeExpression): StylusNode; - - /** - * Coerce JavaScript values to their Stylus equivalents. - */ - coerce(val: any): StylusNode; - coerce(val: any, raw: boolean): StylusNode; - - /** - * Coerce a javascript `Array` to a Stylus `Expression`. - */ - coerceArray(val: any): StylusNodeExpression; - coerceArray(val: any, raw: boolean): StylusNodeExpression; - - /** - * Coerce a javascript object to a Stylus `Expression` or `Object`. - * - * For example `{ foo: 'bar', bar: 'baz' }` would become - * the expression `(foo 'bar') (bar 'baz')`. If `raw` is true - * given `obj` would become a Stylus hash object. - */ - coerceObject(obj: any): StylusNodeExpression; - coerceObject(obj: any, raw: boolean): StylusNodeExpression; - - /** - * Return param names for `fn`. - */ - params(fn: Function): string[]; - - /** - * Merge object `b` with `a`. - */ - merge(a: any, b: any): any; - - /** - * Returns an array with unique values. - */ - uniq(arr: any[]): any[]; - - /** - * Compile selector strings in `arr` from the bottom-up - * to produce the selector combinations. For example - * the following Stylus: - */ - compileSelectors(arr: string[], leaveHidden: boolean): string[]; -} - -interface StylusUrl { - (options: StylusUrlOptions): StylusLiteralFunction; - - mimes: { - ".gif": string; - ".png": string; - ".jpg": string; - ".jpeg": string; - ".svg": string; - ".ttf": string; - ".eot": string; - ".woff": string; - }; -} - -interface StylusMiddleware { - (req: any, res: any, next: Function): void; -} - -//#endregion - -//#region Internal Classes - -declare class StylusVisitor { -} - -declare class StylusParser { -} - -declare class StylusEvaluator { -} - -declare class StylusCompiler { -} - -declare class StylusRenderer { //extends events.EventEmitter { - options: StylusRenderOptions; - str: string; - events: any; - - constructor(str: string); - constructor(str: string, options: StylusRenderOptions); - - /** - * Parse and evaluate AST, then callback `fn(err, css, js)`. - */ - render(callback: StylusRenderCallback): void; - - /** - * Get dependencies of the compiled file. - */ - deps(filename: string): string[]; - - /** - * Set option `key` to `val`. - */ - set(key: string, val: any): StylusRenderer; - - /** - * Get option `key`. - */ - get(key: string): any; - - /** - * Include the given `path` to the lookup paths array. - */ - include(path: string): StylusRenderer; - - /** - * Use the given `fn`. - * - * This allows for plugins to alter the renderer in - * any way they wish, exposing paths etc. - */ - use(fn: Function): StylusRenderer; - - /** - * Define function or global var with the given `name`. Optionally - * the function may accept full expressions, by setting `raw` - * to `true`. - */ - define(name: string, fn: Function): StylusRenderer; - define(name: string, node: StylusNode): StylusRenderer; - define(name: string, fn: Function, raw: boolean): StylusRenderer; - define(name: string, node: StylusNode, raw: boolean): StylusRenderer; - - /** - * Import the given `file`. - */ - import(file: string): StylusRenderer; -} - -//#endregion - -//#region Nodes Classes - -declare class StylusNode { - lineno: number; - column: number; - filename: string; - - first: StylusNode; - hash: string; - nodeName: string; - - constructor(); - - /** - * Return a clone of this node. - */ - clone(): StylusNode; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { lineno: number; column: number; filename: string }; - - /** - * Nodes by default evaluate to themselves. - */ - eval(): StylusNode; - - /** - * Return true. - */ - toBoolean(): StylusNodeBoolean; - - /** - * Return the expression, or wrap this node in an expression. - */ - toExpression(): StylusNodeExpression; - - /** - * Return false if `op` is generally not coerced. - */ - shouldCoerce(op: string): boolean; - - /** - * Operate on `right` with the given `op`. - */ - operate(op: string, right: StylusNode): StylusNode; - - /** - * Default coercion throws. - */ - coerce(other: StylusNode): StylusNode; -} - -declare class StylusNodeRoot extends StylusNode { - nodes: StylusNode[]; - - /** - * Push a `node` to this block. - */ - push(node: StylusNode): void; - - /** - * Unshift a `node` to this block. - */ - unshift(node: StylusNode): void; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { nodes: StylusNode[]; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeString extends StylusNode { - val: string; - string: string; - prefixed: boolean; - quote: string; - - constructor(val: string, quote: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { val: string; quote: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeNumber extends StylusNode { - -} - -declare class StylusNodeBoolean extends StylusNode { - val: boolean; - isTrue: boolean; - isFalse: boolean; - - constructor(); - constructor(val: boolean); - - /** - * Negate the value. - */ - negate(): StylusNodeBoolean; - - /** - * Return 'Boolean'. - */ - inspect(): StylusNodeBoolean; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; val: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeObject extends StylusNode { - vals: StylusDictionary; - length: number; - - constructor(); - - /** - * Set `key` to `val`. - */ - set(key: string, value: StylusNode): StylusNodeObject; - - /** - * Get `key`. - */ - get(key: string): StylusNode; - - /** - * Has `key`? - */ - has(key: string): boolean; - - /** - * Convert object to string with properties. - */ - toBlock(): string; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; vals: StylusDictionary; lineno: number; column: number; filename: string };} - -declare class StylusNodeNull extends StylusNode { - isNull: boolean; - - constructor(); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeIdent extends StylusNode { - name: string; - string: string; - val: StylusNode; - mixin: boolean; - - isEmpty: boolean; - - constructor(name: string, val: StylusNode); - constructor(name: string, val: StylusNode, mixin: boolean); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; name: string; val: StylusNode; mixin: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeLiteral extends StylusNode { - val: string; - string: string; - prefixed: boolean; - - constructor(str: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; string: string; val: string; prefixed: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeUnit extends StylusNode { - val: number; - type: string; - - constructor(val: number, type: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; val: number; type: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeRGBA extends StylusNode { - r: number; - g: number; - b: number; - a: number; - rgba: StylusNodeRGBA; - hsla: StylusNodeHSLA; - - constructor(r: number, g: number, b: number, a: number); - - /** - * Return an `RGBA` without clamping values. - */ - static withoutClamping(r: number, g: number, b: number, a: number): StylusNodeRGBA; - - /** - * Return a `RGBA` from the given `hsla`. - */ - static fromHSLA(hsla: StylusNodeHSLA): StylusNodeRGBA; - - /** - * Add r,g,b,a to the current component values - */ - add(r: number, g: number, b: number, a: number): StylusNodeRGBA; - - /** - * Subtract r,g,b,a from the current component values - */ - substract(r: number, g: number, b: number, a: number): StylusNodeRGBA; - - /** - * Multiply rgb components by `n`. - */ - multiply(n: number): StylusNodeRGBA; - - /** - * Divide rgb components by `n`. - */ - divide(n: number): StylusNodeRGBA; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; r: number; g: number; b: number; a: number; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeHSLA extends StylusNode { - h: number; - s: number; - l: number; - a: number; - hsla: StylusNodeHSLA; - rgba: StylusNodeRGBA; - - constructor(h: number, s: number, l: number, a: number); - - /** - * Return a `HSLA` from the given `hsla`. - */ - static fromRGBA(rgba: StylusNodeRGBA): StylusNodeHSLA; - - /** - * Add h,s,l to the current component values - */ - add(h: number, s: number, l: number): StylusNodeHSLA; - - /** - * Subtract h,s,l from the current component values - */ - substract(h: number, s: number, l: number): StylusNodeHSLA; - - /** - * Adjust lightness by `percent`. - */ - adjustLightness(percent: number): StylusNodeHSLA; - - /** - * djust hue by `deg`. - */ - adjustHue(deg: number): StylusNodeHSLA; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; h: number; s: number; l: number; a: number; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeBlock extends StylusNode { - nodes: StylusNode[]; - parent: StylusNodeBlock; - node: StylusNode; - scope: boolean; - - hasProperties: boolean; - hasMedia: boolean; - isEmpty: boolean; - - constructor(parent: StylusNodeBlock); - constructor(parent: StylusNodeBlock, node: StylusNode); - - /** - * Push a `node` to this block. - */ - push(node: StylusNode): void; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; nodes: StylusNode[]; scope: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeGroup extends StylusNode { - nodes: StylusNode[]; - block: StylusNodeBlock; - - hasOnlyPlaceholders: boolean; - - constructor(); - - /** - * Push the given `selector` node. - */ - push(node: StylusNode): void; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; nodes: StylusNode[]; block: StylusNodeBlock; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeExpression extends StylusNode { - nodes: StylusNode[]; - isList: boolean; - - isEmpty: boolean; - first: StylusNode; - - constructor(isList: boolean); - - /** - * Push the given node. - */ - push(node: StylusNode): void; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; nodes: StylusNode[]; isList: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeProperty extends StylusNode { - segments: StylusNode[]; - expr: StylusNodeExpression; - - constructor(segs: StylusNode[], expr: StylusNodeExpression); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; segments: StylusNode[]; name: string; expr?: StylusNodeExpression; literal?: StylusNodeLiteral; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeEach extends StylusNode { - val: string; - key: string; - expr: StylusNodeExpression; - block: StylusNodeBlock; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; val: string; key: string; expr: StylusNodeExpression; block: StylusNodeBlock; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeIf extends StylusNode { - cond: StylusNodeExpression; - elses: StylusNodeExpression[]; - block: StylusNodeBlock; - negate: boolean; - - constructor(cond: StylusNodeExpression, negate: boolean); - constructor(cond: StylusNodeExpression, block: StylusNodeBlock); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; cond: StylusNodeExpression; elses: StylusNodeExpression[]; block: StylusNodeBlock; negate: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeCall extends StylusNode { - name: string; - args: StylusNodeExpression; - - constructor(name: string, args: StylusNodeExpression); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; name: string; args: StylusNodeExpression; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeUnaryOp extends StylusNode { - op: string; - expr: StylusNodeExpression; - - constructor(op: string, expr: StylusNodeExpression); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; op: string; expr: StylusNodeExpression; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeBinOp extends StylusNode { - op: string; - left: StylusNodeExpression; - right: StylusNodeExpression; - - constructor(op: string, left: StylusNodeExpression, right: StylusNodeExpression); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; op: string; left: StylusNodeExpression; right: StylusNodeExpression; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeTernary extends StylusNode { - op: string; - trueExpr: StylusNodeExpression; - falseExpr: StylusNodeExpression; - - constructor(op: string, trueExpr: StylusNodeExpression, falseExpr: StylusNodeExpression); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; op: string; trueExpr: StylusNodeExpression; falseExpr: StylusNodeExpression; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeReturn extends StylusNode { - expr: StylusNodeExpression; - - constructor(expr: StylusNodeExpression); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; expr: StylusNodeExpression; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeMedia extends StylusNode { - val: string; - - constructor(val: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeQueryList extends StylusNode { - nodes: StylusNode[]; - - constructor(); - - /** - * Push the given `node`. - */ - push(node: StylusNode): void; - - /** - * Merges this query list with the `other`. - */ - merge(other: MediaQueryList): MediaQueryList; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; nodes: StylusNode[]; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeQuery extends StylusNode { - nodes: StylusNodeQueryExpr[]; - type: string; - predicate: string; - - resolvedType: string; - resolvedPredicate: string; - - constructor(); - - /** - * Push the given `expr`. - */ - push(expr: StylusNodeQueryExpr): void; - - /** - * Merges this query with the `other`. - */ - merge(other: StylusNodeQuery): StylusNodeQuery; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; nodes: StylusNodeQueryExpr[]; predicate: string; type: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeQueryExpr extends StylusNode { - segments: StylusNode[]; - expr: StylusNodeExpression; - - constructor(segs: StylusNode[]); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; segments: StylusNode[]; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeParams extends StylusNode { - nodes: StylusNode[]; - - length: number; - - /** - * Push the given `node`. - */ - push(node: StylusNode): void; - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; nodes: StylusNode[]; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeComment extends StylusNode { - str: string; - suppress: boolean; - inline: boolean; - - constructor(str: string, suppress: boolean, inline: boolean); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; str: string; suppress: boolean; inline: boolean; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeKeyframes extends StylusNode { - segments: StylusNode[]; - prefix: string; - - constructor(segs: StylusNode[]); - constructor(segs: StylusNode[], prefix: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; segments: StylusNode[]; prefix: string; block: StylusNodeBlock; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeMember extends StylusNode { - left: StylusNode; - right: StylusNode; - - constructor(left: StylusNode, right: StylusNode); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; left: StylusNode; right: StylusNode; val?: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeCharset extends StylusNode { - val: string; - - constructor(val: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeNamespace extends StylusNode { - val: string; - prefix: string; - - constructor(val: string, prefix: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; val: string; prefix: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeImport extends StylusNode { - path: StylusNodeExpression; - once: boolean; - - constructor(path: StylusNodeExpression); - constructor(path: StylusNodeExpression, once: boolean); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; path: StylusNodeExpression; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeExtend extends StylusNode { - selectors: StylusNodeSelector[]; - - constructor(selectors: StylusNodeSelector[]); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; selectors: StylusNodeSelector[]; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeFunction extends StylusNode { - name: string; - params: StylusNodeParams; - body: StylusNodeBlock; - - constructor(name: string, params: StylusNodeParams, body: StylusNodeBlock); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; name: string; params: StylusNodeParams; body: StylusNodeBlock; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeSelector extends StylusNode { - inherits: boolean; - segments: StylusNode[]; - - constructor(segs: StylusNode[]); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; segments: StylusNode[]; inherits: boolean; val: string; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeArguments extends StylusNodeExpression { - map: StylusDictionary; - - constructor(); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; map: StylusDictionary; isList: boolean; preserve: boolean; nodes: StylusNode[]; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeAtblock extends StylusNode { - block: StylusNodeBlock; - nodes: StylusNode[]; - - constructor(); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; block: StylusNodeBlock; lineno: number; column: number; filename: string }; -} - -declare class StylusNodeAtrule extends StylusNode { - type: string; - - hasOnlyProperties: boolean; - - constructor(type: string); - - /** - * Return a JSON representation of this node. - */ - toJSON(): { __type: string; type: string; segments: StylusNode[]; block?: StylusNodeBlock; lineno: number; column: number; filename: string }; -} - -//#endregion - -//#region Internal Interfaces - -interface StylusDictionary { - [key: string]: T; -} - -interface StylusRenderOptions { - globals: StylusDictionary; - functions: StylusDictionary; - imports: string[]; - paths: string[]; - filename: string; - Evaluator: typeof StylusEvaluator; -} - -interface StylusRenderCallback { - (err: Error, css: string, js: string): void; -} - -interface StylusUrlOptions { - limit?: string; - path: string; -} - -interface StylusLiteralFunction { - (url: string): StylusNodeLiteral; - raw: boolean; -} - -interface StylusExceptionOptions { - filename: string; - context: number; - lineno: number; - column: number; - input: string; -} - -//#endregion - declare module "stylus" { - export = StylusStatic; + var stylus: Stylus.Static; + export = stylus; } From 4b36594da852d2d08543c0ee649647e767c860cf Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Mon, 15 Sep 2014 21:42:47 +0200 Subject: [PATCH 051/149] Add test suite for stylus --- stylus/stylus-tests.ts | 104 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 stylus/stylus-tests.ts diff --git a/stylus/stylus-tests.ts b/stylus/stylus-tests.ts new file mode 100644 index 000000000..78b2456df --- /dev/null +++ b/stylus/stylus-tests.ts @@ -0,0 +1,104 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/LearnBoost/stylus/blob/master/docs/js.md. + */ + +/// +/// +/// + +import stylus = require("stylus"); + +var str = "This is a stylus test"; + +/** + * Basic Usage + */ +stylus.render(str, { filename: 'nesting.css' }, function(err, css){ + if (err) throw err; + console.log(css); +}); + +stylus(str) + .set('filename', 'nesting.css') + .render(function (err, css) { + // logic + }); + +/** + * .set(setting, value) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#setsetting-value + */ +stylus(str) + .set('filename', __dirname + '/test.styl') + .set('paths', [__dirname, __dirname + '/mixins']) + .render(function (err, css) { + // logic + }); + +/** + * .include(path) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#includepath + */ +stylus(str) + .include(require('nib').path) + .include(process.env.HOME + '/mixins') + .render(function (err, css) { + // logic + }); + +/** + * .import(path) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#importpath + */ +stylus(str) + .set('filename', __dirname + '/test.styl') + .import('mixins/vendor') + .render(function (err, css) { + if (err) throw err; + console.log(css); + }); + +/** + * .define(name, node|fn) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#definename-node + */ +stylus(str) + .define('has-canvas', stylus.nodes.false) + .define('some-setting', new stylus.nodes.String('some value')) + + .define('string', 'some string') + .define('number', 15.5) + .define('some-bool', true) + .define('list', [1, 2, 3]) + .define('list', [1, 2, [3, 4, [5, 6]]]) + .define('list', { foo: 'bar', bar: 'baz' }) + .define('families', ['Helvetica Neue', 'Helvetica', 'sans-serif']) + + .define('get-list', function () { + return ['foo', 'bar', 'baz']; + }) + + .render(function (err, css) { + if (err) throw err; + console.log(css); + }); + +/** + * .use(fn) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#usefn + */ +var mylib = function (style: Stylus.Renderer) { + style.define('number', 15.5); + style.define('get-list', function () { + return ['foo', 'bar', 'baz']; + }); +}; + +stylus(str) + .use(mylib) + .render(function (err, css) { + if (err) throw err; + console.log(css); + }); From 9e90c5c89a155e5e2d1ade6c2a14a3c31ea8a1c2 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 01:44:27 +0200 Subject: [PATCH 052/149] Add node tar definitions --- node-tar/node-tar.d.ts | 218 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 node-tar/node-tar.d.ts diff --git a/node-tar/node-tar.d.ts b/node-tar/node-tar.d.ts new file mode 100644 index 000000000..4f3d6278f --- /dev/null +++ b/node-tar/node-tar.d.ts @@ -0,0 +1,218 @@ +// Type definitions for node-tar v1.0.1 +// Project: https://github.com/npm/node-tar +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "tar" { + import stream = require("stream"); + + //#region Interfaces + + export interface HeaderProperties { + path?: string; + mode?: number; + uid?: number; + gid?: number; + size?: number; + mtime?: number; + uname?: string; + gname?: string; + devmaj?: number; + devmin?: number; + } + + export interface ExtractOptions { + type?: string; + Directory?: boolean; + path?: string; + strip?: number; + } + + export interface ParseStream extends stream.Stream { + writable: boolean; + readable: boolean; + position: number; + + _stream: stream.Stream; + _ended: boolean; + + write(c: Buffer): boolean; + end(c: Buffer): void; + + _streamEnd(): void; + _read(): void; + _process(c: Buffer): void; + _startEntry(c: Buffer): void; + } + + export interface PackStream extends stream.Stream { + writable: boolean; + readable: boolean; + + _noProprietary: boolean; + _global: HeaderProperties; + _buffer: stream.Stream[]; + _currentEntry: any; + _processing: boolean; + _pipeRoot: stream.Stream; + _needDrain: boolean; + _paused: boolean; + + addGlobal(props: HeaderProperties): void; + add(stream: stream.Stream): boolean; + pause(): void; + resume(): void; + destroy(): void; + write(): void; + + _process(): void; + } + + export interface ExtractStream extends ParseStream { + } + + //#endregion + + //#region Enums + + export var fields: { + path: number; + mode: number; + uid: number; + gid: number; + size: number; + mtime: number; + cksum: number; + type: number; + linkpath: number; + ustar: number; + ustarvar: number; + uname: number; + gname: number; + devmaj: number; + devmin: number; + prefix: number; + fill: number; + }; + + export var fieldSize: number[]; + export var fieldOffs: number[]; + export var fieldEnds: number[]; + + /** + * Different values of the 'type' field + * paths match the values of Stats.isX() functions, where appropriate + */ + export var types: { + 0: string; + "\0": string; + "": string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + g: string; + x: string; + A: string; + D: string; + I: string; + K: string; + L: string; + M: string; + N: string; + S: string; + V: string; + X: string; + File: string; + OldFile: string; + Link: string; + SymbolicLick: string; + CharacterDevice: string; + BlockDevice: string; + Directory: string; + FIFO: string; + ContiguousFile: string; + GlobalExtendedHeader: string; + ExtendedHeader: string; + SolarisACL: string; + GNUDumpDir: string; + INode: string; + NextFileHasLonLinkPath: string; + NextFileHasLongPath: string; + ContinuationFile: string; + TapeVolumeHeader: string; + OldExtendedHeader: string; + }; + + /** + * Values for the mode field + */ + export var modes: { + suid: number; + sgid: number; + svtx: number; + uread: number; + uwrite: number; + uexec: number; + gread: number; + gwrite: number; + gexec: number; + oread: number; + owrite: number; + oexec: number; + }; + + export var numeric: { + mode: boolean; + uid: boolean; + gid: boolean; + size: boolean; + mtime: boolean; + devmaj: boolean; + devmin: boolean; + cksum: boolean; + atime: boolean; + ctime: boolean; + dev: boolean; + ino: boolean; + nlink: boolean; + }; + + export var knownExtended: { + atime: boolean; + charset: boolean; + comment: boolean; + ctime: boolean; + gid: boolean; + gname: boolean; + linkpat: boolean; + mtime: boolean; + path: boolean; + realtime: boolean; + security: boolean; + size: boolean; + uid: boolean; + uname: boolean; + }; + + export var headerSize: number; + export var blockSize: number; + + //#endregion + + //#region Global Methods + + export function Parse(): ParseStream; + + export function Pack(props: HeaderProperties): PackStream; + + export function Extract(path: string): ExtractStream; + export function Extract(opts: ExtractOptions): ExtractStream; + + //#endregion +} \ No newline at end of file From ab98ab4feecb134c1d3751eb2398b8b1880cd5c2 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 01:55:33 +0200 Subject: [PATCH 053/149] Add node-tar test suite --- node-tar/node-tar-tests.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 node-tar/node-tar-tests.ts diff --git a/node-tar/node-tar-tests.ts b/node-tar/node-tar-tests.ts new file mode 100644 index 000000000..0a526faca --- /dev/null +++ b/node-tar/node-tar-tests.ts @@ -0,0 +1,28 @@ +/** +* Test suite created by Maxime LUCE +* +* Created by using code samples from https://github.com/npm/node-tar. +*/ + +/// +/// + +import tar = require("tar"); +import fs = require("fs"); + +/** + * Quick Extract + */ +fs.createReadStream("path/to/file.tar").pipe(tar.Extract("path/to/extract")); + +/** + * Use with events + */ +var readStream = fs.createReadStream("/path/to/file.tar"); +var extract = tar.Extract("/path/to/target"); + +readStream.pipe(extract); + +extract.on("entry", (entry: any) => { + +}); From 93b8b97b402bd96ba869d1f85b2ec420028d37f9 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 02:04:53 +0200 Subject: [PATCH 054/149] Fix some stream related issues --- node-tar/node-tar-tests.ts | 2 +- node-tar/node-tar.d.ts | 15 ++++----------- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/node-tar/node-tar-tests.ts b/node-tar/node-tar-tests.ts index 0a526faca..727dbc08c 100644 --- a/node-tar/node-tar-tests.ts +++ b/node-tar/node-tar-tests.ts @@ -5,7 +5,7 @@ */ /// -/// +/// import tar = require("tar"); import fs = require("fs"); diff --git a/node-tar/node-tar.d.ts b/node-tar/node-tar.d.ts index 4f3d6278f..06bc61f37 100644 --- a/node-tar/node-tar.d.ts +++ b/node-tar/node-tar.d.ts @@ -30,24 +30,20 @@ declare module "tar" { strip?: number; } - export interface ParseStream extends stream.Stream { - writable: boolean; - readable: boolean; + export interface ParseStream extends NodeJS.ReadableStream { } + export interface ParseStream extends NodeJS.WritableStream { position: number; _stream: stream.Stream; _ended: boolean; - write(c: Buffer): boolean; - end(c: Buffer): void; - _streamEnd(): void; - _read(): void; _process(c: Buffer): void; _startEntry(c: Buffer): void; } - export interface PackStream extends stream.Stream { + export interface PackStream extends NodeJS.ReadableStream { } + export interface PackStream extends NodeJS.WritableStream { writable: boolean; readable: boolean; @@ -62,10 +58,7 @@ declare module "tar" { addGlobal(props: HeaderProperties): void; add(stream: stream.Stream): boolean; - pause(): void; - resume(): void; destroy(): void; - write(): void; _process(): void; } From 93a9e8bb8e8a143abfe86be2bd29a07cdd722025 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 03:58:23 +0200 Subject: [PATCH 055/149] Add npm definitions --- npm/npm.d.ts | 461 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 461 insertions(+) create mode 100644 npm/npm.d.ts diff --git a/npm/npm.d.ts b/npm/npm.d.ts new file mode 100644 index 000000000..e81fb6c5b --- /dev/null +++ b/npm/npm.d.ts @@ -0,0 +1,461 @@ +// Type definitions for npm 2.0.0 +// Project: https://github.com/npm/npm +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module NPM { + export interface Static extends NodeJS.EventEmitter { + config: Config; + commands: Commands; + rollbacks: any[]; + spinner: Spinner; + fullList: string[]; + abbrevs: Dictionary; + + prefix: string; + bin: string; + globalBin: string; + dir: string; + globalDir: string; + root: string; + cache: string; + tmp: string; + + + load(cli: ConfigOptions): void; + load(callback: SimpleCallback): void; + load(cli: ConfigOptions, callback: SimpleCallback): void; + + deref(command: string): string; + } + + //#region Commands Interfaces + + export interface Commands { + // Commands + install: CommandFunction; + uninstall: CommandFunction; + cache: CommandFunction; + config: CommandFunction; + set: CommandFunction; + get: CommandFunction; + update: CommandFunction; + outdated: CommandFunction; + prune: CommandFunction; + submodule: CommandFunction; + pack: CommandFunction; + dedupe: CommandFunction; + + rebuild: CommandFunction; + link: CommandFunction; + + publish: CommandFunction; + star: CommandFunction; + stars: CommandFunction; + tag: CommandFunction; + adduser: CommandFunction; + unpublish: CommandFunction; + owner: CommandFunction; + deprecate: CommandFunction; + shrinkwrap: CommandFunction; + + help: CommandFunction; + "help-search": CommandFunction; + ls: CommandFunction; + search: CommandFunction; + view: CommandFunction; + init: CommandFunction; + version: CommandFunction; + edit: CommandFunction; + explore: CommandFunction; + docs: CommandFunction; + repo: CommandFunction; + bugs: CommandFunction; + faq: CommandFunction; + root: CommandFunction; + prefix: CommandFunction; + bin: CommandFunction; + whoami: CommandFunction; + + test: CommandFunction; + stop: CommandFunction; + start: CommandFunction; + restart: CommandFunction; + "run-script": CommandFunction; + completion: CommandFunction; + + //Aliases + rm: CommandFunction; // uninstall + r: CommandFunction; // uninstall + un: CommandFunction; // uninstall + unlink: CommandFunction; // uninstall + remove: CommandFunction; // uninstall + rb: CommandFunction; // rebuild + list: CommandFunction; // ls + la: CommandFunction; // ls + ll: CommandFunction; // ls + i: CommandFunction; // install + isntall: CommandFunction; // install + up: CommandFunction; // update + c: CommandFunction; // config + info: CommandFunction; // view + show: CommandFunction; // view + find: CommandFunction; // search + s: CommandFunction; // search + se: CommandFunction; // search + author: CommandFunction; // owner + home: CommandFunction; // docs + issues: CommandFunction; // bugs + unstar: CommandFunction; // star + apihelp: CommandFunction; // help + long: CommandFunction; // adduser + "add-user": CommandFunction; // adduser + tst: CommandFunction; // test + t: CommandFunction; // test + "find-dupes": CommandFunction; // dedupe + ddp: CommandFunction; // dedupe + v: CommandFunction; // view + + // plumbing + build: CommandFunction; + unbuild: CommandFunction; + xmas: CommandFunction; + substack: CommandFunction; + visnup: CommandFunction; + + } + + export interface CommandFunction { + (args: string[], callback: CommandCallback): void; + } + + export interface CommandCallback { + (err?: Error, result?: any, result2?: any, result3?: any, result4?: any): void; + } + + //#endregion + + //#region Other Interfaces + + export interface Spinner { + int: string; + started: boolean; + start(): void; + stop(): void; + } + + //#endregion + + //#region Config Interfaces + + export interface ConfigStatic { + new (base: Config): Config; + (base: Config): Config; + } + + export interface Config { + loaded: boolean; + sources: Dictionary; + rootConf: Config; + usingBuiltin: boolean; + root?: Config; + Conf: ConfigStatic; + defs: ConfigDefs; + + get(setting: string): string; + set(setting: string, value: string): void; + + loadPrefix(cb: ErrorCallback): void; + loadCAFile(caFilePath: string, cb: ErrorCallback): void; + loadUid(cb: SimpleCallback): void; + setUser(cb: ErrorCallback): void; + findPrefix(prefix: string, cb: SimpleCallback): void; + getCredentialsByURI(uri: string): Credentials; + setCredentialsByURI(uri: string, cred: Credentials): void; + + loadExtras(cb: ErrorCallback): void; + save(where: string, cb: ErrorCallback): Config; + addFile(file: string, name: string): Config; + parse(content: string, file: string): any; + add(data: Object, marker: Object): any; + addEnv(env: Dictionary): any; + } + + export interface ConfigDefs { + defaults: ConfigOptions; + types: ConfigTypes; + } + + export interface ConfigOptions { + "always-auth"?: boolean; + "bin-links"?: boolean; + browser?: string; + + ca?: any; // string | string[] + cafile?: string; + + cache?: string; + + "cache-lock-stale"?: number; + "cache-lock-retries"?: number; + "cache-lock-wait"?: number; + + "cache-max"?: number; + "cache-min"?: number; + + cert?: string; + + color?: any; // boolean | string ("always") + depth?: number; + description?: boolean; + dev?: boolean; + editor?: string; + "engine-strict"?: boolean; + force?: boolean; + + "fetch-retries"?: number; + "fetch-retry-factor"?: number; + "fetch-retry-mintimeout"?: number; + "fetch-retry-maxtimeout"?: number; + + git?: string; + "git-tag-version"?: boolean; + + global?: boolean; + globalconfig?: string; + group?: any; // number | string + heading?: string; + "ignore-scripts"?: boolean; + "init-module"?: string; + "init.author.name"?: string; + "init.author.email"?: string; + "init.author.url"?: string; + "init.version"?: string; + "init.license"?: string; + json?: boolean; + key?: string; + link?: boolean; + "local-address"?: string; + loglevel?: string; + logstream?: NodeJS.ReadWriteStream; + long?: boolean; + message?: string; + "node-version"?: string; + npat?: boolean; + "onload-script"?: boolean; + optional?: boolean; + parseable?: boolean; + prefix?: string; + production?: boolean; + "proprietary-attribs"?: boolean; + proxy?: any; // boolean | string + "https-proxy"?: string; + "user-agent"?: string; + "rebuild-bundle"?: boolean; + registry?: string; + rollback?: boolean; + save?: boolean; + "save-bundle"?: boolean; + "save-dev"?: boolean; + "save-exact"?: boolean; + "save-optional"?: boolean; + "save-prefix"?: string; + scope?: string; + searchopts?: string; + searchexclude?: string; + searchsort?: string; + shell?: string; + shrinkwrap?: boolean; + "sign-git-tag"?: boolean; + spin?: any; // boolean | string ("always") + "strict-ssl"?: boolean; + tag?: string; + tmp?: string; + unicode?: boolean; + "unsafe-perm"?: boolean; + usage?: boolean; + user?: any; // string | number + userconfig?: string; + umask?: number; + version?: boolean; + versions?: boolean; + viewer?: string; + + _exit?: boolean; + } + + export interface ConfigTypes { + "always-auth": typeof Boolean; + "bin-links": typeof Boolean; + browser: any[]; + + ca: any[]; + cafile: typeof String; + cache: typeof String; + + "cache-lock-stale": typeof Number; + "cache-lock-retries": typeof Number; + "cache-lock-wait": typeof Number; + + "cache-max": typeof Number; + "cache-min": typeof Number; + + cert: typeof String; + + color: any[]; + depth: typeof Number; + description: typeof Boolean; + dev: typeof Boolean; + editor: typeof String; + "engine-strict": typeof Boolean; + force: typeof Boolean; + + "fetch-retries": typeof Number; + "fetch-retry-factor": typeof Number; + "fetch-retry-mintimeout": typeof Number; + "fetch-retry-maxtimeout": typeof Number; + + git: typeof String; + "git-tag-version": typeof Boolean; + + global: typeof Boolean; + globalconfig: typeof String; + group: any[]; + heading: typeof String; + "ignore-scripts": typeof Boolean; + "init-module": typeof String; + "init.author.name": typeof String; + "init.author.email": typeof String; + "init.author.url": typeof String; + "init.version": typeof String; + "init.license": typeof String; + json: typeof Boolean; + key: any[]; + link: typeof Boolean; + "local-address": typeof String; + loglevel: any[]; + logstream: any; // typeof stream.Stream + long: typeof Boolean; + message: typeof String; + "node-version": any[]; + npat: typeof Boolean; + "onload-script": any[]; + optional: typeof Boolean; + parseable: typeof Boolean; + prefix: typeof String; + production: typeof Boolean; + "proprietary-attribs": typeof Boolean; + proxy: any[]; + "https-proxy": any[]; + "user-agent": typeof String; + "rebuild-bundle": Boolean; + registry: any[]; + rollback: typeof Boolean; + save: typeof Boolean; + "save-bundle": typeof Boolean; + "save-dev": typeof Boolean; + "save-exact": typeof Boolean; + "save-optional": typeof Boolean; + "save-prefix": typeof String; + scope: typeof String; + searchopts: typeof String; + searchexclude: any[]; + searchsort: any[]; + shell: typeof String; + shrinkwrap: typeof Boolean; + "sign-git-tag": typeof Boolean; + spin: any[]; + "strict-ssl": typeof Boolean; + tag: typeof String; + tmp: typeof String; + unicode: typeof Boolean; + "unsafe-perm": typeof Boolean; + usage: typeof Boolean; + user: any; // String | Number + userconfig: typeof String; + umask: typeof Number; + version: typeof Boolean; + versions: typeof Boolean; + viewer: typeof String; + + _exit: typeof Boolean; + } + + export interface ConfigShorthands { + s: any[]; + d: any[]; + dd: any[]; + ddd: any[]; + noreg: any[]; + N: any[]; + reg: any[]; + "no-reg": any[]; + silent: any[]; + verbose: any[]; + quiet: any[]; + q: any[]; + h: any[]; + H: any[]; + "?": any[]; + help: any[]; + v: any[]; + f: any[]; + gangster: any[]; + gangsta: any[]; + desc: any[]; + "no-desc": any[]; + "local": any[]; + l: any[]; + m: any[]; + p: any[]; + porcelain: any[]; + g: any[]; + S: any[]; + D: any[]; + E: any[]; + O: any[]; + y: any[]; + n: any[]; + B: any[]; + C: any[]; + } + + export interface ConfigSource { + path: string; + type: string; + } + + export interface Credentials { + scope: string; + token?: string; + password?: string; + username?: string; + email?: string; + auth?: string; + } + + //#endregion + + //#region Utilities Interfaces + + export interface Dictionary { + [key: string]: T; + } + + export interface ErrorCallback { + (err?: Error): void; + } + + export interface SimpleCallback { + (err?: Error, result?: T): void; + } + + //#endregion +} + +declare module "npm" { + var npm: NPM.Static; + export = npm; +} From 85f4f72d9b1c0f9a3760d80023f478281d7efbaa Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:11:30 +0200 Subject: [PATCH 056/149] Add npm tests --- npm/npm-tests.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 npm/npm-tests.ts diff --git a/npm/npm-tests.ts b/npm/npm-tests.ts new file mode 100644 index 000000000..9a8578264 --- /dev/null +++ b/npm/npm-tests.ts @@ -0,0 +1,28 @@ +/** +* Test suite created by Maxime LUCE +* +* Created by using code samples from https://github.com/npm/npm#using-npm-programmatically. +*/ + +/// +/// + +import npm = require("npm"); + +npm.load({}, function (er) { + if (er) { + return console.error(er); + } + + npm.commands.install(["some", "args"], function (er, data) { + if (er) { + return console.error(er); + } + + // command succeeded, and data might have some info + }); + + npm.on("log", function (message: string) { + console.log(message); + }); +}) From e761aa1248be400e1dd802445fb0a8411c1a1bf8 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:15:51 +0200 Subject: [PATCH 057/149] Optimize streams definitions by extending NodeNS.ReadWriteStream --- node-tar/node-tar.d.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/node-tar/node-tar.d.ts b/node-tar/node-tar.d.ts index 06bc61f37..fc9bf3256 100644 --- a/node-tar/node-tar.d.ts +++ b/node-tar/node-tar.d.ts @@ -30,8 +30,7 @@ declare module "tar" { strip?: number; } - export interface ParseStream extends NodeJS.ReadableStream { } - export interface ParseStream extends NodeJS.WritableStream { + export interface ParseStream extends NodeJS.ReadWriteStream { position: number; _stream: stream.Stream; @@ -42,8 +41,7 @@ declare module "tar" { _startEntry(c: Buffer): void; } - export interface PackStream extends NodeJS.ReadableStream { } - export interface PackStream extends NodeJS.WritableStream { + export interface PackStream extends NodeJS.ReadWriteStream { writable: boolean; readable: boolean; From b8a1d326aaa0f6d262a9efca57543b75f8d0f930 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:20:48 +0200 Subject: [PATCH 058/149] Implements NodeJS.EventEmitter in Renderer --- stylus/stylus.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts index dffb04cf0..d6fd6ef5b 100644 --- a/stylus/stylus.d.ts +++ b/stylus/stylus.d.ts @@ -633,7 +633,7 @@ declare module Stylus { export class Compiler { } - export class Renderer { //extends events.EventEmitter { + export class Renderer implements NodeJS.EventEmitter { options: RenderOptions; str: string; events: any; @@ -690,6 +690,17 @@ declare module Stylus { * Import the given `file`. */ import(file: string): Renderer; + + //#region EventEmitter Members + addListener(event: string, listener: Function): Renderer; + on(event: string, listener: Function): Renderer; + once(event: string, listener: Function): Renderer; + removeListener(event: string, listener: Function): Renderer; + removeAllListeners(event?: string): Renderer; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + //#endregion } //#endregion From adf4c5c9f7f8e1f8c820c0a879df17373277f097 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:23:48 +0200 Subject: [PATCH 059/149] Add stylus to Contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..5a07baf48 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -345,6 +345,7 @@ All definitions files include a header with the author and editors, so at some p * [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame)) * [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone)) +* [stylus](https://github.com/LearnBoost/stylus) (by [Maxime LUCE](https://github.com/SomaticIT)) * [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Swiper](http://www.idangero.us/sliders/swiper) (by [Sebastián Galiano](https://github.com/sgaliano)) * [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) From 6cef5d5f96d9dbe9982ac21e3b9ff50201b5cba9 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:25:12 +0200 Subject: [PATCH 060/149] Adding i18n-node to contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..f51c5d557 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -134,6 +134,7 @@ All definitions files include a header with the author and editors, so at some p * [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613)) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) +* [i18n-node](https://github.com/mashpie/i18n-node) (by [Maxime LUCE](https://github.com/SomaticIT)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) From c078217a5a2f27f655192861b10d6376fdb3f858 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:26:46 +0200 Subject: [PATCH 061/149] Add jsonwebtoken to contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..7257af244 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -210,6 +210,7 @@ All definitions files include a header with the author and editors, so at some p * [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) * [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) * [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) (by [Maxime LUCE](https://github.com/SomaticIT)) * [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki)) * [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/)) * [jsTree](http://www.jstree.com/) (by [Adam Pluciński](https://github.com/adaskothebeast)) From 217920c5b59fe506df4328ef85e20a08f8203971 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:27:57 +0200 Subject: [PATCH 062/149] Add node-tar to contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index eb9f9b64e..e3ba0b3ba 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -278,6 +278,7 @@ All definitions files include a header with the author and editors, so at some p * [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) * [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-tar](https://github.com/npm/node-tar) (by [Maxime LUCE](https://github.com/SomaticIT)) * [node-uuid](https://github.com/broofa/node-uuid) (by [Jeff May](https://github.com/jeffmay)) * [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) From a447d5c541784ba088880cc176b66fa95a272edb Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:28:28 +0200 Subject: [PATCH 063/149] Add npm to contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index eb9f9b64e..4686fec17 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -280,6 +280,7 @@ All definitions files include a header with the author and editors, so at some p * [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) * [node-uuid](https://github.com/broofa/node-uuid) (by [Jeff May](https://github.com/jeffmay)) * [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) +* [npm](https://github.com/npm/npm) (by [Maxime LUCE](https://github.com/SomaticIT)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) * [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/)) From cf42a56f72e2fcf1104758bfe3fdbaee499dcadb Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:29:41 +0200 Subject: [PATCH 064/149] Add passport-local to contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..1712e4a2d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -286,6 +286,7 @@ All definitions files include a header with the author and editors, so at some p * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) * [passport-facebook](https://github.com/jaredhanson/passport-facebook) (by [James Roland Cabresos](https://github.com/staticfunction/)) +* [passport-local](https://github.com/jaredhanson/passport-local) (by [Maxime LUCE](https://github.com/SomaticIT)) * [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm)) * [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) From e032721081f8ebcf7b8b01899749bb480aad3623 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:30:34 +0200 Subject: [PATCH 065/149] Add sendgrid to contributors.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..b4441e234 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -324,6 +324,7 @@ All definitions files include a header with the author and editors, so at some p * [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) * [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428)) +* [sendgrid](https://github.com/sendgrid/sendgrid-nodejs) (by [Maxime LUCE](https://github.com/SomaticIT)) * [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) * [ShellJS](http://shelljs.org) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [Showdown](https://github.com/coreyti/showdown) (by [Chris Bowdon](https://github.com/cbowdon)) From 1785970ea15696f6975b66b73560e5214b0c1d3b Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Tue, 16 Sep 2014 04:38:45 +0200 Subject: [PATCH 066/149] Add contributors for azure sdk --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef83ff093..b0e4d7a2e 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -270,6 +270,7 @@ All definitions files include a header with the author and editors, so at some p * [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) * [Node.js](http://nodejs.org/) (from TypeScript samples) * [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-azure](https://github.com/Azure/azure-sdk-for-node) (by [Andrew Gaspar](https://github.com/AndrewGaspar), [Anti Veeranna](https://github.com/antiveeranna) and [Maxime LUCE](https://github.com/SomaticIT)) * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) * [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec)) * [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) From 97a4f36d64639fecd8b3e0c0eb527a7378e7ca87 Mon Sep 17 00:00:00 2001 From: Panu Horsmalahti Date: Tue, 16 Sep 2014 12:19:41 +0300 Subject: [PATCH 067/149] Add exists function to i18next --- i18next/i18next-tests.ts | 19 ++++++++++++++++++- i18next/i18next.d.ts | 7 ++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/i18next/i18next-tests.ts b/i18next/i18next-tests.ts index f40d10b3a..b1732de11 100644 --- a/i18next/i18next-tests.ts +++ b/i18next/i18next-tests.ts @@ -6,7 +6,7 @@ /// declare function done(): void; - + describe('i18next', function () { var i18n = $.i18n @@ -685,6 +685,23 @@ describe('i18next', function () { }); }); + describe('exists functionality', function () { + var resStore = { + dev: { translation: { empty: '' } }, + en: { translation: {} }, + 'en-US': { translation: {} } + }; + + beforeEach(function (done) { + i18n.init($.extend(opts, { resStore: resStore }), + function (t) { done(); }); + }); + + it('it should be able to test if a key exists', function () { + expect(i18n.exists('empty')).to.be(false); + }); + }); + describe('resource string as array', function () { var resStore = { dev: { translation: { testarray: ["title", "text"] } }, diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index e9083c4d5..54bd439f4 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -109,6 +109,7 @@ interface I18nextStatic { }; t(key: string, options?: any): string; translate(key: string, options?: any): string; + exists(key: string, options?: any): boolean; } // jQuery extensions @@ -118,9 +119,9 @@ interface JQueryStatic { } interface JQuery { - /* Note: options are same options as used by the translate function. Alternatively by - setting init option or translation option 'useDataAttrOptions = true' the Options - for translation will be read and cached in the elements data-i18n-options attribute. + /* Note: options are same options as used by the translate function. Alternatively by + setting init option or translation option 'useDataAttrOptions = true' the Options + for translation will be read and cached in the elements data-i18n-options attribute. */ i18n: (options?: I18nextOptions) => void; } From e614990852d73effb455b9da1b3d33c1d1ebafa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pekka=20Lepp=C3=A4nen?= Date: Tue, 16 Sep 2014 14:49:38 +0300 Subject: [PATCH 068/149] Added sendStatus() to express.Response Added as described in documentation: http://expressjs.com/4x/api.html#res.sendStatus --- express/express.d.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/express/express.d.ts b/express/express.d.ts index 17c4ff36a..cf5014e82 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -424,7 +424,22 @@ declare module "express" { * @param code */ status(code: number): Response; - + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Send; + /** * Set Link header field with the given `links`. * From 8143c162e721261a3ab6626e003882ec89ceaddb Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 17 Sep 2014 01:00:47 +0100 Subject: [PATCH 069/149] Update Swig to latest version The swig definitions have been totally rewritten to the latest version as of time of commit. See: http://paularmstrong.github.io/swig/docs/api/ for how the API should work. --- swig/swig-tests.ts | 65 +++++++++++++++---- swig/swig.d.ts | 156 +++++++++++++++++++++++++++++++++++++++------ 2 files changed, 188 insertions(+), 33 deletions(-) diff --git a/swig/swig-tests.ts b/swig/swig-tests.ts index 1f68aa44c..7a6be47f8 100644 --- a/swig/swig-tests.ts +++ b/swig/swig-tests.ts @@ -2,24 +2,61 @@ import swig = require('swig'); +var swigObj: swig.Swig; var value: any; var str: string; var num: number; var bool: boolean; -var opts: swig.Options = { - allowErrors: bool, - autoescape: bool, - cache: bool, - encoding: str, - filters: value, - root: str, - tags: value, - extensions: value, - tzOffset: num +function replaceMs(input:string): string { + return input.replace(/m/g, 'f'); +} + +var opts: swig.SwigOptions = { + autoescape: bool, + cache: value, + cmtControls: ["", ""], + loader: swig.loaders.fs(), + locals: { testVal: "my test" }, + tagControls: ["", ""], + varControls: ["", ""] }; -swig.init(opts); -value = swig.compileFile(str); -value = swig.compile(str); -value = swig.compile(str, opts); +swig.setDefaults(opts); +swig.setDefaultTZOffset(num); +swigObj = new swig.Swig(opts); +str = swig.compileFile(str)(); +swig.compileFile(str, {}, function (err: any, render: (locals: any) => string) { + str = render({}); +}); +str = swig.compile(str)(); +str = swig.compile(str, opts)(); +swig.invalidateCache(); +swig.setFilter("replaceMs", replaceMs); +swig.setTag('tacos', function (): boolean { return true; }, function (): string { return 'Tacos' }, true, true); +swig.setExtension("test", function (v: string) { return 'test: ' + v }); +value = swig.precompile(str, opts); +str = swig.render(str, opts); +str = swig.renderFile(str, {}); +swig.renderFile(str, {}, function (err, output: string) { + +}); +console.log(swig.version); + + +str = swigObj.compileFile(str)(); +swigObj.compileFile(str, opts, function (err: any, render: (locals: any) => string) { + str = render({}); +}); +str = swigObj.compile(str)(); +str = swigObj.compile(str, opts)(); +swigObj.invalidateCache(); +swigObj.setFilter("replaceMs", replaceMs); +swigObj.setTag('tacos', function (): boolean { return true; }, function (): string { return 'Tacos' }, true, true); +swigObj.setExtension("test", function (v: string) { return 'test: ' + v }); +value = swigObj.precompile(str, opts); +str = swigObj.render(str, opts); +str = swigObj.renderFile(str, {}); +swigObj.renderFile(str, {}, function (err, output: string) { + +}); \ No newline at end of file diff --git a/swig/swig.d.ts b/swig/swig.d.ts index 4d8bc9ebe..140d287f7 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -1,27 +1,145 @@ // Type definitions for swig // Project: http://github.com/paularmstrong/swig -// Definitions by: Carlos Ballesteros Velasco +// Definitions by: Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped -// Imported from: https://github.com/soywiz/typescript-node-definitions/swig.d.ts - // API Documentation : http://paularmstrong.github.io/swig/docs/api/ declare module "swig" { - export function init(options: Options): void; - export function compileFile(filepath: string): any; - export function compile(source: string, options?: Options): any; - export function renderFile(pathName: string, locals?: any, cb?: (err: any, output: string) => void): string; + export class Swig { + constructor(options?: SwigOptions); - export interface Options { - allowErrors?: boolean; - autoescape?: boolean; - cache?: boolean; - encoding?: string; - filters?: any; - root?: string; - tags?: any; - extensions?: any; - tzOffset?: number; - } -} + setFilter( + name: string, + method: (input: any, ...args: any[]) => string + ): void; + setTag( + name: string, + parse: (str?: string, line?: string, parser?: Object, types?: TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, + compile: (compiler?: (content?: string, parents?: any, options?: any, blockName?: string) => string, args?: any[], content?: string, parents?: any, options?: any, blockName?: string) => string, + ends?: boolean, + blockLevel?: boolean + ): void; + setExtension(name: string, object: any): void; + parseFile(pathName: string, options?: any); + precompile(source: string, options?: SwigOptions): any; + compile(source: string, options?: SwigOptions): (locals?: any) => string; + compileFile(pathname: string, options: SwigOptions, cb: (err: any, compiledRender: (locals?: any) => string) => void): void; + compileFile(pathname: string, options?: SwigOptions): (locals?: any) => string; + render(source: string, options?: SwigOptions): string; + renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): void; + renderFile(pathName: string, locals?: any): string + run(templateFn: Function, locals?: any, filePath?: string): string; + invalidateCache(): void; + + loaders: typeof loaders; + } + + export interface TYPES { + /** Whitespace */ + WHITESPACE: number; + /** Plain string */ + STRING: number; + /** Variable filter */ + FILTER: number; + /** Empty variable filter */ + FILTEREMPTY: number; + /** Function */ + FUNCTION: number; + /** Function with no arguments */ + FUNCTIONEMPTY: number; + /** Open parenthesis */ + PARENOPEN: number; + /** Close parenthesis */ + PARENCLOSE: number; + /** Comma */ + COMMA: number; + /** Variable */ + VAR: number; + /** Number */ + NUMBER: number; + /** Math operator */ + OPERATOR: number; + /** Open square bracket */ + BRACKETOPEN: number; + /** Close square bracket */ + BRACKETCLOSE: number; + /** Key on an object using dot-notation */ + DOTKEY: number; + /** Start of an array */ + ARRAYOPEN: number; + /** End of an array + * Currently unused + ARRAYCLOSE: number, */ + /** Open curly brace */ + CURLYOPEN: number; + /** Close curly brace */ + CURLYCLOSE: number; + /** Colon (:) */ + COLON: number; + /** JavaScript-valid comparator */ + COMPARATOR: number; + /** Boolean logic */ + LOGIC: number; + /** Boolean logic "not" */ + NOT: number; + /** true or false */ + BOOL: number; + /** Variable assignment */ + ASSIGNMENT: number; + /** Start of a method */ + METHODOPEN: number; + /** End of a method + * Currently unused + METHODEND: 26, */ + /** Unknown type */ + UNKNOWN: number + } + + export interface SwigOptions { + autoescape?: boolean; + cache?: any; + cmtControls?: string[]; + loader?: TemplateLoader; + locals?: any; + tagControls?: string[]; + varControls?: string[]; + } + + export interface TemplateLoader { + resolve(to: string, from: string): string; + load(identifier, callback?: (err: any, data: any) => void): void; + load(identifier): any; + } + + export module loaders { + export function fs(basepath?: string, encoding?: string): TemplateLoader; + export function memory(mapping: any, basepath?: string): TemplateLoader; + } + + export var version: string; + export function setDefaults(options: SwigOptions): void; + export function setDefaultTZOffset(offset: number): void; + export function setFilter( + name: string, + method: (input: any, ...args: any[]) => string + ): void; + export function setTag( + name: string, + parse: (str?: string, line?: string, parser?: Object, types?: TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, + compile: (compiler?: (content?: string, parents?: any, options?: any, blockName?: string) => string, args?: any[], content?: string, parents?: any, options?: any, blockName?: string) => string, + ends?: boolean, + blockLevel?: boolean + ): void; + export function setExtension(name: string, object: any): void; + export function parseFile(pathName: string, options?: any); + export function precompile(source: string, options?: SwigOptions): any; + export function compile(source: string, options?: SwigOptions): (locals?: any) => string; + export function compileFile(pathname: string, options: SwigOptions, cb: (err: any, compiledRender: (locals?: any) => string) => void): void; + export function compileFile(pathname: string, options?: SwigOptions): (locals?: any) => string; + export function render(source: string, options?: SwigOptions): string; + export function renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): void; + export function renderFile(pathName: string, locals?: any): string + export function run(templateFn: Function, locals?: any, filePath?: string): string; + export function invalidateCache(): void; +} \ No newline at end of file From 25247a71c12385051f9140062a08648a77d76c72 Mon Sep 17 00:00:00 2001 From: vasyl Date: Wed, 17 Sep 2014 10:48:03 +1000 Subject: [PATCH 070/149] Add missing descriptions. Copy some annotations over from official module page. --- stampit/stampit.d.ts | 57 ++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/stampit/stampit.d.ts b/stampit/stampit.d.ts index 7cd82a6d4..8d46e7477 100644 --- a/stampit/stampit.d.ts +++ b/stampit/stampit.d.ts @@ -8,14 +8,11 @@ declare var stampit: stampit.Stampit; declare module stampit { interface Stampit { /** - * Return a factory function that will produce new objects using the + * Return a factory (akaStamp) function that will produce new objects using the * prototypes that are passed in or composed. - * @param methods Object containing methods which will be part of - * the .prototype of a resulting object. - * @param state Object which properties will be copied over to - * a resulting object. - * @param enclose Function properties of these objects will be run - * once per each new object. + * @param methods A map of method names and bodies for delegation. + * @param state A map of property names and values to clone for each new object. + * @param enclose A closure (function) used to create private data and privileged methods. * */ (methods?:{}, state?:{}, enclose?:{(...encloseArgs:any[]): void}[]):stampit.Stamp; @@ -69,12 +66,26 @@ declare module stampit { * prototypes that are passed in or composed. */ export interface Stamp { + /** + * Just like calling stamp() invokes the stamp and returns a new object instance. + * @param state Properties you wish to set on the new objects. + * @param encloseArgs The remaining arguments are passed to all .enclose() functions. + * WARNING Avoid using two different .enclose() functions that expect different arguments. + * .enclose() functions that take arguments should not be considered safe to compose + * with other .enclose() functions that also take arguments. Taking arguments with + * an .enclose() function is an anti-pattern that should be avoided, when possible. + * @return A new object composed of the Stamps and prototypes provided. + */ (state?:{}, ...encloseArgs:any[]): any; /** - * - * @param state State passed - * @param encloseArgs + * Just like calling stamp(), stamp.create() invokes the stamp and returns a new instance. + * @param state Properties you wish to set on the new objects. + * @param encloseArgs The remaining arguments are passed to all .enclose() functions. + * WARNING Avoid using two different .enclose() functions that expect different arguments. + * .enclose() functions that take arguments should not be considered safe to compose + * with other .enclose() functions that also take arguments. Taking arguments with + * an .enclose() function is an anti-pattern that should be avoided, when possible. * @return A new object composed of the Stamps and prototypes provided. */ create(state?:{}, ...encloseArgs:any[]): any; @@ -86,39 +97,43 @@ declare module stampit { /** * Add methods to the methods prototype. Chainable. - * @param methods Object(s) containing methods which will be part of - * the .prototype of a resulting object. + * @param methods Object(s) containing map of method names and bodies for delegation. * @return Self. */ methods(...methods:{}[]): Stamp; /** - * Add properties to the state prototype. Chainable. - * @param states Object(s) which properties will be copied over to - * a resulting object. + * Take n objects and add them to the state prototype. Changes `this` object. Chainable. + * @param states Object(s) containing map of property names and values to clone for each new object. * @return Self. */ state(...states:{}[]): Stamp; /** - * Add properties to the state prototype. Chainable. - * @param functions These function will be run once per each new object. + * Take n functions, an array of functions, or n objects and add the functions to the enclose prototype. + * Functions passed into .enclose() are called any time an object is instantiated. + * That happens when the stamp function is invoked, or when the .create() method is called. + * Changes `this` object. Chainable. + * @param functions Closures (functions) used to create private data and privileged methods. * @return Self. */ enclose(...functions:{(...encloseArgs:any[]): void}[]): Stamp; /** - * Add properties to the state prototype. Chainable. - * @param methods Function properties of these objects will be run - * once per each new object. + * Take n functions, an array of functions, or n objects and add the functions to the enclose prototype. + * Functions passed into .enclose() are called any time an object is instantiated. + * That happens when the stamp function is invoked, or when the .create() method is called. + * Changes `this` object. Chainable. + * @param methods Function properties of these objects will be treated as closure functions. * @return Self. */ enclose(...methods:{}[]): Stamp; /** * Take one or more Stamps and - * combine them with `this` to produce and return a new factory. + * combine them with `this` to produce and return a new Stamp. * Combining overrides properties with last-in priority. + * NOT chainable. * @param stamps Stampit factories, aka Stamps. * @return A new Stamp composed from arguments and `this`. */ From 11e519fc6e06fda5dd6ca831e8ae4f92e11ef9c3 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 17 Sep 2014 10:18:44 +0100 Subject: [PATCH 071/149] Change TYPES to now be an enum TYPES used to be an interface in the swig module. It has now been moved to a new module, swig.lexer, and set as an enum type. --- swig/swig.d.ts | 126 +++++++++++++++++++++++++------------------------ 1 file changed, 65 insertions(+), 61 deletions(-) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index 140d287f7..88136162e 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -15,7 +15,7 @@ declare module "swig" { ): void; setTag( name: string, - parse: (str?: string, line?: string, parser?: Object, types?: TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, + parse: (str?: string, line?: string, parser?: Object, types?: lexer.TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, compile: (compiler?: (content?: string, parents?: any, options?: any, blockName?: string) => string, args?: any[], content?: string, parents?: any, options?: any, blockName?: string) => string, ends?: boolean, blockLevel?: boolean @@ -35,65 +35,69 @@ declare module "swig" { loaders: typeof loaders; } - export interface TYPES { - /** Whitespace */ - WHITESPACE: number; - /** Plain string */ - STRING: number; - /** Variable filter */ - FILTER: number; - /** Empty variable filter */ - FILTEREMPTY: number; - /** Function */ - FUNCTION: number; - /** Function with no arguments */ - FUNCTIONEMPTY: number; - /** Open parenthesis */ - PARENOPEN: number; - /** Close parenthesis */ - PARENCLOSE: number; - /** Comma */ - COMMA: number; - /** Variable */ - VAR: number; - /** Number */ - NUMBER: number; - /** Math operator */ - OPERATOR: number; - /** Open square bracket */ - BRACKETOPEN: number; - /** Close square bracket */ - BRACKETCLOSE: number; - /** Key on an object using dot-notation */ - DOTKEY: number; - /** Start of an array */ - ARRAYOPEN: number; - /** End of an array - * Currently unused - ARRAYCLOSE: number, */ - /** Open curly brace */ - CURLYOPEN: number; - /** Close curly brace */ - CURLYCLOSE: number; - /** Colon (:) */ - COLON: number; - /** JavaScript-valid comparator */ - COMPARATOR: number; - /** Boolean logic */ - LOGIC: number; - /** Boolean logic "not" */ - NOT: number; - /** true or false */ - BOOL: number; - /** Variable assignment */ - ASSIGNMENT: number; - /** Start of a method */ - METHODOPEN: number; - /** End of a method - * Currently unused - METHODEND: 26, */ - /** Unknown type */ - UNKNOWN: number + export module lexer { + export enum TYPES { + /** Whitespace */ + WHITESPACE = 0, + /** Plain string */ + STRING = 1, + /** Variable filter */ + FILTER = 2, + /** Empty variable filter */ + FILTEREMPTY = 3, + /** Function */ + FUNCTION = 4, + /** Function with no arguments */ + FUNCTIONEMPTY = 5, + /** Open parenthesis */ + PARENOPEN = 6, + /** Close parenthesis */ + PARENCLOSE = 7, + /** Comma */ + COMMA = 8, + /** Variable */ + VAR = 9, + /** Number */ + NUMBER = 10, + /** Math operator */ + OPERATOR = 11, + /** Open square bracket */ + BRACKETOPEN = 12, + /** Close square bracket */ + BRACKETCLOSE = 13, + /** Key on an object using dot-notation */ + DOTKEY = 14, + /** Start of an array */ + ARRAYOPEN = 15, + /** End of an array + * Currently unused + ARRAYCLOSE = 16, */ + /** Open curly brace */ + CURLYOPEN = 17, + /** Close curly brace */ + CURLYCLOSE = 18, + /** Colon (:) */ + COLON = 19, + /** JavaScript-valid comparator */ + COMPARATOR = 20, + /** Boolean logic */ + LOGIC = 21, + /** Boolean logic "not" */ + NOT = 22, + /** true or false */ + BOOL = 23, + /** Variable assignment */ + ASSIGNMENT = 24, + /** Start of a method */ + METHODOPEN = 25, + /** End of a method + * Currently unused + METHODEND = 26, */ + /** Unknown type */ + UNKNOWN = 100 + } + + export function read(str: string): string[]; } export interface SwigOptions { @@ -126,7 +130,7 @@ declare module "swig" { ): void; export function setTag( name: string, - parse: (str?: string, line?: string, parser?: Object, types?: TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, + parse: (str?: string, line?: string, parser?: Object, types?: lexer.TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, compile: (compiler?: (content?: string, parents?: any, options?: any, blockName?: string) => string, args?: any[], content?: string, parents?: any, options?: any, blockName?: string) => string, ends?: boolean, blockLevel?: boolean From b8afdd76d784eb329d8834878402f79031609500 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 17 Sep 2014 10:57:43 +0100 Subject: [PATCH 072/149] Fix build errors Fixed the Travis CI build errors stated. --- swig/swig-tests.ts | 8 ++++---- swig/swig.d.ts | 23 ++++++++++++++++------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/swig/swig-tests.ts b/swig/swig-tests.ts index 7a6be47f8..929a67c89 100644 --- a/swig/swig-tests.ts +++ b/swig/swig-tests.ts @@ -26,7 +26,7 @@ swig.setDefaults(opts); swig.setDefaultTZOffset(num); swigObj = new swig.Swig(opts); str = swig.compileFile(str)(); -swig.compileFile(str, {}, function (err: any, render: (locals: any) => string) { +swig.compileFile(str, {}, function (err: Error, render: (locals: any) => string) { str = render({}); }); str = swig.compile(str)(); @@ -38,14 +38,14 @@ swig.setExtension("test", function (v: string) { return 'test: ' + v }); value = swig.precompile(str, opts); str = swig.render(str, opts); str = swig.renderFile(str, {}); -swig.renderFile(str, {}, function (err, output: string) { +swig.renderFile(str, {}, function (err: Error, output: string) { }); console.log(swig.version); str = swigObj.compileFile(str)(); -swigObj.compileFile(str, opts, function (err: any, render: (locals: any) => string) { +swigObj.compileFile(str, opts, function (err: Error, render: (locals: any) => string) { str = render({}); }); str = swigObj.compile(str)(); @@ -57,6 +57,6 @@ swigObj.setExtension("test", function (v: string) { return 'test: ' + v }); value = swigObj.precompile(str, opts); str = swigObj.render(str, opts); str = swigObj.renderFile(str, {}); -swigObj.renderFile(str, {}, function (err, output: string) { +swigObj.renderFile(str, {}, function (err: Error, output: string) { }); \ No newline at end of file diff --git a/swig/swig.d.ts b/swig/swig.d.ts index 88136162e..4ac885963 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -21,13 +21,13 @@ declare module "swig" { blockLevel?: boolean ): void; setExtension(name: string, object: any): void; - parseFile(pathName: string, options?: any); + parseFile(pathName: string, options?: any): parser.ParseReturn; precompile(source: string, options?: SwigOptions): any; compile(source: string, options?: SwigOptions): (locals?: any) => string; - compileFile(pathname: string, options: SwigOptions, cb: (err: any, compiledRender: (locals?: any) => string) => void): void; + compileFile(pathname: string, options: SwigOptions, cb: (err: Error, compiledRender: (locals?: any) => string) => void): void; compileFile(pathname: string, options?: SwigOptions): (locals?: any) => string; render(source: string, options?: SwigOptions): string; - renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): void; + renderFile(pathName: string, locals: any, cb: (err: Error, output: string) => void): void; renderFile(pathName: string, locals?: any): string run(templateFn: Function, locals?: any, filePath?: string): string; invalidateCache(): void; @@ -100,6 +100,15 @@ declare module "swig" { export function read(str: string): string[]; } + export module parser { + interface ParseReturn { + name: string; + parent: any; + tokens: any[]; + blocks: any; + } + } + export interface SwigOptions { autoescape?: boolean; cache?: any; @@ -112,8 +121,8 @@ declare module "swig" { export interface TemplateLoader { resolve(to: string, from: string): string; - load(identifier, callback?: (err: any, data: any) => void): void; - load(identifier): any; + load(identifier: string, callback?: (err: Error, data: any) => void): void; + load(identifier:string): any; } export module loaders { @@ -139,10 +148,10 @@ declare module "swig" { export function parseFile(pathName: string, options?: any); export function precompile(source: string, options?: SwigOptions): any; export function compile(source: string, options?: SwigOptions): (locals?: any) => string; - export function compileFile(pathname: string, options: SwigOptions, cb: (err: any, compiledRender: (locals?: any) => string) => void): void; + export function compileFile(pathname: string, options: SwigOptions, cb: (err: Error, compiledRender: (locals?: any) => string) => void): void; export function compileFile(pathname: string, options?: SwigOptions): (locals?: any) => string; export function render(source: string, options?: SwigOptions): string; - export function renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): void; + export function renderFile(pathName: string, locals: any, cb: (err: Error, output: string) => void): void; export function renderFile(pathName: string, locals?: any): string export function run(templateFn: Function, locals?: any, filePath?: string): string; export function invalidateCache(): void; From cf18b507b1e487a09a732e81382f7582f4673718 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 17 Sep 2014 11:01:49 +0100 Subject: [PATCH 073/149] Add return type to static parseFile function. --- swig/swig.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index 4ac885963..4626fb9b9 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -145,7 +145,7 @@ declare module "swig" { blockLevel?: boolean ): void; export function setExtension(name: string, object: any): void; - export function parseFile(pathName: string, options?: any); + export function parseFile(pathName: string, options?: any): parser.ParseReturn; export function precompile(source: string, options?: SwigOptions): any; export function compile(source: string, options?: SwigOptions): (locals?: any) => string; export function compileFile(pathname: string, options: SwigOptions, cb: (err: Error, compiledRender: (locals?: any) => string) => void): void; From 837677d435964108fd0b328dc7fba5aa6e45a076 Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Wed, 17 Sep 2014 23:43:10 +0200 Subject: [PATCH 074/149] Fix issue in generateSharedAccessSignature function of BlobService --- node-azure/azure.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index cb1f3b694..cb759f19e 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -317,7 +317,7 @@ declare module "azure" { /** * Retrieves a shared access signature token. */ - generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; + generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): SharedAccessSignatureResult; /** * Retrieves a blob or container URL. @@ -1726,6 +1726,18 @@ declare module "azure" { leaseBreakPeriod?: number; } + export interface SharedAccessSignatureResult { + baseUrl: string; + path: string; + queryString: { + se: string; + sp: string; + sr: string; + sv: string; + sig: string; + }; + url: () => string; + } export interface BlobHeaders { cacheControl?: string; contentType?: string; From e18d2af8b627acb9157ac110ccd42f7be93ff48a Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Thu, 18 Sep 2014 15:03:57 +0200 Subject: [PATCH 075/149] add typings for any-db --- CONTRIBUTORS.md | 1 + any-db/any-db-tests.ts | 13 ++ any-db/any-db.d.ts | 281 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 295 insertions(+) create mode 100644 any-db/any-db-tests.ts create mode 100644 any-db/any-db.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4fe6f526e..71c7472a4 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -19,6 +19,7 @@ All definitions files include a header with the author and editors, so at some p * [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) * [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) +* [any-db](https://github.com/grncdr/node-any-db) (by [Rogier Schouten](https://github.com/rogier-schouten)) * [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago)) * [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16)) * [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com)) diff --git a/any-db/any-db-tests.ts b/any-db/any-db-tests.ts new file mode 100644 index 000000000..06a0dd2b0 --- /dev/null +++ b/any-db/any-db-tests.ts @@ -0,0 +1,13 @@ + +/// + +"use strict"; + +import anyDB = require("any-db"); + +var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); +var sql: string = "SELECT * FROM questions"; +conn.query(sql).on("data", (row: Object[]): void => { +// nothing +}); +conn.end(); diff --git a/any-db/any-db.d.ts b/any-db/any-db.d.ts new file mode 100644 index 000000000..fbdd4537e --- /dev/null +++ b/any-db/any-db.d.ts @@ -0,0 +1,281 @@ +// Type definitions for any-db 2.1.0 +// Project: https://github.com/grncdr/node-any-db +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "any-db" { + import events = require("events"); + import stream = require("stream"); + + export interface ConnectOpts { + adapter: string; + } + + export interface Adapter { + name: string; + /** + * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. + * If a continuation is given, it must be called, either with an error or the established connection. + */ + createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; + + /** + * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, + * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract + * by synchronously returning a Query stream + */ + createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; + createQuery(query: Query): Query; + } + /** + * Other properties are driver specific + */ + export interface Field { + name: string; + } + + /** + * ResultSet objects are just plain data that collect results of a query when a continuation + * is provided to Queryable.query. The lastInsertId is optional, and currently supported by + * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. + */ + export interface ResultSet { + fields: Field[]; + rows: Object[]; + rowCount: number; + lastInsertId?: any; + } + + /** + * Query objects are returned by the Queryable.query method, available on connections, + * pools, and transactions. Queries are instances of Readable, and as such can be piped + * through transforms and support backpressure for more efficient memory-usage on very + * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) + * + * Internally, Query instances are created by a database Adapter and may have more methods, + * properties, and events than are described here. Consult the documentation for your + * specific adapter to find out about any extensions. + * + * Events: + * + * Error event + * The 'error' event is emitted at most once per query. Note that this event will be + * emitted for errors even if a callback was provided, the callback will + * simply be subscribed to the 'error' event. + * One argument is passed to event listeners: + * error - the error object. + * + * Fields event + * A 'fields' event is emmitted before any 'data' events. + * One argument is passed to event listeners: + * fields - an array of [Field][ResultSet] objects. + * + * The following events are part of the stream.Readable interface which is implemented by Query: + * + * Data event + * A 'data' event is emitted for each row in the query result set. + * One argument is passed to event listeners: + * row contains the contents of a single row in the query result + * + * Close event + * A 'close' event is emitted when the query completes. + * No arguments are passed to event listeners. + * + * End event + * An 'end' event is emitted after all query results have been consumed. + * No arguments are passed to event listeners. + */ + export interface Query extends stream.Readable { + /** + * The SQL query as a string. If you are using MySQL this will contain + * interpolated values after the query has been enqueued by a connection. + */ + text: string; + + /** + * The array of parameter values. + */ + values: any[]; + + /** + * The callback (if any) that was provided to Queryable.query. Note that + * Query objects must not use a closed over reference to their callback, + * as other any-db libraries may rely on modifying the callback property + * of a Query they did not create. + */ + callback: (error: Error, results: ResultSet) => void; + } + + /** + * Events: + * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: + * - query: a Query object + */ + export interface Queryable extends events.EventEmitter { + /** + * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. + */ + adapter: Adapter; + + /** + * Execute a SQL statement using bound parameters (if they are provided) and return a Query object + * that is a Readable stream of the resulting rows. If a Continuation is provided the rows + * returned by the database will be aggregated into a [ResultSet][] which will be passed to the + * continuation after the query has completed. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query + + /** + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + query(query: Query): Query; + } + + /** + * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, + * both of which delegate to the createConnection implementation of the specified adapter. + * While all Connection objects implement the Queryable interface, the implementations in + * each adapter may add additional methods or emit additional events. If you need to access a + * feature of your database that is not described here (such as Postgres' server-side prepared + * statements), consult the documentation for your adapter. + * + * Events: + * Error event + * The 'error' event is emitted when there is a connection-level error. + * No arguments are passed to event listeners. + * + * Open event + * The 'open' event is emitted when the connection has been established and is ready to query. + * No arguments are passed to event listeners. + * + * Close event + * The 'close' event is emitted when the connection has been closed. + * No arguments are passed to event listeners. + */ + export interface Connection extends Queryable { + /** + * Close the database connection. If a continuation is provided it + * will be called after the connection has closed. + */ + end(callback?: (error: Error) => void): void; + } + + export interface ConnectionStatic { + new(): Connection; + + name: string; + createConnection(): void; + createPool(): void; + } + + /** + * ConnectionPool events + * 'acquire' - emitted whenever pool.acquire is called + * 'release' - emitted whenever pool.release is called + * 'query', query - emitted immediately after .query is called on a + * connection via pool.query. The argument is a Query object. + * 'close' - emitted when the connection pool has closed all of it + * connections after a call to close(). + */ + export interface ConnectionPool extends events.EventEmitter { + /** + * The string name of the adapter used for this connection pool, e.g. 'sqlite3'. + */ + adapter: string; + + /** + * Implements Queryable.query by automatically acquiring a connection + * and releasing it when the query completes. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; + + /** + * Remove a connection from the pool. If you use this method you must + * return the connection back to the pool using ConnectionPool.release + */ + acquire(callback: (error: Error, result: Connection) => void): void; + + /** + * Return a connection to the pool. This should only be called with connections + * you've manually acquired. You must not continue to use the connection after releasing it. + */ + release(connection: Connection): void; + + /** + * Stop giving out new connections, and close all existing database connections as they + * are returned to the pool. + */ + close(callback?: (error: Error) => void): void; + } + + /** + * A PoolConfig is generally a plain object with any of the following properties (they are all optional): + */ + export interface PoolConfig { + /** + * min (default 0) The minimum number of connections to keep open in the pool. + */ + min?: number; + /** + * max (default 10) The maximum number of connections to keep open in the pool. + * When this limit is reached further requests for connections will queue waiting + * for an existing connection to be released back into the pool. + */ + max?: number; + /** + * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped + */ + idleTimeout?: number; + /** + * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. + */ + reapInterval?: number; + /** + * (default true) When this is true, the pool will reap connections that + * have been idle for more than idleTimeout milliseconds. + */ + refreshIdle?: boolean; + /** + * Called immediately after a connection is first established. Use this to do one-time setup of new connections. + * The supplied Connection will not be added to the pool until you pass it to the done continuation. + */ + onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; + /** + * Called each time a connection is returned to the pool. Use this to restore a connection to + * it's original state (e.g. rollback transactions, set the database session vars). If reset + * fails to call the done continuation the connection will be lost in limbo. + */ + reset?: (connection: Connection, done: (error: Error) => void) => void; + /** + * (default function (err) { return true }) - Called when an error is encountered + * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) + * is truthy the connection will be destroyed, otherwise it will be reset. + */ + shouldDestroyConnection?: (error: Error) => boolean; + } + + /** + * Create a database connection. + * @param url String of the form adapter://user:password@host/database + * @param callback + * @returns Connection object. + */ + export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; + + /** + * Create a database connection. + * @param opts Object with adapter name and any properties that the given adapter requires + * @param callback + * @returns Connection object. + */ + export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; + + + export function createPool(url: string, config: PoolConfig): ConnectionPool; + +} From 665516c3952c75146628826a42d666ea845c3f64 Mon Sep 17 00:00:00 2001 From: tigerswithguitars Date: Thu, 18 Sep 2014 17:58:18 +0100 Subject: [PATCH 076/149] Add the pattern class to the fabric js typeings. --- fabricjs/fabricjs.d.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index d532b1c56..9903d9065 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -607,6 +607,21 @@ declare module fabric { loadFromDatalessJSON(json, callback: () => void): void; } + export interface IPattern { + (options: IPatternOptions): IPattern; + + initialise(options: IPatternOptions): IPattern; + + toLive(ctx: CanvasRenderingContext2D): IPattern; + toObject(): any; + toSVG(): string; + + offsetX: number; + offsetY: number; + repeat: string; + source: any; + } + export interface IBrightnessFilter { } export interface IInvertFilter { @@ -658,6 +673,13 @@ declare module fabric { stateful?: boolean; } + export interface IPatternOptions { + source: () => any; + offsetX: number; + offsetY: number; + repeat: string; + } + export interface IRectOptions extends IObjectOptions { x?: number; y?: number; @@ -697,6 +719,12 @@ declare module fabric { prototype: any; } + var Pattern: { + new (options: IPatternOptions): IPattern; + + prototype: any; + } + var Circle: { ATTRIBUTE_NAMES: string[]; fromElement(element: SVGElement, options: ICircleOptions): ICircle; From 6a93336c48e7865227429ffe150d000c28e628b3 Mon Sep 17 00:00:00 2001 From: tigerswithguitars Date: Thu, 18 Sep 2014 18:04:46 +0100 Subject: [PATCH 077/149] typo for the source, should be any, not function --- fabricjs/fabricjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 9903d9065..81397ea4a 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -674,7 +674,7 @@ declare module fabric { } export interface IPatternOptions { - source: () => any; + source: any; offsetX: number; offsetY: number; repeat: string; From 61c97db6af0fc7c842c64aa72ead7b57234dd9fe Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 18 Sep 2014 20:52:55 +0100 Subject: [PATCH 078/149] Add node-ip type definitions Add node-ip type definitions file with a test script. --- node-ip/ip-tests.ts | 19 ++++++++++ node-ip/ip.d.ts | 89 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 node-ip/ip-tests.ts create mode 100644 node-ip/ip.d.ts diff --git a/node-ip/ip-tests.ts b/node-ip/ip-tests.ts new file mode 100644 index 000000000..0975361b5 --- /dev/null +++ b/node-ip/ip-tests.ts @@ -0,0 +1,19 @@ +/// + +import ip = require('ip'); + +var myIP = ip.address(); + +ip.cidr("192.168.0.1/24"); +ip.fromLong(ip.toLong(myIP)); +ip.fromPrefixLen(24); +ip.isEqual("192.168.0.1", myIP); +ip.isLoopback("127.0.0.1"); +ip.isPrivate(myIP); +ip.isPublic(myIP); +ip.loopback("ipv6"); +ip.mask("192.168.0.1", "255.255.255.0"); +ip.not("255.255.255.0"); +ip.or("192.168.0.1", "255.255.255.0"); +var buff = ip.toBuffer(myIP); +ip.toString(buff); \ No newline at end of file diff --git a/node-ip/ip.d.ts b/node-ip/ip.d.ts new file mode 100644 index 000000000..82c2755d7 --- /dev/null +++ b/node-ip/ip.d.ts @@ -0,0 +1,89 @@ +// Type definitions for node-ip +// Project: https://github.com/indutny/node-ip +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "ip" { + /** + * Check two IP address are the same. + **/ + export function isEqual(ip1: string, ip2: string): boolean; + + /** + * Convert an IP string into a buffer. + **/ + export function toBuffer(ip: string, buffer?: number, offset?: number): NodeBuffer; + + /** + * Convert an IP buffer into a string. + **/ + export function toString(ip: NodeBuffer, offset?: number, length?: number): string; + + /** + * Get the subnet mask from a CIDR prefix length. + * + * @param family The IP family is infered from the prefixLength, but can be explicity specified as either "ipv4" or "ipv6". + **/ + export function fromPrefixLen(prefixLength: number, family?:string): string; + + /** + * Get the network ID IP address from an IP address and its subnet mask. + **/ + export function mask(ip: string, mask: string): string; + + /** + * Get the network ID IP address from an IP address in CIDR notation. + **/ + export function cidr(cidr: string): string; + + /** + * Get the bitwise inverse (NOT every octet) of an IP address or subnet mask. + **/ + export function not(ip: string): string; + + /** + * Get the bitwise OR of two IP addresses (usually an IP address and a subnet mask). + **/ + export function or(ip: string, mask:string): string; + + /** + * Check whether an IP is within a private IP address range. + **/ + export function isPrivate(ip: string): boolean; + + /** + * Check whether an IP is within a public IP address range. + **/ + export function isPublic(ip: string): boolean; + + /** + * Check whether an IP is a loopback address. + **/ + export function isLoopback(ip: string): boolean; + + /** + * Get the loopback address for an IP family. + * + * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". + **/ + export function loopback(family?: string): string; + + /** + * Get the address for the network interface on the current system with the specified 'name'. + * If no interface name is specified, the first IPv4 address or loopback address is returned. + * + * @param name The name can be any named interface, or 'public' or 'private'. + * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". + **/ + export function address(name?: string, family?: string):string; + + /** + * Convert a string IPv4 IP address to the equivalent long numeric value. + **/ + export function toLong(ip: string): number; + + /** + * Convert an IPv4 IP address from its the long numeric value to a string. + **/ + export function fromLong(ip: number): string; +} \ No newline at end of file From 203d7a8d33c9ff9a42a61065888587394efee0a8 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 18 Sep 2014 21:10:55 +0100 Subject: [PATCH 079/149] Add empty NodeBuffer interface The empty NodeBuffer interface acts as a placeholder if node's type definitions file isn't referenced. This is to hopefully stop the Travis CI build error. --- node-ip/ip-tests.ts | 2 +- node-ip/ip.d.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/node-ip/ip-tests.ts b/node-ip/ip-tests.ts index 0975361b5..b852e08e7 100644 --- a/node-ip/ip-tests.ts +++ b/node-ip/ip-tests.ts @@ -15,5 +15,5 @@ ip.loopback("ipv6"); ip.mask("192.168.0.1", "255.255.255.0"); ip.not("255.255.255.0"); ip.or("192.168.0.1", "255.255.255.0"); -var buff = ip.toBuffer(myIP); +var buff:any = ip.toBuffer(myIP); ip.toString(buff); \ No newline at end of file diff --git a/node-ip/ip.d.ts b/node-ip/ip.d.ts index 82c2755d7..2fe3201c7 100644 --- a/node-ip/ip.d.ts +++ b/node-ip/ip.d.ts @@ -3,6 +3,8 @@ // Definitions by: Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped +interface NodeBuffer { } + declare module "ip" { /** * Check two IP address are the same. From f5c7418b9da3707b4149c93a57eaf1721c7fc660 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 18 Sep 2014 22:26:10 +0100 Subject: [PATCH 080/149] Add node-radius definitions and tests More info about node library: https://github.com/retailnext/node-radius --- node-radius/radius-tests.ts | 43 +++++++++++++++ node-radius/radius.d.ts | 106 ++++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 node-radius/radius-tests.ts create mode 100644 node-radius/radius.d.ts diff --git a/node-radius/radius-tests.ts b/node-radius/radius-tests.ts new file mode 100644 index 000000000..5d06d2fcb --- /dev/null +++ b/node-radius/radius-tests.ts @@ -0,0 +1,43 @@ +/// + +import radius = require('radius'); + +var radius_secret: string = "shhhh" + +radius.add_dictionary("./"); +var encodedPacket: NodeBuffer = radius.encode({ + code: "Access-Request", + secret: radius_secret, + attributes: { + "NAS-IP-Address": "10.5.5.5", + "User-Name": "me", + "User-Password": "its-a-secret" + } +}); + +var radiusPacket: radius.RadiusPacket = radius.decode({ + packet: encodedPacket, + secret: radius_secret +}); + +var response: NodeBuffer; + +if (radiusPacket.attributes["User-Name"] == "me" && radiusPacket.attributes["User-Password"] == "its-a-secret") { + response = radius.encode_response({ + packet: radiusPacket, + code: "Access-Accept", + secret: radius_secret + }); +} else { + response = radius.encode_response({ + packet: radiusPacket, + code: "Access-Reject", + secret: radius_secret + }); +} + +console.log(radius.verify_response({ + request: encodedPacket, + response: response, + secret: radius_secret +})); \ No newline at end of file diff --git a/node-radius/radius.d.ts b/node-radius/radius.d.ts new file mode 100644 index 000000000..cb6be029d --- /dev/null +++ b/node-radius/radius.d.ts @@ -0,0 +1,106 @@ +// Type definitions for node-radius +// Project: https://github.com/retailnext/node-radius +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface NodeBuffer { } + +declare module "radius" { + /** + * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. + **/ + export function decode(args: DecodeArgsWithSecret): RadiusPacket; + + /** + * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. + **/ + export function decode_without_secret(args: DecodeArgs): RadiusPacket; + + /** + * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. + **/ + export function encode(args: EncodeArgs): NodeBuffer; + + /** + * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. + **/ + export function encode_response(args: EncodeResponseArgs): NodeBuffer; + + /** + * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. + **/ + export function verify_response(args: VerifyResponseArgs):boolean; + + /** + * {@link https://github.com/retailnext/node-radius#radiusadd_dictionarypath} for more info. + * + * @param path Can be either a path to a file or a directory. + **/ + export function add_dictionary(path:string); + + export function unload_dictionaries(); + + + + + + + /** + * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. + **/ + interface DecodeArgs { + packet: NodeBuffer; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. + **/ + interface DecodeArgsWithSecret extends DecodeArgs { + secret: string; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. + **/ + interface EncodeArgs { + code: string; + secret: string; + identifier?: number; + /** + * This can be an object: { attribute_name: attribute_value, ... }, + * an array within an array: [ [ attribute_name, attribute_value ], ... ], + * or if you haven't loaded a dictionary for the attributes: [ [ attribute_id, Buffer ], ... ]. + * + * Tag field-attributes can be specified like so: [ [ attribute_name, tag_number, attribute_value ] ... ] + **/ + attributes?: any; + add_message_authenticator?: boolean; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. + **/ + interface EncodeResponseArgs { + packet: RadiusPacket; + code: string; + secret: string; + attributes?: any; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. + **/ + interface VerifyResponseArgs { + request: NodeBuffer; + response: NodeBuffer; + secret: string; + } + + interface RadiusPacket { + code: string; + identifier: number; + length: number; + attributes: any; + raw_attributes: Array> + } +} \ No newline at end of file From cf069224122a02f7aaaed616f9322d9856cb103a Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 18 Sep 2014 22:30:48 +0100 Subject: [PATCH 081/149] Add return types to all functions --- node-radius/radius.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/node-radius/radius.d.ts b/node-radius/radius.d.ts index cb6be029d..b1079fafd 100644 --- a/node-radius/radius.d.ts +++ b/node-radius/radius.d.ts @@ -36,9 +36,9 @@ declare module "radius" { * * @param path Can be either a path to a file or a directory. **/ - export function add_dictionary(path:string); + export function add_dictionary(path:string): void; - export function unload_dictionaries(); + export function unload_dictionaries(): void; From 0a8f9e6df426d3cd601229c67ec14cfbc676ab92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Rudge?= Date: Thu, 18 Sep 2014 23:36:53 -0300 Subject: [PATCH 082/149] add reload arguments to pjax reload --- jquery.pjax/jquery.pjax.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery.pjax/jquery.pjax.d.ts b/jquery.pjax/jquery.pjax.d.ts index 621d87d21..48e48bcac 100644 --- a/jquery.pjax/jquery.pjax.d.ts +++ b/jquery.pjax/jquery.pjax.d.ts @@ -131,7 +131,7 @@ interface PjaxStatic { /** * Reload current page with pjax. */ - reload(): JQueryXHR; + reload(container: string, options?: PjaxSettings): JQueryXHR; } interface JQuerySupport { From b342292528fb5a075b1e22a53bb3d609ea3c314d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Rudge?= Date: Thu, 18 Sep 2014 23:38:33 -0300 Subject: [PATCH 083/149] add reload arguments to pjax reload --- jquery.pjax/jquery.pjax-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery.pjax/jquery.pjax-tests.ts b/jquery.pjax/jquery.pjax-tests.ts index 214bb3922..7b08ca6c4 100644 --- a/jquery.pjax/jquery.pjax-tests.ts +++ b/jquery.pjax/jquery.pjax-tests.ts @@ -39,7 +39,7 @@ function test_disable() { } function test_reload() { - $.pjax.reload(); + $.pjax.reload("#pjax-container"); } function test_defauluts() { From 8d9ab7d6b3af2773319a7ac867fdf6e729b22293 Mon Sep 17 00:00:00 2001 From: Jeremy Hull Date: Fri, 19 Sep 2014 00:12:44 -0700 Subject: [PATCH 084/149] Take out top from IAutoHighlightResult --- highlightjs/highlightjs.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index 91675cfa6..dc7606d88 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -57,19 +57,23 @@ declare module "highlight.js" export var TITLE_MODE : IMode; export var UNDERSCORE_TITLE_MODE : IMode; - export interface IHighlightResult + export interface IHighlightResultBase { relevance: number; language: string; - top: ICompiledMode; value: string; } - export interface IAutoHighlightResult extends IHighlightResult + export interface IAutoHighlightResult extends IHighlightResultBase { second_best?: IAutoHighlightResult; } + export interface IHighlightResult extends IHighlightResultBase + { + top: ICompiledMode; + } + export interface HLJSStatic { inherit(parent: Object, obj: Object): Object; From 2063e5067d34aaec850c317d626fdab93f2abd72 Mon Sep 17 00:00:00 2001 From: Sergio Date: Fri, 19 Sep 2014 10:01:01 +0200 Subject: [PATCH 085/149] Added textInput binding handler From here: http://knockoutjs.com/documentation/textinput-binding.html --- knockout/knockout.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 27487c7a6..5784112f8 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -161,6 +161,7 @@ interface KnockoutBindingHandlers { enable: KnockoutBindingHandler; disable: KnockoutBindingHandler; value: KnockoutBindingHandler; + textInput: KnockoutBindingHandler; hasfocus: KnockoutBindingHandler; checked: KnockoutBindingHandler; options: KnockoutBindingHandler; From 3b611ce056f73d5e02e33f23a499878e54e78df9 Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Fri, 19 Sep 2014 15:38:04 +0200 Subject: [PATCH 086/149] Update angular-translate.d.ts Update defintions to match Angular Translate v2.3.0 --- angular-translate/angular-translate.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 4b8da8449..7aa71c577 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate (pascalprecht.translate module) +// Type definitions for Angular Translate v2.3.0 (pascalprecht.translate module) // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -42,7 +42,7 @@ declare module ng.translate { instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; - preferredLanguage(): string; + preferredLanguage(langKey?: string): string; proposedLanguage(): string; refresh(langKey?: string): ng.IPromise; storage(): IStorage; @@ -61,14 +61,14 @@ declare module ng.translate { useMessageFormatInterpolation(): ITranslateProvider; useInterpolation(factory: string): ITranslateProvider; useSanitizeValueStrategy(value: string): ITranslateProvider; - preferredLanguage(): string; + preferredLanguage(): ITranslateProvider; preferredLanguage(language: string): ITranslateProvider; translationNotFoundIndicator(indicator: string): ITranslateProvider; translationNotFoundIndicatorLeft(): string; translationNotFoundIndicatorLeft(indicator: string): ITranslateProvider; translationNotFoundIndicatorRight(): string; translationNotFoundIndicatorRight(indicator: string): ITranslateProvider; - fallbackLanguage(): string; + fallbackLanguage(): ITranslateProvider; fallbackLanguage(language: string): ITranslateProvider; fallbackLanguage(languages: string[]): ITranslateProvider; use(): string; From 3e107a29425482e019d9d716de0177d165a6d1b9 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Sat, 20 Sep 2014 03:58:09 +0900 Subject: [PATCH 087/149] Added appendTo overload --- zepto/zepto.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/zepto/zepto.d.ts b/zepto/zepto.d.ts index 04f11289e..d85072a66 100644 --- a/zepto/zepto.d.ts +++ b/zepto/zepto.d.ts @@ -493,6 +493,11 @@ interface ZeptoCollection { **/ appendTo(target: HTMLElement[]): ZeptoCollection; + /** + * @see ZeptoCollection.appendTo + **/ + appendTo(target: ZeptoCollection): ZeptoCollection; + /** * Read or set DOM attributes. When no value is given, reads specified attribute from the first element in the collection. When value is given, sets the attribute to that value on each element in the collection. When value is null, the attribute is removed (like with removeAttr). Multiple attributes can be set by passing an object with name-value pairs. * To read DOM properties such as checked or selected, use prop. From 96236f954d484300e4fcfc0b5668eae9d43775b3 Mon Sep 17 00:00:00 2001 From: AdaskoTheBeAsT Date: Sat, 20 Sep 2014 15:11:12 +0200 Subject: [PATCH 088/149] Knockstrap definition file added Knockstrap definition file added --- CONTRIBUTORS.md | 1 + knockstrap/knockstrap-tests.ts | 43 +++++++++ knockstrap/knockstrap.d.ts | 163 +++++++++++++++++++++++++++++++++ 3 files changed, 207 insertions(+) create mode 100644 knockstrap/knockstrap-tests.ts create mode 100644 knockstrap/knockstrap.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4fe6f526e..40554b6d3 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -230,6 +230,7 @@ All definitions files include a header with the author and editors, so at some p * [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek)) * [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig)) * [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising)) +* [Knockstrap](http://faulknercs.github.io/Knockstrap/) (by [Adam Pluciński](https://github.com/adaskothebeast)) * [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising)) * [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov)) * [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds)) diff --git a/knockstrap/knockstrap-tests.ts b/knockstrap/knockstrap-tests.ts new file mode 100644 index 000000000..233ce6f4d --- /dev/null +++ b/knockstrap/knockstrap-tests.ts @@ -0,0 +1,43 @@ +/// +/// +/// +/// + + +// test unique id +var adaskoUnitqueId: string = ko.utils.uniqueId('adaskothebeast'); + +class Sample { + public property1: KnockoutObservable; + + constructor() { + this.property1 = ko.observable('test'); + } +} + +var sample = new Sample(); + +// test unwrap properties +var unwrappedProperties = ko.utils.unwrapProperties(sample); + +var kts: KnockoutTemplateSources; +var stringTemplate = kts.stringTemplate('string-template'); +var stname = stringTemplate.templateName; + +ko.stringTemplateEngine.instance.allowTemplateRewriting = true; + +var templateSource = ko.stringTemplateEngine.instance.makeTemplateSource('template'); +ko.stringTemplateEngine.instance.addTemplate('test', {}); +ko.stringTemplateEngine.instance.removeTemplate('test'); +ko.stringTemplateEngine.instance.isTemplateExist('test'); + + +var alertbh = ko.bindingHandlers.alert; +var carouselbh = ko.bindingHandlers.carousel; +var checkboxbh = ko.bindingHandlers.checkbox; +var modalbh = ko.bindingHandlers.modal; +var popoverbh = ko.bindingHandlers.popover; +var progressbh = ko.bindingHandlers.progress; +var radiobh = ko.bindingHandlers.radio; +var togglebh = ko.bindingHandlers.toggle; +var tooltipbh = ko.bindingHandlers.tooltip; \ No newline at end of file diff --git a/knockstrap/knockstrap.d.ts b/knockstrap/knockstrap.d.ts new file mode 100644 index 000000000..a1f9791da --- /dev/null +++ b/knockstrap/knockstrap.d.ts @@ -0,0 +1,163 @@ +// Type definitions for Knockstrap +// Project: http://faulknercs.github.io/Knockstrap/ +// Definitions by: Adam Pluciński +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +interface KnockoutUtils { + uniqueId(prefix: string): string; + unwrapProperties(wrappedProperies: any): any; +} + +interface KnockoutTemplateSources { + stringTemplate: { + prototype: KnockstrapStringTemplate; + new (template: string): KnockstrapStringTemplate; + }; +} + +interface KnockstrapStringTemplate extends KnockoutTemplateSourcesDomElement { + templateName: string; +} + +interface KnockoutStatic { + stringTemplateEngine: { + prototype: KnockstrapStringTemplateEngine; + new (): KnockstrapStringTemplateEngine; + instance: KnockstrapStringTemplateEngine; + } +} + +interface KnockstrapStringTemplateEngine extends KnockoutNativeTemplateEngine { + allowTemplateRewriting: boolean; + makeTemplateSource(template: string): KnockstrapStringTemplate; + addTemplate(name: string, template: any): void; + removeTemplate(name: string): void; + isTemplateExist(name: string): boolean; + getTemplate(name: string): any; +} + +interface KnockoutBindingHandlers { + alert: AlertKnockoutBindingHandler; + carousel: CarouselKnockoutBindingHandler; + checkbox: KnockoutBindingHandler; + modal: ModalKnockoutBindingHandler; + popover: PopoverKnockoutBindingHandler; + progress: ProgressKnockoutBindingHandler; + radio: KnockoutBindingHandler; + toggle: KnockoutBindingHandler; + tooltip: KnockoutBindingHandler; +} + +interface KnockoutControlsDescendantBindings { + controlsDescendantBindings: boolean; +} + +interface AlertKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; +} + +interface CarouselKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; + defaults: KnockstrapCarouselDefaults; +} + +interface KnockstrapCarouselDefaults { + css: string; + controlsTemplate: KnockstrapCarouselDefaultsControlsTemplate; + indicatorsTemplate: KnockstrapCarouselDefaultsIndicatorsTemplate; + itemTemplate: KnockstrapCarouselDefaultsItemTemplate; +} + +interface KnockstrapDefaultsTemplateBase { + name: string; + templateEngine: KnockstrapStringTemplateEngine; +} + +interface KnockstrapCarouselDefaultsControlsTemplate extends KnockstrapDefaultsTemplateBase { + dataConverter(value: any): KnockstrapCarouselDefaultsIdDataConverted; + +} + +interface KnockstrapCarouselDefaultsIdDataConverted { + id: KnockoutComputed; +} + +interface KnockstrapCarouselDefaultsIndicatorsTemplate extends KnockstrapDefaultsTemplateBase { + dataConverter(value: any): KnockstrapCarouselDefaultsIdItemsDataConverted; +} + +interface KnockstrapCarouselDefaultsIdItemsDataConverted extends KnockstrapCarouselDefaultsIdDataConverted { + items: any; +} + +interface KnockstrapCarouselDefaultsItemTemplate extends KnockstrapDefaultsTemplateBase { + converter(value: any): any; +} + +interface ModalKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; + defaults: KnockstrapModalDefaults; +} + +interface KnockstrapModalDefaults { + css: string; + attributes: KnockstrapModalDefaultsAttributes; + headerTemplate: KnockstrapDefaultsTemplateBase; + bodyTemplate: KnockstrapDefaultsTemplateBase; + footerTemplate: KnockstrapModalDefaultsFooterTemplate; +} + +interface KnockstrapModalDefaultsAttributes { + role: string; +} + +interface KnockstrapModalDefaultsFooterTemplate extends KnockstrapDefaultsTemplateBase { + data: KnockstrapModalDefaultsFooterData; +} + +interface KnockstrapModalDefaultsFooterData { + closeLabel: string; + primaryLabel: string; +} + +interface PopoverKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; +} + +interface ProgressKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; + defaults: KnockstrapProgressDefaults; +} + +interface KnockstrapProgressDefaults { + css: string; + text: string; + textHidden: boolean; + striped: boolean; + type: string; + animated: boolean; +} \ No newline at end of file From 67d3e3547f2b3ebd4b683d78b7670e018a09ab4d Mon Sep 17 00:00:00 2001 From: Shinnosuke Watanabe Date: Mon, 22 Sep 2014 12:58:36 +0900 Subject: [PATCH 089/149] Add definitions for FastClick https://github.com/ftlabs/fastclick --- CONTRIBUTORS.md | 3 ++- fastclick/fastclick-tests.ts | 22 ++++++++++++++++++ fastclick/fastclick.d.ts | 44 ++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 fastclick/fastclick-tests.ts create mode 100644 fastclick/fastclick.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4fe6f526e..5f71104bc 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,4 +1,4 @@ -# Contributors +# Contributors This is a non-exhaustive list of definitions and their creators. If you created a definition but are not listed then feel free to send a pull request on this file with your name and url. @@ -85,6 +85,7 @@ All definitions files include a header with the author and editors, so at some p * [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428)) * [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/)) * [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov)) +* [FastClick](https://github.com/ftlabs/fastclick) (by [Shinnosuke Watanabe](https://github.com/shinnn)) * [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/)) * [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/)) * [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/)) diff --git a/fastclick/fastclick-tests.ts b/fastclick/fastclick-tests.ts new file mode 100644 index 000000000..0e31846ab --- /dev/null +++ b/fastclick/fastclick-tests.ts @@ -0,0 +1,22 @@ +/// + +// on browser +new FastClick(document.body); +new FastClick(document.getElementById('foo'), {tapDelay: 50}); +new FastClick(document.getElementsByTagName('p')[0], {touchBoundary: 50}); +var fc = FastClick.attach(document.body); +fc.determineEventType(document.getElementsByClassName('foo')).concat('bar'); +fc.findControl(document.querySelector('label')); +fc.focus(document.querySelectorAll('section')[0]); +document.body.addEventListener('click', function(e) { + fc.getTargetElementFromEventTarget(e.target); + fc.needsClick(e.target); + fc.needsFocus(e.target); +}); + +// on CommonJS environment +import fastclick = require('fastclick'); +fastclick(document.body); +new fastclick.FastClick(document.links[0]); +new fastclick.FastClick(document.links[1], {tapDelay: 50}); +new fastclick.FastClick(document.links[2], {touchBoundary: 50}); diff --git a/fastclick/fastclick.d.ts b/fastclick/fastclick.d.ts new file mode 100644 index 000000000..e90c3ac2e --- /dev/null +++ b/fastclick/fastclick.d.ts @@ -0,0 +1,44 @@ +// Type definitions for FastClick v1.0.3 +// Project: https://github.com/ftlabs/fastclick +// Definitions by: Shinnosuke Watanabe +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface FastClickObject { + lastTouchIdentifier: number; + layer: Element; + tapDelay: number; + targetElement: any; + touchBoundary: number; + touchStartX: number; + touchStartY: number; + trackingClick: boolean; + trackingClickStart: number; + destroy(): void; + determineEventType(targetElement: any): string; + findControl(labelElement: any /* EventTarget | HTMLLabelElement */): any; + focus(targetElement: any /* EventTarget | Element */): void; + getTargetElementFromEventTarget(eventTarget: EventTarget): any; + needsClick(target: any /* EventTarget | Element */): boolean; + needsFocus(target: any /* EventTarget | Element */): boolean; +} + +interface FastClickOptions { + touchBoundary?: number; + tapDelay?: number; +} + +interface FastClickStatic { + new(layer: any, options?: FastClickOptions): FastClickObject; + attach(layer: any, options?: FastClickOptions): FastClickObject; +} + +declare module "fastclick" { + function fastclick(layer: any, options?: FastClickOptions): FastClickObject; + module fastclick { + var FastClick: FastClickStatic; + } + + export = fastclick; +} + +declare var FastClick: FastClickStatic; From edcc9824cc9b497c093a8d52e4ffba80796129e5 Mon Sep 17 00:00:00 2001 From: progre Date: Mon, 22 Sep 2014 21:02:16 +0900 Subject: [PATCH 090/149] fix: return values --- gulp/gulp.d.ts | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 908fc4c27..d8b1a6e65 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -3,6 +3,8 @@ // Definitions by: Drew Noakes // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module gulp { /** @@ -193,7 +195,7 @@ declare module gulp { * @param name the name of the task. Tasks that you want to run from the command line should not have spaces in them. * @param fn the function that performs the task's operations. Generally this takes the form of gulp.src().pipe(someplugin()). */ - task(name:string, fn:ITaskCallback): Gulp; + task(name:string, fn:ITaskCallback): any; /** * Define a task. @@ -202,7 +204,7 @@ declare module gulp { * @param dep an array of tasks to be executed and completed before your task will run. * @param fn the function that performs the task's operations. Generally this takes the form of gulp.src().pipe(someplugin()). */ - task(name:string, dep:string[], fn?:ITaskCallback): Gulp; + task(name:string, dep:string[], fn?:ITaskCallback): any; /** @@ -210,14 +212,14 @@ declare module gulp { * @param glob a glob string, using node-glob syntax * @param opt an optional option object */ - src(glob:string, opt?:ISrcOptions): Gulp; + src(glob:string, opt?:ISrcOptions): NodeJS.ReadWriteStream; /** * Takes a glob and represents a file structure. Can be piped to plugins. * @param glob an array of glob strings, using node-glob syntax * @param opt an optional option object */ - src(glob:string[], opt?:ISrcOptions): Gulp; + src(glob:string[], opt?:ISrcOptions): NodeJS.ReadWriteStream; /** @@ -227,7 +229,7 @@ declare module gulp { * @param outFolder the path (output folder) to write files to. * @param opt */ - dest(outFolder:string, opt?:IDestOptions): Gulp; + dest(outFolder:string, opt?:IDestOptions): NodeJS.ReadWriteStream; /** * Can be piped to and it will write files. Re-emits all data passed to it so you can pipe to multiple folders. @@ -236,15 +238,7 @@ declare module gulp { * @param outFolder a function that converts a vinyl File instance into an output path * @param opt */ - dest(outFolder:(file:string)=>string, opt?:IDestOptions): Gulp; - - - /** - * Forwards the current Gulp instance, along with its contained files, to the specified receiver. - * - * @param receiver the receiver - */ - pipe(receiver:any): Gulp; + dest(outFolder:(file:string)=>string, opt?:IDestOptions): NodeJS.ReadWriteStream; /** From 81ff395285ed26afeea689958e7f054ab6288569 Mon Sep 17 00:00:00 2001 From: progre Date: Mon, 22 Sep 2014 21:47:57 +0900 Subject: [PATCH 091/149] fix: watch() can abbreviate opt --- gulp/gulp.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index d8b1a6e65..d12c3edc1 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -241,6 +241,15 @@ declare module gulp { dest(outFolder:(file:string)=>string, opt?:IDestOptions): NodeJS.ReadWriteStream; + /** + * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. + * + * @param glob a single glob or array of globs that indicate which files to watch for changes. + * @param tasks names of task(s) to run when a file changes, added with gulp.task() + */ + watch(glob:string, tasks:string[]): EventEmitter; + watch(glob:string[], tasks:string[]): EventEmitter; + /** * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. * From 021326f9376a1f154ffb5064fd4a120b89846a31 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Mon, 22 Sep 2014 17:49:42 +0200 Subject: [PATCH 092/149] add typings for any-db-transaction and adjust any-db --- CONTRIBUTORS.md | 1 + .../any-db-transaction-tests.ts | 29 ++++ any-db-transaction/any-db-transaction.d.ts | 93 ++++++++++ any-db/any-db-tests.ts | 25 +++ any-db/any-db.d.ts | 164 ++++++++++-------- 5 files changed, 241 insertions(+), 71 deletions(-) create mode 100644 any-db-transaction/any-db-transaction-tests.ts create mode 100644 any-db-transaction/any-db-transaction.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 71c7472a4..3ea68d240 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -20,6 +20,7 @@ All definitions files include a header with the author and editors, so at some p * [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) * [any-db](https://github.com/grncdr/node-any-db) (by [Rogier Schouten](https://github.com/rogier-schouten)) +* [any-db-transaction](https://github.com/grncdr/node-any-db-transaction) (by [Rogier Schouten](https://github.com/rogier-schouten)) * [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago)) * [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16)) * [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com)) diff --git a/any-db-transaction/any-db-transaction-tests.ts b/any-db-transaction/any-db-transaction-tests.ts new file mode 100644 index 000000000..55ca53bdc --- /dev/null +++ b/any-db-transaction/any-db-transaction-tests.ts @@ -0,0 +1,29 @@ + +/// +/// + +"use strict"; + +import anyDB = require("any-db"); +import begin = require("any-db-transaction"); + +var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); + + +var transaction = begin(conn); +var transaction2 = begin(transaction); + +begin(conn, { autoRollback: true }); +begin(conn, (error: Error, result: begin.Transaction): void => { +}); + +transaction.query("SELECT * FROM MyTable"); + +transaction.commit(); +transaction.commit((error: Error): void => { +}); + +transaction.rollback(); +transaction.rollback((error: Error): void => { +}); + diff --git a/any-db-transaction/any-db-transaction.d.ts b/any-db-transaction/any-db-transaction.d.ts new file mode 100644 index 000000000..7f65e959d --- /dev/null +++ b/any-db-transaction/any-db-transaction.d.ts @@ -0,0 +1,93 @@ +// Type definitions for any-db-transaction 2.2.1 +// Project: https://github.com/grncdr/node-any-db-transaction +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "any-db-transaction" { + import anyDB = require("any-db"); + + module begin { + /** + * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, + * but guarantee that all queries take place within a single database transaction or not at all. Note that + * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you + * can simply pass a pool to it: var tx = begin(pool) + * + * By default, any queries that error during a transaction will cause an automatic rollback. If a query has + * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. + * This enables handling errors for an entire transaction in a single place. + * + * Transactions may also be nested by passing a Transaction to begin and these nested transactions can + * safely error and rollback without rolling back their parent transaction + * + * Transaction events: + * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. + * 'commit:start' - Emitted when .commit() is called. + * 'commit:complete' - Emitted after the transaction has committed. + * 'rollback:start' - Emitted when .rollback() is called. + * 'rollback:complete' - Emitted after the transaction has rolled back. + * 'close' - Emitted after rollback or commit completes. + * 'error', err - Emitted under three conditions: + * There was an error acquiring a connection. + * Any query performed in this transaction emits an error that would otherwise go unhandled. + * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. + * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. + */ + interface Transaction extends anyDB.Queryable { + + /** + * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. + * If a continuation is provided it will be called (possibly with an error) after the COMMIT + * statement completes. The transaction object itself will be unusable after calling commit(). + */ + commit(callback?: (error: Error) => void): void; + + /** + * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. + */ + rollback(callback?: (error: Error) => void): void; + } + + interface TransactionOptions { + /** + * Adapter name e.g. 'mysql' + */ + adapter?: anyDB.Adapter; + /** + * SQL statement for beginning a transaction, default 'BEGIN' + */ + begin?: string; + /** + * SQL statement for committing a transaction, default 'COMMIT' + */ + commit?: string; + /** + * SQL statement for rolling back a transaction, default 'ROLLBACK' + */ + rollback?: string; + /** + * Callback for transaction + */ + callback?: (error: Error, transaction: Transaction) => void; + /** + * Rollback automatically on error, default true + */ + autoRollback?: boolean; + } + } + + /** + * Start a transaction + */ + function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + + export = begin; +} + + + diff --git a/any-db/any-db-tests.ts b/any-db/any-db-tests.ts index 06a0dd2b0..15dc6c7e6 100644 --- a/any-db/any-db-tests.ts +++ b/any-db/any-db-tests.ts @@ -7,7 +7,32 @@ import anyDB = require("any-db"); var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); var sql: string = "SELECT * FROM questions"; + +conn.query(sql, [1, "boo"]); + conn.query(sql).on("data", (row: Object[]): void => { // nothing }); + +conn.query(sql, [1, "s"], (error: Error, result: anyDB.ResultSet): void => { + result.rows.length; + result.fields.length; +}); + conn.end(); + + +var poolConfig: anyDB.PoolConfig = { + min: 1, + max: 200 +}; + +var pool: anyDB.ConnectionPool = anyDB.createPool("mysql://user:password@localhost/testdb", poolConfig); + +pool.query(sql).on("data", (row: Object[]): void => { +// nothing +}); + +pool.close((error: Error): void => { +}); + diff --git a/any-db/any-db.d.ts b/any-db/any-db.d.ts index fbdd4537e..04817623a 100644 --- a/any-db/any-db.d.ts +++ b/any-db/any-db.d.ts @@ -7,12 +7,12 @@ declare module "any-db" { import events = require("events"); - import stream = require("stream"); + import stream = require("stream"); export interface ConnectOpts { adapter: string; } - + export interface Adapter { name: string; /** @@ -20,10 +20,10 @@ declare module "any-db" { * If a continuation is given, it must be called, either with an error or the established connection. */ createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; - + /** - * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, - * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract + * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, + * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract * by synchronously returning a Query stream */ createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; @@ -33,36 +33,62 @@ declare module "any-db" { * Other properties are driver specific */ export interface Field { - name: string; + name: string; } /** * ResultSet objects are just plain data that collect results of a query when a continuation - * is provided to Queryable.query. The lastInsertId is optional, and currently supported by + * is provided to Queryable.query. The lastInsertId is optional, and currently supported by * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. */ export interface ResultSet { - fields: Field[]; - rows: Object[]; + /** + * Affected rows. Note e.g. for INSERT queries the rows property is not filled even + * though rowCount is non-zero. + */ rowCount: number; + /** + * Result rows + */ + rows: Object[]; + /** + * Result field descriptions + */ + fields: Field[]; + + /** + * Not supported by all drivers. + */ + fieldCount?: number; + /** + * Not supported by all drivers. + */ lastInsertId?: any; + /** + * Not supported by all drivers. + */ + affectedRows?: number; + /** + * Not supported by all drivers. + */ + changedRows?: number; } /** - * Query objects are returned by the Queryable.query method, available on connections, - * pools, and transactions. Queries are instances of Readable, and as such can be piped - * through transforms and support backpressure for more efficient memory-usage on very + * Query objects are returned by the Queryable.query method, available on connections, + * pools, and transactions. Queries are instances of Readable, and as such can be piped + * through transforms and support backpressure for more efficient memory-usage on very * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) * - * Internally, Query instances are created by a database Adapter and may have more methods, - * properties, and events than are described here. Consult the documentation for your + * Internally, Query instances are created by a database Adapter and may have more methods, + * properties, and events than are described here. Consult the documentation for your * specific adapter to find out about any extensions. * * Events: * * Error event - * The 'error' event is emitted at most once per query. Note that this event will be - * emitted for errors even if a callback was provided, the callback will + * The 'error' event is emitted at most once per query. Note that this event will be + * emitted for errors even if a callback was provided, the callback will * simply be subscribed to the 'error' event. * One argument is passed to event listeners: * error - the error object. @@ -89,25 +115,25 @@ declare module "any-db" { */ export interface Query extends stream.Readable { /** - * The SQL query as a string. If you are using MySQL this will contain + * The SQL query as a string. If you are using MySQL this will contain * interpolated values after the query has been enqueued by a connection. */ text: string; - + /** * The array of parameter values. */ values: any[]; - + /** - * The callback (if any) that was provided to Queryable.query. Note that - * Query objects must not use a closed over reference to their callback, - * as other any-db libraries may rely on modifying the callback property + * The callback (if any) that was provided to Queryable.query. Note that + * Query objects must not use a closed over reference to their callback, + * as other any-db libraries may rely on modifying the callback property * of a Query they did not create. */ callback: (error: Error, results: ResultSet) => void; } - + /** * Events: * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: @@ -118,30 +144,30 @@ declare module "any-db" { * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. */ adapter: Adapter; - + /** - * Execute a SQL statement using bound parameters (if they are provided) and return a Query object - * that is a Readable stream of the resulting rows. If a Continuation is provided the rows - * returned by the database will be aggregated into a [ResultSet][] which will be passed to the + * Execute a SQL statement using bound parameters (if they are provided) and return a Query object + * that is a Readable stream of the resulting rows. If a Continuation is provided the rows + * returned by the database will be aggregated into a [ResultSet][] which will be passed to the * continuation after the query has completed. - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. */ query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query - + /** - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. */ - query(query: Query): Query; + // query(query: Query): Query; } - + /** - * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, + * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, * both of which delegate to the createConnection implementation of the specified adapter. - * While all Connection objects implement the Queryable interface, the implementations in - * each adapter may add additional methods or emit additional events. If you need to access a - * feature of your database that is not described here (such as Postgres' server-side prepared + * While all Connection objects implement the Queryable interface, the implementations in + * each adapter may add additional methods or emit additional events. If you need to access a + * feature of your database that is not described here (such as Postgres' server-side prepared * statements), consult the documentation for your adapter. * * Events: @@ -155,64 +181,59 @@ declare module "any-db" { * * Close event * The 'close' event is emitted when the connection has been closed. - * No arguments are passed to event listeners. + * No arguments are passed to event listeners. */ - export interface Connection extends Queryable { + export interface Connection extends Queryable { /** - * Close the database connection. If a continuation is provided it + * Close the database connection. If a continuation is provided it * will be called after the connection has closed. */ end(callback?: (error: Error) => void): void; } - + export interface ConnectionStatic { new(): Connection; - + name: string; createConnection(): void; createPool(): void; } - + /** * ConnectionPool events * 'acquire' - emitted whenever pool.acquire is called * 'release' - emitted whenever pool.release is called * 'query', query - emitted immediately after .query is called on a * connection via pool.query. The argument is a Query object. - * 'close' - emitted when the connection pool has closed all of it + * 'close' - emitted when the connection pool has closed all of it * connections after a call to close(). */ - export interface ConnectionPool extends events.EventEmitter { + export interface ConnectionPool extends Queryable { /** - * The string name of the adapter used for this connection pool, e.g. 'sqlite3'. - */ - adapter: string; - - /** - * Implements Queryable.query by automatically acquiring a connection + * Implements Queryable.query by automatically acquiring a connection * and releasing it when the query completes. */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; - + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; + /** * Remove a connection from the pool. If you use this method you must * return the connection back to the pool using ConnectionPool.release */ acquire(callback: (error: Error, result: Connection) => void): void; - + /** - * Return a connection to the pool. This should only be called with connections + * Return a connection to the pool. This should only be called with connections * you've manually acquired. You must not continue to use the connection after releasing it. */ release(connection: Connection): void; - + /** - * Stop giving out new connections, and close all existing database connections as they + * Stop giving out new connections, and close all existing database connections as they * are returned to the pool. */ close(callback?: (error: Error) => void): void; } - + /** * A PoolConfig is generally a plain object with any of the following properties (they are all optional): */ @@ -222,8 +243,8 @@ declare module "any-db" { */ min?: number; /** - * max (default 10) The maximum number of connections to keep open in the pool. - * When this limit is reached further requests for connections will queue waiting + * max (default 10) The maximum number of connections to keep open in the pool. + * When this limit is reached further requests for connections will queue waiting * for an existing connection to be released back into the pool. */ max?: number; @@ -236,7 +257,7 @@ declare module "any-db" { */ reapInterval?: number; /** - * (default true) When this is true, the pool will reap connections that + * (default true) When this is true, the pool will reap connections that * have been idle for more than idleTimeout milliseconds. */ refreshIdle?: boolean; @@ -246,19 +267,19 @@ declare module "any-db" { */ onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; /** - * Called each time a connection is returned to the pool. Use this to restore a connection to - * it's original state (e.g. rollback transactions, set the database session vars). If reset + * Called each time a connection is returned to the pool. Use this to restore a connection to + * it's original state (e.g. rollback transactions, set the database session vars). If reset * fails to call the done continuation the connection will be lost in limbo. */ reset?: (connection: Connection, done: (error: Error) => void) => void; /** - * (default function (err) { return true }) - Called when an error is encountered - * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) + * (default function (err) { return true }) - Called when an error is encountered + * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) * is truthy the connection will be destroyed, otherwise it will be reset. */ shouldDestroyConnection?: (error: Error) => boolean; } - + /** * Create a database connection. * @param url String of the form adapter://user:password@host/database @@ -266,7 +287,7 @@ declare module "any-db" { * @returns Connection object. */ export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; - + /** * Create a database connection. * @param opts Object with adapter name and any properties that the given adapter requires @@ -274,8 +295,9 @@ declare module "any-db" { * @returns Connection object. */ export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; - - + + export function createPool(url: string, config: PoolConfig): ConnectionPool; - + export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; + } From 6160116b2f893282157bcbd248402f85718b8cf0 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Mon, 22 Sep 2014 17:57:21 +0200 Subject: [PATCH 093/149] build fix --- any-db-transaction/any-db-transaction.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/any-db-transaction/any-db-transaction.d.ts b/any-db-transaction/any-db-transaction.d.ts index 7f65e959d..ca5bc84b0 100644 --- a/any-db-transaction/any-db-transaction.d.ts +++ b/any-db-transaction/any-db-transaction.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// declare module "any-db-transaction" { import anyDB = require("any-db"); From b4571c30c2c1402cffab00f2db0420c69408f1d0 Mon Sep 17 00:00:00 2001 From: Simon Lovely Date: Mon, 22 Sep 2014 18:08:22 +0100 Subject: [PATCH 094/149] Updated "google.maps.geometry.poly" to static The 'poly' class should be static (as already correctly marked on the 'spherical' class). --- googlemaps/google.maps.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 27275f098..cf51d84c1 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1263,8 +1263,8 @@ declare module google.maps { } export class poly { - containsLocation(point: LatLng, polygon: Polygon): boolean; - isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): boolean; + static containsLocation(point: LatLng, polygon: Polygon): boolean; + static isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): boolean; } } From 6b7838e07984d419e3bc9acfed3bd77c68f4004d Mon Sep 17 00:00:00 2001 From: Georgie Date: Mon, 22 Sep 2014 22:01:28 -0700 Subject: [PATCH 095/149] Small fixes --- google.visualization/google.visualization.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 2657d8274..eb2d49469 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -14,8 +14,8 @@ declare module google { export interface ChartSpecs { chartType: string; - containerId: string; - oprtions?: Object; + containerId?: string; + options?: Object; dataTable?: Object; dataSourceUrl?: string; query?: string; @@ -75,7 +75,7 @@ declare module google { addRows(rows: DataObjectCell[][]): number; addRows(rows: any[][]): number; clone(): DataTable; - getColumnId(columnIndex: number): String; + getColumnId(columnIndex: number): string; getColumnLabel(columnIndex: number): string; getColumnPattern(columnIndex: number): string; getColumnProperties(columnIndex: number): Properties; @@ -438,15 +438,15 @@ declare module google { groupWidth: any; // number | string } - export interface VisualizationSelectionArray { + export interface SelectedCell { column?: number; row?: number; } class ChartBase { constructor(element: Element); - getSelection(): any[]; - setSelection(selection: any[]): void; + getSelection(): SelectedCell[]; + setSelection(selection: SelectedCell[]): void; clearChart(): void; getImageURI(): string; } From 950ec44efb68d56595cb82a0f491fbd1fc1ecf88 Mon Sep 17 00:00:00 2001 From: Georgie Date: Mon, 22 Sep 2014 22:01:28 -0700 Subject: [PATCH 096/149] Small fixes --- google.visualization/google.visualization.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 2657d8274..eb2d49469 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -14,8 +14,8 @@ declare module google { export interface ChartSpecs { chartType: string; - containerId: string; - oprtions?: Object; + containerId?: string; + options?: Object; dataTable?: Object; dataSourceUrl?: string; query?: string; @@ -75,7 +75,7 @@ declare module google { addRows(rows: DataObjectCell[][]): number; addRows(rows: any[][]): number; clone(): DataTable; - getColumnId(columnIndex: number): String; + getColumnId(columnIndex: number): string; getColumnLabel(columnIndex: number): string; getColumnPattern(columnIndex: number): string; getColumnProperties(columnIndex: number): Properties; @@ -438,15 +438,15 @@ declare module google { groupWidth: any; // number | string } - export interface VisualizationSelectionArray { + export interface SelectedCell { column?: number; row?: number; } class ChartBase { constructor(element: Element); - getSelection(): any[]; - setSelection(selection: any[]): void; + getSelection(): SelectedCell[]; + setSelection(selection: SelectedCell[]): void; clearChart(): void; getImageURI(): string; } From e75c7945e3a9aaed4cc4cee0d098fbe1fd3fa55c Mon Sep 17 00:00:00 2001 From: Mark Bell Date: Tue, 23 Sep 2014 06:28:25 +0100 Subject: [PATCH 097/149] Add definitions for mustache.js 0.8.2 Add new definitions for 0.8.2, move 0.7 definitions and tests into versioned files and remove empty .tscparams files. --- mustache/mustache-0.7.0-tests.ts | 11 ++++++ mustache/mustache-0.7.0.d.ts | 54 ++++++++++++++++++++++++++++ mustache/mustache-tests.ts | 17 +++++---- mustache/mustache-tests.ts.tscparams | 1 - mustache/mustache.d.ts | 17 ++++----- mustache/mustache.d.ts.tscparams | 1 - 6 files changed, 81 insertions(+), 20 deletions(-) create mode 100644 mustache/mustache-0.7.0-tests.ts create mode 100644 mustache/mustache-0.7.0.d.ts delete mode 100644 mustache/mustache-tests.ts.tscparams delete mode 100644 mustache/mustache.d.ts.tscparams diff --git a/mustache/mustache-0.7.0-tests.ts b/mustache/mustache-0.7.0-tests.ts new file mode 100644 index 000000000..0f39985ef --- /dev/null +++ b/mustache/mustache-0.7.0-tests.ts @@ -0,0 +1,11 @@ +/// + +var view = { title: "Joe", calc: function () { return 2 + 4; } }; +var output = Mustache.render("{{title}} spends {{calc}}", view); + +var person; +var template = "

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; +var html = Mustache.to_html(template, person); + +var writer = Mustache.compile(template); +var writerOutput = writer(view); diff --git a/mustache/mustache-0.7.0.d.ts b/mustache/mustache-0.7.0.d.ts new file mode 100644 index 000000000..9921231bc --- /dev/null +++ b/mustache/mustache-0.7.0.d.ts @@ -0,0 +1,54 @@ +// Type definitions for Mustache 0.7 +// Project: https://github.com/janl/mustache.js +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface MustacheScanner { + string: string; + tail: string; + pos: number; + + eos(): boolean; + scan(re: RegExp): string; + scanUntil(re: RegExp): string; +} + +interface MustacheContext { + view; + parent; + + clearCache(); + push(view): MustacheContext; + lookup(name: string): any; +} + +interface MustacheWriter { + (view: any): string; + clearCache(); + compile(template: string, tags); + compilePartial(name, template, tags); + compileTokens(tokens, template); + render(template, view, partials); +} + +interface MustacheStatic { + name: string; + version: string; + tags: string; + Scanner: MustacheScanner; + Context: MustacheContext; + Writer: MustacheWriter; + escape; + + parse(template: string, tags); + clearCache(): MustacheWriter; + compile(template: string): MustacheWriter; + compile(template: string, tags): MustacheWriter; + compilePartial(name: string, template: string, tags): MustacheWriter; + compileTokens(tokens, template: string): MustacheWriter; + render(template: string, view: any, partials?: any): string; + to_html(template: string, view: any, partials?: any, send?): string; +} + +declare var Mustache: MustacheStatic; diff --git a/mustache/mustache-tests.ts b/mustache/mustache-tests.ts index 9b42131ef..5265dec0a 100644 --- a/mustache/mustache-tests.ts +++ b/mustache/mustache-tests.ts @@ -1,11 +1,14 @@ /// -var view = { title: "Joe", calc: function () { return 2 + 4; } }; -var output = Mustache.render("{{title}} spends {{calc}}", view); +var view1 = { title: "Joe", calc: function () { return 2 + 4; } }; +var template1 = "{{title}} spends {{calc}}"; +var output = Mustache.render(template1, view1); -var person; -var template = "

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; -var html = Mustache.to_html(template, person); +var view2 = { forename: "Jane", calc: function () { return 10 + 5; } }; +var template2 = "{{forename}} spends {{calc}}"; +Mustache.parse(template2, null); +var output2 = Mustache.render(template2, view2); -var writer = Mustache.compile(template); -var writerOutput = writer(view); +var view3 = { firstName: "John", lastName: "Smith", blogURL: "http://testblog.com" }; +var template3 = "

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; +var html = Mustache.to_html(template3, view3); diff --git a/mustache/mustache-tests.ts.tscparams b/mustache/mustache-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/mustache/mustache-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/mustache/mustache.d.ts b/mustache/mustache.d.ts index 9cd5e6f69..6737a7dd9 100644 --- a/mustache/mustache.d.ts +++ b/mustache/mustache.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Mustache 0.7 +// Type definitions for Mustache 0.8.2 // Project: https://github.com/janl/mustache.js -// Definitions by: Boris Yankov +// Definitions by: Mark Ashley Bell // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -18,18 +18,17 @@ interface MustacheContext { view; parent; - clearCache(); push(view): MustacheContext; lookup(name: string): any; } interface MustacheWriter { (view: any): string; + clearCache(); - compile(template: string, tags); - compilePartial(name, template, tags); - compileTokens(tokens, template); + parse(template: string, tags?: any); render(template, view, partials); + renderTokens(tokens, context, partials, originalTemplate); } interface MustacheStatic { @@ -41,12 +40,8 @@ interface MustacheStatic { Writer: MustacheWriter; escape; - parse(template: string, tags); clearCache(): MustacheWriter; - compile(template: string): MustacheWriter; - compile(template: string, tags): MustacheWriter; - compilePartial(name: string, template: string, tags): MustacheWriter; - compileTokens(tokens, template: string): MustacheWriter; + parse(template: string, tags?: any); render(template: string, view: any, partials?: any): string; to_html(template: string, view: any, partials?: any, send?): string; } diff --git a/mustache/mustache.d.ts.tscparams b/mustache/mustache.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/mustache/mustache.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - From 0778e9dec5954ce5e15982607dde8f5f711bd237 Mon Sep 17 00:00:00 2001 From: Mark Bell Date: Tue, 23 Sep 2014 07:17:08 +0100 Subject: [PATCH 098/149] Add parameter typing, fix old definition version I was omitting the -noImplicitAny flag when testing; interestingly, even the old (0.7.3) definitions failed the Travis CI tests... --- ...0.7.0-tests.ts => mustache-0.7.3-tests.ts} | 4 +-- ...ustache-0.7.0.d.ts => mustache-0.7.3.d.ts} | 33 ++++++++++--------- mustache/mustache.d.ts | 20 +++++------ 3 files changed, 29 insertions(+), 28 deletions(-) rename mustache/{mustache-0.7.0-tests.ts => mustache-0.7.3-tests.ts} (71%) rename mustache/{mustache-0.7.0.d.ts => mustache-0.7.3.d.ts} (52%) diff --git a/mustache/mustache-0.7.0-tests.ts b/mustache/mustache-0.7.3-tests.ts similarity index 71% rename from mustache/mustache-0.7.0-tests.ts rename to mustache/mustache-0.7.3-tests.ts index 0f39985ef..f95913cc7 100644 --- a/mustache/mustache-0.7.0-tests.ts +++ b/mustache/mustache-0.7.3-tests.ts @@ -1,9 +1,9 @@ -/// +/// var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view); -var person; +var person = { firstName: "John", lastName: "Smith", blogURL: "http://testblog.com" }; var template = "

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; var html = Mustache.to_html(template, person); diff --git a/mustache/mustache-0.7.0.d.ts b/mustache/mustache-0.7.3.d.ts similarity index 52% rename from mustache/mustache-0.7.0.d.ts rename to mustache/mustache-0.7.3.d.ts index 9921231bc..ac40de0a0 100644 --- a/mustache/mustache-0.7.0.d.ts +++ b/mustache/mustache-0.7.3.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mustache 0.7 +// Type definitions for Mustache 0.7.3 // Project: https://github.com/janl/mustache.js // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -15,21 +15,22 @@ interface MustacheScanner { } interface MustacheContext { - view; - parent; + view: any; + parent: MustacheContext; - clearCache(); - push(view): MustacheContext; + clearCache(): void; + push(view: any): MustacheContext; lookup(name: string): any; } interface MustacheWriter { (view: any): string; - clearCache(); - compile(template: string, tags); - compilePartial(name, template, tags); - compileTokens(tokens, template); - render(template, view, partials); + + clearCache(): void; + compile(template: string, tags: any): any; + compilePartial(name: string, template: string, tags: any): any; + compileTokens(tokens: string[], template: string): any; + render(template: string, view: any, partials: any): any; } interface MustacheStatic { @@ -39,16 +40,16 @@ interface MustacheStatic { Scanner: MustacheScanner; Context: MustacheContext; Writer: MustacheWriter; - escape; + escape: any; - parse(template: string, tags); + parse(template: string, tags: any): any; clearCache(): MustacheWriter; compile(template: string): MustacheWriter; - compile(template: string, tags): MustacheWriter; - compilePartial(name: string, template: string, tags): MustacheWriter; - compileTokens(tokens, template: string): MustacheWriter; + compile(template: string, tags: any): MustacheWriter; + compilePartial(name: string, template: string, tags: any): MustacheWriter; + compileTokens(tokens: string[], template: string): MustacheWriter; render(template: string, view: any, partials?: any): string; - to_html(template: string, view: any, partials?: any, send?): string; + to_html(template: string, view: any, partials?: any, send?: any): string; } declare var Mustache: MustacheStatic; diff --git a/mustache/mustache.d.ts b/mustache/mustache.d.ts index 6737a7dd9..3f0a83dfa 100644 --- a/mustache/mustache.d.ts +++ b/mustache/mustache.d.ts @@ -15,20 +15,20 @@ interface MustacheScanner { } interface MustacheContext { - view; - parent; + view: any; + parentContext: MustacheContext; - push(view): MustacheContext; + push(view: any): MustacheContext; lookup(name: string): any; } interface MustacheWriter { (view: any): string; - clearCache(); - parse(template: string, tags?: any); - render(template, view, partials); - renderTokens(tokens, context, partials, originalTemplate); + clearCache(): void; + parse(template: string, tags?: any): any; + render(template: string, view: any, partials: any): string; + renderTokens(tokens: string[], context: MustacheContext, partials: any, originalTemplate: any): string; } interface MustacheStatic { @@ -38,12 +38,12 @@ interface MustacheStatic { Scanner: MustacheScanner; Context: MustacheContext; Writer: MustacheWriter; - escape; + escape: any; clearCache(): MustacheWriter; - parse(template: string, tags?: any); + parse(template: string, tags?: any): any; render(template: string, view: any, partials?: any): string; - to_html(template: string, view: any, partials?: any, send?): string; + to_html(template: string, view: any, partials?: any, send?: any): any; } declare var Mustache: MustacheStatic; From a41df0ac5598a1b41656813900b75e2ac38d8124 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 23 Sep 2014 08:29:45 +0200 Subject: [PATCH 099/149] selenium-webdriver: Added selenium testing & executors modules --- selenium-webdriver/selenium-webdriver.d.ts | 74 +++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 9ce5321de..a4d1017aa 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3150,4 +3150,76 @@ declare module webdriver { declare module 'selenium-webdriver' { export = webdriver; -} \ No newline at end of file +} + +declare module 'selenium-webdriver/testing' { + + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/executors' { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. + */ + function createExecutor(url: any): webdriver.CommandExecutor; +} From 9be7aba21273f764a7aa406fdb47e99f0708de70 Mon Sep 17 00:00:00 2001 From: Steve <_steve_@outlook.com> Date: Tue, 23 Sep 2014 09:43:01 +0200 Subject: [PATCH 100/149] request.d.ts: fixing RequestAPI.Options.form type --- request/request-tests.ts | 2 +- request/request.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/request/request-tests.ts b/request/request-tests.ts index 986702c27..506205db8 100644 --- a/request/request-tests.ts +++ b/request/request-tests.ts @@ -69,7 +69,7 @@ var options: request.Options = { }, jar: value, - form: value, + form: obj, oauth: value, aws: aws, qs: obj, diff --git a/request/request.d.ts b/request/request.d.ts index fc03a7e19..d8d058d1d 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -61,7 +61,7 @@ declare module 'request' { uri?: string; callback?: (error: any, response: any, body: any) => void; jar?: any; // CookieJar - form?: FormData; + form?: any; // Object or string oauth?: OAuthOptions; aws?: AWSOptions; hawk ?: HawkOptions; From b5528071bb7ccec16f72b06ef40013e4e62cc3c9 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 23 Sep 2014 14:50:50 +0100 Subject: [PATCH 101/149] Created basic angular-file-upload typings Not perfect I suspect but a starting point. --- CONTRIBUTORS.md | 1 + .../angular-file-upload-tests.ts | 47 +++++++++++++++++++ angular-file-upload/angular-file-upload.d.ts | 26 ++++++++++ 3 files changed, 74 insertions(+) create mode 100644 angular-file-upload/angular-file-upload-tests.ts create mode 100644 angular-file-upload/angular-file-upload.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4fe6f526e..815d84b27 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -13,6 +13,7 @@ All definitions files include a header with the author and editors, so at some p * [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [angular-file-upload](https://github.com/danialfarid/angular-file-upload) (by [John Reilly](https://github.com/johnnyreilly)) * [angular-spinner](https://github.com/urish/angular-spinner) (by [Marcin Biegała](https://github.com/Biegal)) * [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27)) diff --git a/angular-file-upload/angular-file-upload-tests.ts b/angular-file-upload/angular-file-upload-tests.ts new file mode 100644 index 000000000..d59e65b4e --- /dev/null +++ b/angular-file-upload/angular-file-upload-tests.ts @@ -0,0 +1,47 @@ +/// + +module controllers { + + "use strict"; + + var controllerId = "upload"; + + class Upload { + + static $inject = ["$upload"]; + constructor( + private $upload: ng.angularFileUpload.IUploadService + ) { + } + + onFileSelect($files: File[]) { + //$files: an array of files selected, each file has name, size, and type. + var uploads: ng.IPromise[] = []; + for (var i = 0; i < $files.length; i++) { + var file = $files[i]; + uploads.push(this.$upload.upload({ + url: "/api/upload", + method: "POST", + data: { + extraData: { + fileName: file.name, test: "anything" + } + }, + file: file + }) + .progress((evt: any) => { + console.log('progress'); + }) + .then(success => { + // file is uploaded successfully + console.log(success.data); + }) + .catch(err => { + console.error(err); + })); + } + } + } + + angular.module("app").controller(controllerId, Upload); +} diff --git a/angular-file-upload/angular-file-upload.d.ts b/angular-file-upload/angular-file-upload.d.ts new file mode 100644 index 000000000..9c3542888 --- /dev/null +++ b/angular-file-upload/angular-file-upload.d.ts @@ -0,0 +1,26 @@ +// Type definitions for Angular File Upload 1.6.7 +// Project: https://github.com/danialfarid/angular-file-upload +// Definitions by: John Reilly +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ng.angularFileUpload { + + interface IUploadService { + + http(config: IFileUploadConfig): IUploadPromise; + upload(config: IFileUploadConfig): IUploadPromise; + } + + interface IUploadPromise extends IHttpPromise { + + progress(callback: IHttpPromiseCallback): IUploadPromise; + } + + interface IFileUploadConfig extends ng.IRequestConfig { + + file: File; + fileName?: string; + } +} \ No newline at end of file From 83188776d90639bcaaf787629ddc2152e611f905 Mon Sep 17 00:00:00 2001 From: Adi Dahiya Date: Tue, 23 Sep 2014 18:43:38 -0400 Subject: [PATCH 102/149] Add pickadate.js typings --- pickadate/pickadate-tests.ts | 241 +++++++++++++++++++++++++++ pickadate/pickadate.d.ts | 314 +++++++++++++++++++++++++++++++++++ 2 files changed, 555 insertions(+) create mode 100644 pickadate/pickadate-tests.ts create mode 100644 pickadate/pickadate.d.ts diff --git a/pickadate/pickadate-tests.ts b/pickadate/pickadate-tests.ts new file mode 100644 index 000000000..6b3e9fccb --- /dev/null +++ b/pickadate/pickadate-tests.ts @@ -0,0 +1,241 @@ +/// +/// + +function testApiMethods(api: PickadateApi) { + api.clear(); + api.close(); + api.close(true); + api.get('value'); + api.get('value', 'yyyy-mm-dd'); + api.off('open'); + api.off('open', 'close', 'render'); + api.on('set', (context: {[key: string]: any}) => { }); + api.on('get', () => { }); + api.open(); + api.open(true); + api.render(); + api.render(true); + api.set('value', '2014-09-23'); + api.set({ + value: '2014-09-23', + max: new Date(2014, 12, 1) + }); + api.start(); + api.stop(); + api.trigger('open'); + + var pickerInputElement = api.$node; + pickerInputElement.show(); + + var pickerRootElement = api.$root; + pickerRootElement.show(); +} + +var datePickerInput = $("input.date"); + +datePickerInput.pickadate(); + +datePickerInput.pickadate({ + monthsFull: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + weekdaysFull: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + showMonthsShort: true, + showWeekdaysFull: true, + + today: 'Today', + clear: 'Clear', + close: 'Close', + + labelMonthNext: 'Next month', + labelMonthPrev: 'Previous month', + labelMonthSelect: 'Select a month', + labelYearSelect: 'Select a year', + + // Formats + format: 'd mmmm, yyyy', + formatSubmit: 'yyyy-mm-dd', + hiddenPrefix: 'foo', + hiddenSuffix: '_submit', + hiddenName: 'bar', + + // Editable input + editable: true, + + // Dropdown selectors + selectYears: true, + selectMonths: 10, + + // First day of the week + firstDay: 0, + + // Date limits + min: new Date(2013, 3, 20), + max: [2013, 7, 14], + + // Disable dates + disable: [ new Date(2013, 3, 21) ], + + // Root container + container: '.root-container', + + // Events + onStart: () => { }, + onRender: () => { }, + onOpen: () => { }, + onClose: () => { }, + onSet: (context: {[key: string]: any}) => { }, + onStop: () => { } +}); + +datePickerInput.pickadate({ + klass: { + // The element states + input: 'picker__input', + active: 'picker__input--active', + + // The root picker and states * + picker: 'picker', + opened: 'picker--opened', + focused: 'picker--focused', + + // The picker holder + holder: 'picker__holder', + + // The picker frame, wrapper, and box + frame: 'picker__frame', + wrap: 'picker__wrap', + box: 'picker__box', + + // The picker header + header: 'picker__header', + + // Month navigation + navPrev: 'picker__nav--prev', + navNext: 'picker__nav--next', + navDisabled: 'picker__nav--disabled', + + // Month & year labels + month: 'picker__month', + year: 'picker__year', + + // Month & year dropdowns + selectMonth: 'picker__select--month', + selectYear: 'picker__select--year', + + // Table of dates + table: 'picker__table', + + // Weekday labels + weekdays: 'picker__weekday', + + // Day states + day: 'picker__day', + disabled: 'picker__day--disabled', + selected: 'picker__day--selected', + highlighted: 'picker__day--highlighted', + now: 'picker__day--today', + infocus: 'picker__day--infocus', + outfocus: 'picker__day--outfocus', + + // The picker footer + footer: 'picker__footer', + + // Today, clear, & close buttons + buttonClear: 'picker__button--clear', + buttonClose: 'picker__button--close', + buttonToday: 'picker__button--today' + } +}); + +var datePickerApi = datePickerInput.pickadate('picker'); + +datePickerInput.pickadate('open'); +datePickerInput.pickadate('get', 'value'); + +testApiMethods(datePickerApi); + +// ==================================================================================================================== + +var timePickerInput = $("input.time"); + +timePickerInput.pickatime(); + +timePickerInput.pickatime({ + // Translations and clear button + clear: 'Clear', + + // Formats + format: 'h:i A', + formatLabel: 'h:i a', + formatSubmit: 'HH:i', + hiddenPrefix: 'prefix__', + hiddenSuffix: '__suffix', + + // Editable input + editable: true, + + // Time intervals + interval: 30, + + // Time limits + min: new Date(2013, 3, 20, 7), + max: [7, 14], + + // Disable times + disable: [ new Date(2013, 3, 21, 7) ], + + // Root container + container: '.root-container', + + // Events + onStart: () => { }, + onRender: () => { }, + onOpen: () => { }, + onClose: () => { }, + onSet: (context: {[key: string]: any}) => { }, + onStop: () => { } +}); + +timePickerInput.pickatime({ + klass: { + // The element states + input: 'picker__input', + active: 'picker__input--active', + + // The root picker and states * + picker: 'picker picker--time', + opened: 'picker--opened', + focused: 'picker--focused', + + // The picker holder + holder: 'picker__holder', + + // The picker frame, wrapper, and box + frame: 'picker__frame', + wrap: 'picker__wrap', + box: 'picker__box', + + // List of times + list: 'picker__list', + listItem: 'picker__list-item', + + // Time states + disabled: 'picker__list-item--disabled', + selected: 'picker__list-item--selected', + highlighted: 'picker__list-item--highlighted', + viewset: 'picker__list-item--viewset', + now: 'picker__list-item--now', + + // Clear button + buttonClear: 'picker__button--clear' + } +}); + +var timePickerApi = timePickerInput.pickatime('picker'); + +timePickerInput.pickatime('open'); +timePickerInput.pickatime('get', 'value'); + +testApiMethods(timePickerApi); + diff --git a/pickadate/pickadate.d.ts b/pickadate/pickadate.d.ts new file mode 100644 index 000000000..5575b8bc7 --- /dev/null +++ b/pickadate/pickadate.d.ts @@ -0,0 +1,314 @@ +// Type definitions for pickadate.js 3.5.4 +// Project: https://github.com/amsul/pickadate.js +// Definitions by: Adi Dahiya +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface PickadateApi { + /** + * Clear the value in the picker's input element. + */ + clear(): PickadateApi; + + /** + * Close the picker. + * + * @param keepFocus whether to retain focus on the input element (default: false) + */ + close(keepFocus?: boolean): PickadateApi; + + /** + * Get the properties, objects, and states of the picker. + * + * @param field one of [ "value", "select", "highlight", "view", "min", "max", "open", "start", "id", "disable", "enable" ] + * @param format string formatter (available for certain fields) + */ + get(field: string, format?: string): any; + + /** + * Unbind callbacks that are bound using the `on` method. + * @param methodName one of [ "open, "close", "render", "start", "stop", "set" ] + */ + off(methodName: string, ...moreMethodNames: string[]): PickadateApi; + + /** + * Attach an event handler for the picker. Only "set" events callbacks receive a "context" object. + * + * @param methodName event to attach handler to, one of [ "open", "close", "render", "start", "stop", or "set" ] + * @param callback event handler + */ + on(methodName: string, callback: (context?: any) => void): PickadateApi; + + /** + * Open the picker. + * + * @param keepFocus whether to focus the input element (default: true) + */ + open(keepFocus?: boolean): PickadateApi; + + /** + * Refresh the picker after adding something to the holder. + * By default, only the “face” of the picker (i.e. the box element), has its contents re-rendered. + * + * @param fromRoot whether to render the entire picker from the root up (default: false) + */ + render(fromRoot?: boolean): PickadateApi; + + /** + * Set the properties, objects, and states of the picker. + * + * @param field one of [ "clear", "select", "highlight", "view", "min", "max", "disable", "enable", "interval" ] + * @param value the thing you want to set + */ + set(field: string, value: any, options?: {[key: string]: any}): PickadateApi; + /** + * Batch set picker options after initialization. + */ + set(values: {[field: string]: any}, options?: {[key: string]: any}): PickadateApi; + + /** + * Rebuild the picker. + */ + start(): PickadateApi; + + /** + * Destroy the picker. + */ + stop(): PickadateApi; + + /** + * Trigger a picker event. + * @param eventName the event to trigger + */ + trigger(eventName: string): PickadateApi; + + /** + * The picker's relative element. + */ + $node: JQuery; + + /** + * The picker's relative root holder element. + */ + $root: JQuery; + + /** + * The picker's relative hidden element, which is undefined if there's no formatSubmit option. + * This is meant to be mostly for internal use. + */ + _hidden: JQuery; +} + +interface PickadateOptions { + // String and translations + monthsFull?: string[]; + monthsShort?: string[]; + weekdaysFull?: string[]; + weekdaysShort?: string[] + showMonthsShort?: boolean; + showWeekdaysFull?: boolean; + + // Button labels (if falsy, the corresponding button is disabled) + today?: string; + clear?: string; + close?: string; + + // Accessibility labels + labelMonthNext?: string; + labelMonthPrev?: string; + labelMonthSelect?: string; + labelYearSelect?: string; + + // Formats + format?: string; + formatSubmit?: string; + hiddenPrefix?: string; + hiddenSuffix?: string; + hiddenName?: string; + + // Editable input + editable?: boolean; + + // Number of months to show in the month selection dropdown OR a boolean + selectMonths?: any; + // Number of years to show in the month selection dropdown OR a boolean + selectYears?: any; + + // First day of the week + firstDay?: number + + // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + disable?: any[]; + + // Root container selector + container?: string + + // Events + onStart?: () => void; + onRender?: () => void; + onOpen?: () => void; + onClose?: () => void; + onSet?: (context: {[key: string]: any}) => void; + onStop?: () => void; + + // Classes + klass?: PickadateKlassOptions; +} + +interface PickadateKlassOptions { + // The element states + input?: string; + active?: string; + + // The root picker and states + picker?: string; + opened?: string; + focused?: string; + + // The picker holder + holder?: string; + + // The picker frame, wrapper, and box + frame?: string; + wrap?: string; + box?: string; + + // The picker header + header?: string; + + // Month navigation + navPrev?: string; + navNext?: string; + navDisabled?: string; + + // Month & year labels + month?: string; + year?: string; + + // Month & year dropdowns + selectMonth?: string; + selectYear?: string; + + // Table of dates + table?: string; + + // Weekday labels + weekdays?: string; + + // Day states + day?: string; + disabled?: string; + selected?: string; + highlighted?: string; + now?: string; + infocus?: string; + outfocus?: string; + + // The picker footer + footer?: string; + + // Today, clear, & close buttons + buttonClear?: string; + buttonClose?: string; + buttonToday?: string +} + +interface PickatimeOptions { + // Translations and clear button + clear?: string; + + // Formats + format?: string; + formatLabel?: string; + formatSubmit?: string; + hiddenPrefix?: string; + hiddenSuffix?: string; + + // Editable input + editable?: boolean; + + // Time intervals + interval?: number; + + // Time limits (can be Dates, arrays formatted as [HOUR, MINUTE], integers, or booleans) + min?: any; + max?: any; + + // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + disable?: any[]; + + // Root container selector + container?: string + + // Events + onStart?: () => void; + onRender?: () => void; + onOpen?: () => void; + onClose?: () => void; + onSet?: (context: {[key: string]: any}) => void; + onStop?: () => void; + + // Classes + klass?: PickatimeKlassOptions; +} + +interface PickatimeKlassOptions { + // The element states + input?: string; + active?: string; + + // The root picker and states + picker?: string; + opened?: string; + focused?: string; + + // The picker holder + holder?: string; + + // The picker frame, wrapper, and box + frame?: string; + wrap?: string; + box?: string; + + // List of times + list?: string; + listItem?: string; + + // Time states + disabled?: string; + selected?: string; + highlighted?: string; + viewset?: string; + now?: string; + + // Clear button + buttonClear?: string; +} + +interface JQuery { + /** + * Initialize a date picker. + */ + pickadate(options?: PickadateOptions): any; + + /** + * Access objects attached to the picker or invoke API methods after initialization. + * If keyword is "picker", this returns a PickadateApi. + * @param keyword "picker", an object name, or method name + * @param arguments any arguments to pass to the method + */ + pickadate(keyword: string, ...arguments: any[]): any; + + /** + * Initialize a time picker. + */ + pickatime(options?: PickatimeOptions): any; + + /** + * Access objects attached to the picker or invoke API methods after initialization. + * If keyword is "picker", this returns a PickadateApi. + * @param keyword "picker", an object name, or method name + * @param arguments any arguments to pass to the method + */ + pickatime(keyword: string, ...arguments: any[]): any; +} + From b33c9ec8a7181edd52c6bab563f66a6d7f634877 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 24 Sep 2014 12:19:31 +0200 Subject: [PATCH 103/149] add missing external test these tests existed in moment-tests.ts but were missing in moment-external-tests.ts --- moment/moment-external-tests.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index 0c0b56784..559ad7ce6 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -87,6 +87,13 @@ m2.add('hours', 24).hours(); var duration = moment.duration({'days': 1}); moment([2012, 0, 31]).add(duration); +moment().add('seconds', 1); +moment().add('seconds', '1'); +moment().add(1, 'seconds'); + +moment().add('1', 'seconds'); +moment().add('seconds', '1'); + moment().subtract('days', 7); moment().seconds(30); From fa35d205efc89d776b3a6d93ef79af7fa36dace2 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 24 Sep 2014 12:20:27 +0200 Subject: [PATCH 104/149] fix locale/localeData definitions I am not entirely sure about this. But this is how I understand the docs. See http://momentjs.com/docs/#/i18n/ --- moment/moment-external-tests.ts | 39 +++++++++++++++++++-------------- moment/moment-tests.ts | 39 +++++++++++++++++++-------------- moment/moment.d.ts | 7 ++++-- 3 files changed, 49 insertions(+), 36 deletions(-) diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index 559ad7ce6..5f2e23e46 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -230,8 +230,13 @@ adur.subtract(bdur).days(); adur.subtract(1).days(); adur.subtract(1, 'd').days(); +// Selecting a language +moment.locale(); +moment.locale('en'); +moment.locale(['en', 'fr']); + // Defining a custom language: -moment.localeData('en', { +moment.locale('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], weekdays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], @@ -289,14 +294,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { months : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }); -moment.localeData('en', { +moment.locale('en', { months : function (momentToFormat: Moment, format: string) { // momentToFormat is the moment currently being formatted // format is the formatting string @@ -308,14 +313,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { monthsShort : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); -moment.localeData('en', { +moment.locale('en', { monthsShort : function (momentToFormat: Moment, format: string) { if (/^MMMM/.test(format)) { return this.nominative[momentToFormat.month()]; @@ -325,39 +330,39 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { weekdays : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] }); -moment.localeData('en', { +moment.locale('en', { weekdays : function (momentToFormat: Moment) { return this.weekdays[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : function (momentToFormat: Moment) { return this.weekdaysShort[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : function (momentToFormat: Moment) { return this.weekdaysMin[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -371,7 +376,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -381,7 +386,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { relativeTime : { future: "in %s", past: "%s ago", @@ -399,7 +404,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { meridiem : function (hour, minute, isLowercase) { if (hour < 9) { return "早上"; @@ -415,7 +420,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { calendar : { lastDay : '[Yesterday at] LT', sameDay : '[Today at] LT', @@ -428,7 +433,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { ordinal : function (number) { var b = number % 10; var output = (~~ (number % 100 / 10) === 1) ? 'th' : diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 2a8941d8f..4f81b5020 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -228,8 +228,13 @@ adur.subtract(bdur).days(); adur.subtract(1).days(); adur.subtract(1, 'd').days(); +// Selecting a language +moment.locale(); +moment.locale('en'); +moment.locale(['en', 'fr']); + // Defining a custom language: -moment.localeData('en', { +moment.locale('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], weekdays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], @@ -287,14 +292,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { months : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }); -moment.localeData('en', { +moment.locale('en', { months : function (momentToFormat: Moment, format: string) { // momentToFormat is the moment currently being formatted // format is the formatting string @@ -306,14 +311,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { monthsShort : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); -moment.localeData('en', { +moment.locale('en', { monthsShort : function (momentToFormat: Moment, format: string) { if (/^MMMM/.test(format)) { return this.nominative[momentToFormat.month()]; @@ -323,39 +328,39 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { weekdays : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] }); -moment.localeData('en', { +moment.locale('en', { weekdays : function (momentToFormat: Moment) { return this.weekdays[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : function (momentToFormat: Moment) { return this.weekdaysShort[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : function (momentToFormat: Moment) { return this.weekdaysMin[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -369,7 +374,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -379,7 +384,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { relativeTime : { future: "in %s", past: "%s ago", @@ -397,7 +402,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { meridiem : function (hour, minute, isLowercase) { if (hour < 9) { return "早上"; @@ -413,7 +418,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { calendar : { lastDay : '[Yesterday at] LT', sameDay : '[Today at] LT', @@ -426,7 +431,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { ordinal : function (number) { var b = number % 10; var output = (~~ (number % 100 / 10) === 1) ? 'th' : diff --git a/moment/moment.d.ts b/moment/moment.d.ts index 57d967f78..6037b0ef0 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -382,8 +382,11 @@ interface MomentStatic { lang(language?: string): string; lang(language?: string, definition?: MomentLanguage): string; - localeData(language?: string): string; - localeData(language?: string, definition?: MomentLanguage): string; + locale(language?: string): string; + locale(language?: string[]): string; + locale(language?: string, definition?: MomentLanguage): string; + + localeData(language?: string): MomentLanguage; longDateFormat: any; relativeTime: any; From dde8ea1a3f679b70567db0e22199e8de0026e4be Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 24 Sep 2014 12:22:32 +0200 Subject: [PATCH 105/149] Strip Whitespace --- moment/moment-external-tests.ts | 58 ++++++++++++++++----------------- moment/moment-tests.ts | 58 ++++++++++++++++----------------- 2 files changed, 58 insertions(+), 58 deletions(-) diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index 5f2e23e46..14376f2b4 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -18,7 +18,7 @@ var now = moment(); var day7 = moment([2010, 1, 14, 15, 25, 50, 125]); var day8 = moment([2010]); var day9 = moment([2010, 6]); -var day10 = moment([2010, 6, 10]); +var day10 = moment([2010, 6, 10]); var array = [2010, 1, 14, 15, 25, 50, 125]; var day11 = moment(Date.UTC.apply({}, array)); var day12 = moment.unix(1318781876); @@ -62,8 +62,8 @@ a.hours(); a.local(); a.hours(); -moment("2011-10-10", "YYYY-MM-DD").isValid(); -moment("2011-10-50", "YYYY-MM-DD").isValid(); +moment("2011-10-10", "YYYY-MM-DD").isValid(); +moment("2011-10-50", "YYYY-MM-DD").isValid(); moment("2011-10-10T10:20:90").isValid(); moment([2011, 0, 1]).isValid(); moment([2011, 0, 50]).isValid(); @@ -74,16 +74,16 @@ moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).sec moment().add('days', 7); moment().add('days', 7).add('months', 1); moment().add({days:7,months:1}); -moment().add('milliseconds', 1000000); +moment().add('milliseconds', 1000000); moment().add('days', 360); -moment([2010, 0, 31]); +moment([2010, 0, 31]); moment([2010, 0, 31]).add('months', 1); var m = moment(new Date(2011, 2, 12, 5, 0, 0)); -m.hours(); +m.hours(); m.add('days', 1).hours(); -var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); +var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); m2.hours(); -m2.add('hours', 24).hours(); +m2.add('hours', 24).hours(); var duration = moment.duration({'days': 1}); moment([2012, 0, 31]).add(duration); @@ -99,14 +99,14 @@ moment().subtract('days', 7); moment().seconds(30); moment().minutes(30); -moment().hours(12); +moment().hours(12); moment().date(5); moment().day(5); moment().day("Sunday"); moment().month(5); moment().month("January"); moment().year(1984); -moment().startOf('year'); +moment().startOf('year'); moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0); moment().startOf('hour'); moment().minutes(0).seconds(0).milliseconds(0); @@ -127,10 +127,10 @@ moment().isoWeek(45); moment().isoWeeks(); moment().isoWeeks(45); -var getMilliseconds: number = moment().milliseconds(); -var getSeconds: number = moment().seconds(); -var getMinutes: number = moment().minutes(); -var getHours: number = moment().hours(); +var getMilliseconds: number = moment().milliseconds(); +var getSeconds: number = moment().seconds(); +var getMinutes: number = moment().minutes(); +var getHours: number = moment().hours(); var getDate: number = moment().date(); var getDay: number = moment().day(); var getMonth: number = moment().month(); @@ -145,11 +145,11 @@ a3.utc(); a3.hours(); var a4 = moment([2010, 1, 14, 15, 25, 50, 125]); -a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); +a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); a4.format("ddd, hA"); moment().format('\\L'); -moment().format('[today] DDDD'); +moment().format('[today] DDDD'); var a5 = moment([2007, 0, 29]); var b5 = moment([2007, 0, 28]); @@ -158,8 +158,8 @@ a5.from(b5); var a6 = moment([2007, 0, 29]); var b6 = moment([2007, 0, 28]); a6.from(b6); -a6.from([2007, 0, 28]); -a6.from(new Date(2007, 0, 28)); +a6.from([2007, 0, 28]); +a6.from(new Date(2007, 0, 28)); a6.from("1-28-2007"); var a7 = moment(); @@ -168,23 +168,23 @@ a7.from(b7); var start = moment([2007, 0, 5]); var end = moment([2007, 0, 10]); -start.from(end); +start.from(end); start.from(end, true); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(true); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(true); var a8 = moment([2007, 0, 29]); var b8 = moment([2007, 0, 28]); a8.diff(b8) ; a8.diff(b8, 'days'); -a8.diff(b8, 'years') +a8.diff(b8, 'years') a8.diff(b8, 'years', true); moment([2007, 0, 29]).toDate(); moment([2007, 1, 23]).toISOString(); -moment(1318874398806).valueOf(); +moment(1318874398806).valueOf(); moment(1318874398806).unix(); moment([2000]).isLeapYear(); moment().zone(); @@ -198,12 +198,12 @@ moment.isMoment(moment()); moment.localeData('fr'); moment(1316116057189).fromNow(); -moment.localeData('en'); +moment.localeData('en'); var globalLang = moment(); var localLang = moment(); -localLang.localeData('fr'); -localLang.format('LLLL'); -globalLang.format('LLLL'); +localLang.localeData('fr'); +localLang.format('LLLL'); +globalLang.format('LLLL'); moment.duration(100); moment.duration(2, 'seconds'); @@ -235,7 +235,7 @@ moment.locale(); moment.locale('en'); moment.locale(['en', 'fr']); -// Defining a custom language: +// Defining a custom language: moment.locale('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 4f81b5020..ab629921d 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -16,7 +16,7 @@ var now = moment(); var day7 = moment([2010, 1, 14, 15, 25, 50, 125]); var day8 = moment([2010]); var day9 = moment([2010, 6]); -var day10 = moment([2010, 6, 10]); +var day10 = moment([2010, 6, 10]); var array = [2010, 1, 14, 15, 25, 50, 125]; var day11 = moment(Date.UTC.apply({}, array)); var day12 = moment.unix(1318781876); @@ -60,8 +60,8 @@ a.hours(); a.local(); a.hours(); -moment("2011-10-10", "YYYY-MM-DD").isValid(); -moment("2011-10-50", "YYYY-MM-DD").isValid(); +moment("2011-10-10", "YYYY-MM-DD").isValid(); +moment("2011-10-50", "YYYY-MM-DD").isValid(); moment("2011-10-10T10:20:90").isValid(); moment([2011, 0, 1]).isValid(); moment([2011, 0, 50]).isValid(); @@ -72,16 +72,16 @@ moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).sec moment().add('days', 7); moment().add('days', 7).add('months', 1); moment().add({days:7,months:1}); -moment().add('milliseconds', 1000000); +moment().add('milliseconds', 1000000); moment().add('days', 360); -moment([2010, 0, 31]); +moment([2010, 0, 31]); moment([2010, 0, 31]).add('months', 1); var m = moment(new Date(2011, 2, 12, 5, 0, 0)); -m.hours(); +m.hours(); m.add('days', 1).hours(); -var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); +var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); m2.hours(); -m2.add('hours', 24).hours(); +m2.add('hours', 24).hours(); var duration = moment.duration({'days': 1}); moment([2012, 0, 31]).add(duration); @@ -97,14 +97,14 @@ moment().subtract('days', 7); moment().seconds(30); moment().minutes(30); -moment().hours(12); +moment().hours(12); moment().date(5); moment().day(5); moment().day("Sunday"); moment().month(5); moment().month("January"); moment().year(1984); -moment().startOf('year'); +moment().startOf('year'); moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0); moment().startOf('hour'); moment().minutes(0).seconds(0).milliseconds(0); @@ -125,10 +125,10 @@ moment().isoWeek(45); moment().isoWeeks(); moment().isoWeeks(45); -var getMilliseconds: number = moment().milliseconds(); -var getSeconds: number = moment().seconds(); -var getMinutes: number = moment().minutes(); -var getHours: number = moment().hours(); +var getMilliseconds: number = moment().milliseconds(); +var getSeconds: number = moment().seconds(); +var getMinutes: number = moment().minutes(); +var getHours: number = moment().hours(); var getDate: number = moment().date(); var getDay: number = moment().day(); var getMonth: number = moment().month(); @@ -143,11 +143,11 @@ a3.utc(); a3.hours(); var a4 = moment([2010, 1, 14, 15, 25, 50, 125]); -a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); +a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); a4.format("ddd, hA"); moment().format('\\L'); -moment().format('[today] DDDD'); +moment().format('[today] DDDD'); var a5 = moment([2007, 0, 29]); var b5 = moment([2007, 0, 28]); @@ -156,8 +156,8 @@ a5.from(b5); var a6 = moment([2007, 0, 29]); var b6 = moment([2007, 0, 28]); a6.from(b6); -a6.from([2007, 0, 28]); -a6.from(new Date(2007, 0, 28)); +a6.from([2007, 0, 28]); +a6.from(new Date(2007, 0, 28)); a6.from("1-28-2007"); var a7 = moment(); @@ -166,23 +166,23 @@ a7.from(b7); var start = moment([2007, 0, 5]); var end = moment([2007, 0, 10]); -start.from(end); +start.from(end); start.from(end, true); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(true); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(true); var a8 = moment([2007, 0, 29]); var b8 = moment([2007, 0, 28]); a8.diff(b8) ; a8.diff(b8, 'days'); -a8.diff(b8, 'years') +a8.diff(b8, 'years') a8.diff(b8, 'years', true); moment([2007, 0, 29]).toDate(); moment([2007, 1, 23]).toISOString(); -moment(1318874398806).valueOf(); +moment(1318874398806).valueOf(); moment(1318874398806).unix(); moment([2000]).isLeapYear(); moment().zone(); @@ -196,12 +196,12 @@ moment.isMoment(moment()); moment.localeData('fr'); moment(1316116057189).fromNow(); -moment.localeData('en'); +moment.localeData('en'); var globalLang = moment(); var localLang = moment(); -localLang.localeData('fr'); -localLang.format('LLLL'); -globalLang.format('LLLL'); +localLang.localeData('fr'); +localLang.format('LLLL'); +globalLang.format('LLLL'); moment.duration(100); moment.duration(2, 'seconds'); @@ -233,7 +233,7 @@ moment.locale(); moment.locale('en'); moment.locale(['en', 'fr']); -// Defining a custom language: +// Defining a custom language: moment.locale('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], From 5c7e8235061fea99ebda10f6c572ac77b72c3221 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 24 Sep 2014 15:42:07 +0100 Subject: [PATCH 106/149] Rename node-ip directory to ip Rename node-ip to ip so the folder name matches the library name on npm. --- {node-ip => ip}/ip-tests.ts | 0 {node-ip => ip}/ip.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {node-ip => ip}/ip-tests.ts (100%) rename {node-ip => ip}/ip.d.ts (100%) diff --git a/node-ip/ip-tests.ts b/ip/ip-tests.ts similarity index 100% rename from node-ip/ip-tests.ts rename to ip/ip-tests.ts diff --git a/node-ip/ip.d.ts b/ip/ip.d.ts similarity index 100% rename from node-ip/ip.d.ts rename to ip/ip.d.ts From 68e02ce374f7d93de515bc8a410894a2dfc959e7 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 24 Sep 2014 15:43:41 +0100 Subject: [PATCH 107/149] Rename node-radius directory to radius Rename node-radius directory to radius to match its library name on npm. --- {node-radius => radius}/radius-tests.ts | 0 {node-radius => radius}/radius.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {node-radius => radius}/radius-tests.ts (100%) rename {node-radius => radius}/radius.d.ts (100%) diff --git a/node-radius/radius-tests.ts b/radius/radius-tests.ts similarity index 100% rename from node-radius/radius-tests.ts rename to radius/radius-tests.ts diff --git a/node-radius/radius.d.ts b/radius/radius.d.ts similarity index 100% rename from node-radius/radius.d.ts rename to radius/radius.d.ts From 648f460f302b223c98b3b4e85c65a7c4db8d860f Mon Sep 17 00:00:00 2001 From: Adi Dahiya Date: Wed, 24 Sep 2014 12:15:09 -0400 Subject: [PATCH 108/149] Update pickadate.d.ts to expose only one top-level module * Also update CONTRIBUTORS.md * Add api method chaining to pickadate-tests.ts --- CONTRIBUTORS.md | 1 + pickadate/pickadate-tests.ts | 8 +- pickadate/pickadate.d.ts | 487 ++++++++++++++++++----------------- 3 files changed, 251 insertions(+), 245 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index eb9f9b64e..5fe2714f4 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -300,6 +300,7 @@ All definitions files include a header with the author and editors, so at some p * [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) * [Physijs](http://chandlerprall.github.io/Physijs/) (by [gyoh_k](https://github.com/gyohk)) +* [Pickadate.js](https://github.com/amsul/pickadate.js) (by [Adi Dahiya](https://github.com/adidahiya)) * [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments)) * [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) * [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) diff --git a/pickadate/pickadate-tests.ts b/pickadate/pickadate-tests.ts index 6b3e9fccb..ac48a9856 100644 --- a/pickadate/pickadate-tests.ts +++ b/pickadate/pickadate-tests.ts @@ -1,7 +1,7 @@ /// /// -function testApiMethods(api: PickadateApi) { +function testApiMethods(api: Pickadate.Api) { api.clear(); api.close(); api.close(true); @@ -24,6 +24,8 @@ function testApiMethods(api: PickadateApi) { api.stop(); api.trigger('open'); + api.start().open().close().stop(); + var pickerInputElement = api.$node; pickerInputElement.show(); @@ -148,7 +150,7 @@ datePickerInput.pickadate({ } }); -var datePickerApi = datePickerInput.pickadate('picker'); +var datePickerApi = datePickerInput.pickadate('picker'); datePickerInput.pickadate('open'); datePickerInput.pickadate('get', 'value'); @@ -232,7 +234,7 @@ timePickerInput.pickatime({ } }); -var timePickerApi = timePickerInput.pickatime('picker'); +var timePickerApi = timePickerInput.pickatime('picker'); timePickerInput.pickatime('open'); timePickerInput.pickatime('get', 'value'); diff --git a/pickadate/pickadate.d.ts b/pickadate/pickadate.d.ts index 5575b8bc7..d21550d00 100644 --- a/pickadate/pickadate.d.ts +++ b/pickadate/pickadate.d.ts @@ -3,312 +3,315 @@ // Definitions by: Adi Dahiya // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface PickadateApi { - /** - * Clear the value in the picker's input element. - */ - clear(): PickadateApi; +declare module Pickadate { - /** - * Close the picker. - * - * @param keepFocus whether to retain focus on the input element (default: false) - */ - close(keepFocus?: boolean): PickadateApi; + export interface Api { + /** + * Clear the value in the picker's input element. + */ + clear(): Pickadate.Api; - /** - * Get the properties, objects, and states of the picker. - * - * @param field one of [ "value", "select", "highlight", "view", "min", "max", "open", "start", "id", "disable", "enable" ] - * @param format string formatter (available for certain fields) - */ - get(field: string, format?: string): any; + /** + * Close the picker. + * + * @param keepFocus whether to retain focus on the input element (default: false) + */ + close(keepFocus?: boolean): Pickadate.Api; - /** - * Unbind callbacks that are bound using the `on` method. - * @param methodName one of [ "open, "close", "render", "start", "stop", "set" ] - */ - off(methodName: string, ...moreMethodNames: string[]): PickadateApi; + /** + * Get the properties, objects, and states of the picker. + * + * @param field one of [ "value", "select", "highlight", "view", "min", "max", "open", "start", "id", "disable", "enable" ] + * @param format string formatter (available for certain fields) + */ + get(field: string, format?: string): any; - /** - * Attach an event handler for the picker. Only "set" events callbacks receive a "context" object. - * - * @param methodName event to attach handler to, one of [ "open", "close", "render", "start", "stop", or "set" ] - * @param callback event handler - */ - on(methodName: string, callback: (context?: any) => void): PickadateApi; + /** + * Unbind callbacks that are bound using the `on` method. + * @param methodName one of [ "open, "close", "render", "start", "stop", "set" ] + */ + off(methodName: string, ...moreMethodNames: string[]): Pickadate.Api; - /** - * Open the picker. - * - * @param keepFocus whether to focus the input element (default: true) - */ - open(keepFocus?: boolean): PickadateApi; + /** + * Attach an event handler for the picker. Only "set" events callbacks receive a "context" object. + * + * @param methodName event to attach handler to, one of [ "open", "close", "render", "start", "stop", or "set" ] + * @param callback event handler + */ + on(methodName: string, callback: (context?: any) => void): Pickadate.Api; - /** - * Refresh the picker after adding something to the holder. - * By default, only the “face” of the picker (i.e. the box element), has its contents re-rendered. - * - * @param fromRoot whether to render the entire picker from the root up (default: false) - */ - render(fromRoot?: boolean): PickadateApi; + /** + * Open the picker. + * + * @param keepFocus whether to focus the input element (default: true) + */ + open(keepFocus?: boolean): Pickadate.Api; - /** - * Set the properties, objects, and states of the picker. - * - * @param field one of [ "clear", "select", "highlight", "view", "min", "max", "disable", "enable", "interval" ] - * @param value the thing you want to set - */ - set(field: string, value: any, options?: {[key: string]: any}): PickadateApi; - /** - * Batch set picker options after initialization. - */ - set(values: {[field: string]: any}, options?: {[key: string]: any}): PickadateApi; + /** + * Refresh the picker after adding something to the holder. + * By default, only the “face” of the picker (i.e. the box element), has its contents re-rendered. + * + * @param fromRoot whether to render the entire picker from the root up (default: false) + */ + render(fromRoot?: boolean): Pickadate.Api; - /** - * Rebuild the picker. - */ - start(): PickadateApi; + /** + * Set the properties, objects, and states of the picker. + * + * @param field one of [ "clear", "select", "highlight", "view", "min", "max", "disable", "enable", "interval" ] + * @param value the thing you want to set + */ + set(field: string, value: any, options?: {[key: string]: any}): Pickadate.Api; + /** + * Batch set picker options after initialization. + */ + set(values: {[field: string]: any}, options?: {[key: string]: any}): Pickadate.Api; - /** - * Destroy the picker. - */ - stop(): PickadateApi; + /** + * Rebuild the picker. + */ + start(): Pickadate.Api; - /** - * Trigger a picker event. - * @param eventName the event to trigger - */ - trigger(eventName: string): PickadateApi; + /** + * Destroy the picker. + */ + stop(): Pickadate.Api; - /** - * The picker's relative element. - */ - $node: JQuery; + /** + * Trigger a picker event. + * @param eventName the event to trigger + */ + trigger(eventName: string): Pickadate.Api; - /** - * The picker's relative root holder element. - */ - $root: JQuery; + /** + * The picker's relative element. + */ + $node: JQuery; - /** - * The picker's relative hidden element, which is undefined if there's no formatSubmit option. - * This is meant to be mostly for internal use. - */ - _hidden: JQuery; -} + /** + * The picker's relative root holder element. + */ + $root: JQuery; -interface PickadateOptions { - // String and translations - monthsFull?: string[]; - monthsShort?: string[]; - weekdaysFull?: string[]; - weekdaysShort?: string[] - showMonthsShort?: boolean; - showWeekdaysFull?: boolean; + /** + * The picker's relative hidden element, which is undefined if there's no formatSubmit option. + * This is meant to be mostly for internal use. + */ + _hidden: JQuery; + } - // Button labels (if falsy, the corresponding button is disabled) - today?: string; - clear?: string; - close?: string; + export interface DateOptions { + // String and translations + monthsFull?: string[]; + monthsShort?: string[]; + weekdaysFull?: string[]; + weekdaysShort?: string[] + showMonthsShort?: boolean; + showWeekdaysFull?: boolean; - // Accessibility labels - labelMonthNext?: string; - labelMonthPrev?: string; - labelMonthSelect?: string; - labelYearSelect?: string; + // Button labels (if falsy, the corresponding button is disabled) + today?: string; + clear?: string; + close?: string; - // Formats - format?: string; - formatSubmit?: string; - hiddenPrefix?: string; - hiddenSuffix?: string; - hiddenName?: string; + // Accessibility labels + labelMonthNext?: string; + labelMonthPrev?: string; + labelMonthSelect?: string; + labelYearSelect?: string; - // Editable input - editable?: boolean; + // Formats + format?: string; + formatSubmit?: string; + hiddenPrefix?: string; + hiddenSuffix?: string; + hiddenName?: string; - // Number of months to show in the month selection dropdown OR a boolean - selectMonths?: any; - // Number of years to show in the month selection dropdown OR a boolean - selectYears?: any; + // Editable input + editable?: boolean; - // First day of the week - firstDay?: number + // Number of months to show in the month selection dropdown OR a boolean + selectMonths?: any; + // Number of years to show in the month selection dropdown OR a boolean + selectYears?: any; - // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) - disable?: any[]; + // First day of the week + firstDay?: number - // Root container selector - container?: string + // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + disable?: any[]; - // Events - onStart?: () => void; - onRender?: () => void; - onOpen?: () => void; - onClose?: () => void; - onSet?: (context: {[key: string]: any}) => void; - onStop?: () => void; + // Root container selector + container?: string - // Classes - klass?: PickadateKlassOptions; -} + // Events + onStart?: () => void; + onRender?: () => void; + onOpen?: () => void; + onClose?: () => void; + onSet?: (context: {[key: string]: any}) => void; + onStop?: () => void; -interface PickadateKlassOptions { - // The element states - input?: string; - active?: string; + // Classes + klass?: DateKlassOptions; + } - // The root picker and states - picker?: string; - opened?: string; - focused?: string; + export interface DateKlassOptions { + // The element states + input?: string; + active?: string; - // The picker holder - holder?: string; + // The root picker and states + picker?: string; + opened?: string; + focused?: string; - // The picker frame, wrapper, and box - frame?: string; - wrap?: string; - box?: string; + // The picker holder + holder?: string; - // The picker header - header?: string; + // The picker frame, wrapper, and box + frame?: string; + wrap?: string; + box?: string; - // Month navigation - navPrev?: string; - navNext?: string; - navDisabled?: string; + // The picker header + header?: string; - // Month & year labels - month?: string; - year?: string; + // Month navigation + navPrev?: string; + navNext?: string; + navDisabled?: string; - // Month & year dropdowns - selectMonth?: string; - selectYear?: string; + // Month & year labels + month?: string; + year?: string; - // Table of dates - table?: string; + // Month & year dropdowns + selectMonth?: string; + selectYear?: string; - // Weekday labels - weekdays?: string; + // Table of dates + table?: string; - // Day states - day?: string; - disabled?: string; - selected?: string; - highlighted?: string; - now?: string; - infocus?: string; - outfocus?: string; + // Weekday labels + weekdays?: string; - // The picker footer - footer?: string; + // Day states + day?: string; + disabled?: string; + selected?: string; + highlighted?: string; + now?: string; + infocus?: string; + outfocus?: string; - // Today, clear, & close buttons - buttonClear?: string; - buttonClose?: string; - buttonToday?: string -} + // The picker footer + footer?: string; -interface PickatimeOptions { - // Translations and clear button - clear?: string; + // Today, clear, & close buttons + buttonClear?: string; + buttonClose?: string; + buttonToday?: string + } - // Formats - format?: string; - formatLabel?: string; - formatSubmit?: string; - hiddenPrefix?: string; - hiddenSuffix?: string; + export interface TimeOptions { + // Translations and clear button + clear?: string; - // Editable input - editable?: boolean; + // Formats + format?: string; + formatLabel?: string; + formatSubmit?: string; + hiddenPrefix?: string; + hiddenSuffix?: string; - // Time intervals - interval?: number; + // Editable input + editable?: boolean; - // Time limits (can be Dates, arrays formatted as [HOUR, MINUTE], integers, or booleans) - min?: any; - max?: any; + // Time intervals + interval?: number; - // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) - disable?: any[]; + // Time limits (can be Dates, arrays formatted as [HOUR, MINUTE], integers, or booleans) + min?: any; + max?: any; - // Root container selector - container?: string + // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + disable?: any[]; - // Events - onStart?: () => void; - onRender?: () => void; - onOpen?: () => void; - onClose?: () => void; - onSet?: (context: {[key: string]: any}) => void; - onStop?: () => void; + // Root container selector + container?: string - // Classes - klass?: PickatimeKlassOptions; -} + // Events + onStart?: () => void; + onRender?: () => void; + onOpen?: () => void; + onClose?: () => void; + onSet?: (context: {[key: string]: any}) => void; + onStop?: () => void; -interface PickatimeKlassOptions { - // The element states - input?: string; - active?: string; + // Classes + klass?: TimeKlassOptions; + } - // The root picker and states - picker?: string; - opened?: string; - focused?: string; + export interface TimeKlassOptions { + // The element states + input?: string; + active?: string; - // The picker holder - holder?: string; + // The root picker and states + picker?: string; + opened?: string; + focused?: string; - // The picker frame, wrapper, and box - frame?: string; - wrap?: string; - box?: string; + // The picker holder + holder?: string; - // List of times - list?: string; - listItem?: string; + // The picker frame, wrapper, and box + frame?: string; + wrap?: string; + box?: string; - // Time states - disabled?: string; - selected?: string; - highlighted?: string; - viewset?: string; - now?: string; + // List of times + list?: string; + listItem?: string; - // Clear button - buttonClear?: string; + // Time states + disabled?: string; + selected?: string; + highlighted?: string; + viewset?: string; + now?: string; + + // Clear button + buttonClear?: string; + } } interface JQuery { /** - * Initialize a date picker. - */ - pickadate(options?: PickadateOptions): any; + * Initialize a date picker. + */ + pickadate(options?: Pickadate.DateOptions): any; /** - * Access objects attached to the picker or invoke API methods after initialization. - * If keyword is "picker", this returns a PickadateApi. - * @param keyword "picker", an object name, or method name - * @param arguments any arguments to pass to the method - */ + * Access objects attached to the picker or invoke API methods after initialization. + * If keyword is "picker", this returns a PickadateApi. + * @param keyword "picker", an object name, or method name + * @param arguments any arguments to pass to the method + */ pickadate(keyword: string, ...arguments: any[]): any; /** - * Initialize a time picker. - */ - pickatime(options?: PickatimeOptions): any; + * Initialize a time picker. + */ + pickatime(options?: Pickadate.TimeOptions): any; /** - * Access objects attached to the picker or invoke API methods after initialization. - * If keyword is "picker", this returns a PickadateApi. - * @param keyword "picker", an object name, or method name - * @param arguments any arguments to pass to the method - */ + * Access objects attached to the picker or invoke API methods after initialization. + * If keyword is "picker", this returns a PickadateApi. + * @param keyword "picker", an object name, or method name + * @param arguments any arguments to pass to the method + */ pickatime(keyword: string, ...arguments: any[]): any; } From 42dc44b2d544b89e9f19a98083a5c70c055211a1 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Wed, 24 Sep 2014 22:05:34 +0100 Subject: [PATCH 109/149] Update winston definitions and tests A large rewrite, with greater detailed definitions. *BREAKING CHANGE:* winston.Transport and winston.Logger types have been renamed to winston.TransportStatic and winston.LoggerStatic respectively. Instantiating the types still uses the old syntax: ```var logger = new winston.Logger``` but the return type's name has had "Static" appended. --- winston/winston-tests.ts | 199 +++++++++++++++++++++++++++++++++++++-- winston/winston.d.ts | 183 ++++++++++++++++++++++++++++++----- 2 files changed, 349 insertions(+), 33 deletions(-) diff --git a/winston/winston-tests.ts b/winston/winston-tests.ts index 499b427a6..0fa3cb442 100644 --- a/winston/winston-tests.ts +++ b/winston/winston-tests.ts @@ -4,14 +4,73 @@ import winston = require('winston'); var str: string; var bool: boolean; +var num: number; var metadata: any; +var obj: any = {}; + +var queryOptions: winston.QueryOptions; +var transportOptions: winston.TransportOptions; +var loggerOptions: winston.LoggerOptions = { + transports: [new (winston.Transport)()], + rewriters: [new (winston.Transport)()], + exceptionHandlers: [new (winston.Transport)()], + handleExceptions: false +}; + var options: any; var value: any; -var transport: winston.Transport; +var transport: winston.TransportInstance; +var logger: winston.LoggerInstance; +var profiler: winston.ProfileHandler; + +var writeableStream: NodeJS.WritableStream; +var readableStream: NodeJS.ReadableStream; + + +var transportStatic: winston.TransportStatic = winston.Transport; + + +var transportInstance: winston.TransportInstance = new (winston.Transport)(transportOptions); +transportInstance = new (winston.Transport)(); + +var containerInstance: winston.ContainerInstance = new (winston.Container)(loggerOptions); +winston.loggers.options.transports = [ + new (winston.Transport)() +]; +winston.loggers.add('category1', { + console: { + level: 'silly', + colorize: 'true', + label: 'category one' + }, + file: { + filename: '/path/to/some/file' + }, + transports: [ + new (winston.Transport)() + ] +}); +logger = winston.loggers.get('category1'); + +bool = containerInstance.has(str); +logger = containerInstance.get(str, loggerOptions); +containerInstance.close(str); -transport = winston.transports.File; transport = winston.transports.Console; +transport = winston.transports.DailyRotateFile; +transport = winston.transports.File; +transport = winston.transports.Http; transport = winston.transports.Loggly; +transport = winston.transports.Memory +transport = winston.transports.Webhook; + +value = transport.formatQuery({}); +queryOptions = transport.normalizeQuery(queryOptions); +value = transport.formatResults([], {}); +transport.logException(str, metadata, () => { }); + +winston.exitOnError = bool; + winston.log(str, str); winston.log(str, str, metadata); @@ -24,17 +83,139 @@ winston.warn(str, metadata); winston.error(str); winston.error(str, metadata); -winston.add(transport, options); -winston.remove(transport); +winston.query(queryOptions, (err: Error, results: any): void => { -winston.profile(str); - -winston.query(options, (err: any, results: any) => { +}); +winston.query((err: Error, results: any): void => { }); -value = winston.stream(options); +logger = winston.add(transport, transportOptions); +logger = winston.remove(transport); + +winston.clear(); +logger = winston.profile(str, str, metadata, (err: Error, level: string, msg: string, meta: any):void => { + +}); +logger = winston.profile(str); +profiler = winston.startTimer(); +winston.setLevels({}); +logger = winston.cli(); winston.handleExceptions(transport); -winston.exitOnError = bool; +winston.unhandleExceptions(transport); +readableStream = winston.stream(options); + +readableStream.on('log', function (log:any):void { + console.log(log); +}); + + + +logger = logger.extend(obj); +logger.log(str, str); +logger.log(str, str, metadata); +logger.debug(str); +logger.debug(str, metadata); +logger.info(str); +logger.info(str, metadata); +logger.warn(str); +logger.warn(str, metadata); +logger.error(str); +logger.error(str, metadata); + +logger.query(queryOptions, (err: Error, results: any): void => { + +}); +logger.query((err: Error, results: any): void => { + +}); + +readableStream = winston.stream(options); +logger.close(); +logger.handleExceptions(transport); +logger.unhandleExceptions(transport); +logger = logger.add(transport, transportOptions, bool); +logger = logger.add(transport); +logger.addRewriter(transport)[0]; +logger.clear(); +logger = logger.remove(transport); +profiler = logger.startTimer(); +logger = logger.profile(str, str, metadata, (err: Error, level: string, msg: string, meta: any):void => { + +}); +value = logger.setLevels(value); +logger = logger.cli(); + + +logger = profiler.done(str); +logger = profiler.logger; +profiler.start = new Date(); + + +/** + * New Logger instances with transports tests: + */ + +var logger: winston.LoggerInstance = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ + level: str, + silent: bool, + colorize: bool, + timestamp: bool, + }), + new (winston.transports.DailyRotateFile)({ + level: str, + silent: bool, + colorize: bool, + maxsize: num, + maxFiles: num, + prettyPrint: bool, + timestamp: bool, + filename: str, + dirname: str, + datePattern: str + }), + new (winston.transports.File)({ + level: str, + silent: bool, + timestamp: bool, + filename: str, + maxsize: num, + maxFiles: num, + stream: writeableStream, + }), + new (winston.transports.Http)({ + level: str, + host: str, + port: num, + path: str, + auth: { username: str, password: str }, + ssl: {}, + }), + new (winston.transports.Loggly)({ + level: str, + subdomain: str, + auth: {}, + inputName: str, + json: bool, + }), + new (winston.transports.Memory)({ + level: str, + timestamp: bool, + label: str, + }), + new (winston.transports.Webhook)({ + level: str, + name: str, + host: str, + port: num, + method: str, + path: str, + auth: { username: str, password: str }, + ssl: {}, + }), + ] +}); \ No newline at end of file diff --git a/winston/winston.d.ts b/winston/winston.d.ts index 8ebd618ff..c0e5a7a42 100644 --- a/winston/winston.d.ts +++ b/winston/winston.d.ts @@ -1,39 +1,174 @@ // Type definitions for winston // Project: https://github.com/flatiron/winston -// Definitions by: bonnici +// Definitions by: bonnici , Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/winston.d.ts -declare module "winston" { - export function log(level: string, message: string, metadata?: any): void; - export function debug(message: string, metadata?: any): void; - export function info(message: string, metadata?: any): void; - export function warn(message: string, metadata?: any): void; - export function error(message: string, metadata?: any): void; +/// - export function add(transport: Transport, options: any): void; - export function remove(transport: Transport): void; - export function profile(name: string): void; +//////// Here for backwards compatibility to older Node definitions //////// +declare module NodeJS { + interface EventEmitter { } + interface ReadWriteStream { } +} - export function query(options: any, done: (err: any, results: any) => void): void; +interface NodeEventEmitter extends NodeJS.EventEmitter { } +interface ReadableStream extends NodeJS.ReadableStream { } +//////////////////////////////////////////////////////////////////////////// - export function stream(options: any): any; +declare module "winston" { - export function handleExceptions(transport: Transport): void; + export var transports: Transports; + export var Transport: TransportStatic; + export var Logger: LoggerStatic; + export var Container: ContainerStatic; + export var loggers: ContainerInstance; + export var defaultLogger: LoggerInstance; - export class Logger { + export var exitOnError: boolean; - } - export interface Transport { - } - export interface Transports { - File: Transport; - Console: Transport; - Loggly: Transport; - } - export var transports: Transports; - export var exitOnError: boolean; + export function log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function log(level: string, msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + export function debug(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function debug(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + export function info(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function info(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + export function warn(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function warn(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + export function error(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function error(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + export function query(options: QueryOptions, callback?: (err: Error, results: any) => void): any; + export function query(callback: (err: Error, results: any) => void): any; + export function stream(options?: any): ReadableStream; + export function handleExceptions(...transports: TransportInstance[]): void; + export function unhandleExceptions(...transports: TransportInstance[]): void; + export function add(transport: TransportInstance, options?: TransportOptions, created?: boolean): LoggerInstance; + export function clear(): void; + export function remove(transport: TransportInstance): LoggerInstance; + export function startTimer(): ProfileHandler; + export function profile(id: string, msg?: string, meta?: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function setLevels(target: any): any; + export function cli(): LoggerInstance; + + + export interface LoggerStatic { + new (options?: LoggerOptions); + } + + export interface LoggerInstance extends NodeEventEmitter { + extend(target: any): LoggerInstance; + + log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + log(level: string, msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + debug(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + debug(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + info(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + info(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + warn(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + warn(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + error(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + error(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + query(options: QueryOptions, callback?: (err: Error, results: any) => void): any; + query(callback: (err: Error, results: any) => void): any; + stream(options?: any): ReadableStream; + close(): void; + handleExceptions(...transports: TransportInstance[]): void; + unhandleExceptions(...transports: TransportInstance[]): void; + add(transport: TransportInstance, options?: TransportOptions, created?: boolean): LoggerInstance; + addRewriter(rewriter: TransportInstance): TransportInstance[]; + clear(): void; + remove(transport: TransportInstance): LoggerInstance; + startTimer(): ProfileHandler; + profile(id: string, msg?: string, meta?: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + setLevels(target: any): any; + cli(): LoggerInstance; + } + + export interface LoggerOptions { + transports?: TransportInstance[]; + rewriters?: TransportInstance[]; + exceptionHandlers?: TransportInstance[]; + handleExceptions?: boolean; + + /** + * @type {(boolean|(err: Error) => void)} + */ + exitOnError?: any; + } + + export interface TransportStatic { + new (options?: TransportOptions): TransportInstance; + } + + export interface TransportInstance extends TransportStatic, NodeEventEmitter { + formatQuery(query: any): any; + normalizeQuery(options: QueryOptions): QueryOptions; + formatResults(results: any, options: any): any; + logException(msg: string, meta: any, callback: () => void): void; + } + + export interface ContainerStatic { + new (options: LoggerOptions): ContainerInstance; + } + + export interface ContainerInstance extends ContainerStatic { + get(id: string, options?: LoggerOptions): LoggerInstance; + add(id: string, options: LoggerOptions): LoggerInstance; + has(id: string): boolean; + close(id: string): void; + options: LoggerOptions; + loggers: any; + default: LoggerOptions; + } + + export interface Transports { + File: TransportInstance; + Console: TransportInstance; + Loggly: TransportInstance; + DailyRotateFile: TransportInstance; + Http: TransportInstance; + Memory: TransportInstance; + Webhook: TransportInstance; + } + + export interface TransportOptions { + level?: string; + silent?: boolean; + raw?: boolean; + name?: string; + handleExceptions?: boolean; + } + + export interface QueryOptions { + rows?: number; + limit?: number; + start?: number; + from?: Date; + until?: Date; + /** + * 'asc' or 'desc' + */ + order?: string; + fields: any; + } + + export interface ProfileHandler { + logger: LoggerInstance; + start: Date; + done: (msg: string) => LoggerInstance; + } } From 6370ba5a784e630b725527664813bb7965a006cf Mon Sep 17 00:00:00 2001 From: Jeff Fisher Date: Fri, 22 Aug 2014 14:12:30 -0700 Subject: [PATCH 110/149] Big update of WinJS definitions. Went through and did a large number of fixes as part of converting the WinJS test tree to TypeScript. Full list of changes: Fix small issue with WinJS.Promise.timeout. (The first argument should be optional.) Remove an unnecessary comment about winControl. Fix WinJS Promise types Make addEventListener and removeEventListener static. markDisposable's second argument is optional. WinJS.UI.Fragments.clearCache had a missing overload. Add missing overload for WinJS.UI.Fragments.renderCopy. WinJS.Class.define constructor parameter is optional. Add override for WinJS.log Message can also be a function that returns a string. Also add override for WinJS.Utilities.startLog All ILogOptions properties are optional. Make WinJS.log arguments optional. WinJS.Resources.processAll returns a Promise. Add WinJS.Utilities.Scheduler.currentPriority Make WinJS.Promise.wrap()'s argument optional. Make IXHROptions data property optional. Add CustomRequestInitializer to IXHROptions. Correct doc comment for WinJS.Application.*.writeText Fix declaration for static render on WinJS.Binding.Template. Add WinJS.Utilities.getTabIndex. Add overload for WinJS.Utilities.QueryCollection.include Fix WinJS.Utilities.getRelativeTop and getRelativeLeft parameters. Add getScrollPosition and setScrollPosition. Make BindingList.createGrouped last argument optional. Fix return type of WinJS.UI.computeDataSourceGroups() Add missing static createResultSuggestionImage to WinJS.UI.SearchBox. Add missing overload for WinJS.Binding.List.push() Add generic overload for IItemPromise.then() Fix the return value of IItemPromise.then to be correct. Promise.dispatchEvent should be static. Fix IItemPromise.retain return value. Create IPromise interface. This helps type coercion with custom promise types (such as IItemPromise). Add missing animations to latest d.ts. Update optional parameters on animations. Add BindingList.unshift overload Fix BindingList.sort() to have argument be optional. Fix arguments for BindingList.splice and BindingList.join Fix BindingList.lastIndexOf optional second argument. Fix return time of items in GroupedSortedListProjections. Make last argument of QueryCollection.template optional. Fix WinJS.UI.Repeater constructor. Fix the type of the second parameter of the WinJS.Binding.Template constructor Update WinJS.UI.ListLayout so that it implements ILayout2. Update WinJS.UI.GridLayout. Add static Promise.cancel property. Add type property to IListViewItem Make argument to Promise.as optional. Add AppBar.closedDisplayMode Make some arguments optional on Flyout.show() Make arguments optional on Menu.show(); Fix generic type of Hub.zoomableView. Add missing Promise.then overloads. Update author information Fix IPageControlMembers to reflect the real contract. TypeScript doesn't allow overrides to vary only by return type, so we have to use any as both void and returning a Promise are allowed. WinJS.UI.Pages.render()'s second argument is optional. WinJS.UI.Pages.render() returns a promise to the page itself. Fix return values of WinJS.UI.Pages.get/define. Add Pivot and PivotItem to latest d.ts. Fix PivotItem.header type --- winjs/winjs-1.0.d.ts | 298 ++++++++++++-------- winjs/winjs-2.0.d.ts | 342 +++++++++++++++-------- winjs/winjs-2.1.d.ts | 338 +++++++++++++++-------- winjs/winjs.d.ts | 634 +++++++++++++++++++++++++++++++++++-------- 4 files changed, 1138 insertions(+), 474 deletions(-) diff --git a/winjs/winjs-1.0.d.ts b/winjs/winjs-1.0.d.ts index 0952b03fe..7e46ed53f 100644 --- a/winjs/winjs-1.0.d.ts +++ b/winjs/winjs-1.0.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -362,6 +362,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -432,7 +438,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -539,7 +545,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -599,7 +605,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -607,7 +613,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -661,7 +667,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -714,6 +720,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -727,6 +734,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -934,30 +942,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?: any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1085,6 +1091,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1101,7 +1113,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1157,10 +1169,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1179,7 +1205,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1191,34 +1217,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1240,7 +1272,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1248,7 +1280,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1257,7 +1289,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1266,7 +1298,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1275,7 +1307,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1284,7 +1316,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1294,7 +1382,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1302,21 +1390,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1332,7 +1420,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: () => string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1356,8 +1445,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?: (request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1518,7 +1608,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1623,7 +1713,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1639,7 +1729,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1656,7 +1746,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1664,7 +1754,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1672,7 +1762,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1680,7 +1770,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1703,7 +1793,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1741,7 +1831,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1749,7 +1839,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1757,7 +1847,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Performs a deselection animation in response to a swipe interaction. @@ -1773,7 +1863,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1789,7 +1879,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; //#endregion Functions @@ -2244,32 +2334,10 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2278,16 +2346,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + retain(): IItemPromise; //#endregion Methods @@ -4608,7 +4667,7 @@ declare module WinJS.UI { * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; /** * Shows the specified commands of the Menu. @@ -5511,6 +5570,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -5577,9 +5643,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -5679,6 +5745,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -5695,6 +5762,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -5716,7 +5784,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -5724,14 +5792,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -5739,7 +5807,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -5747,7 +5815,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -5765,11 +5833,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } //#endregion Objects @@ -5781,14 +5844,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -5798,7 +5861,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -6362,6 +6425,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -6416,7 +6485,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -6537,7 +6606,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -6545,7 +6614,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -6663,6 +6732,7 @@ declare module WinJS.Utilities { * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -6691,10 +6761,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { diff --git a/winjs/winjs-2.0.d.ts b/winjs/winjs-2.0.d.ts index 205b41889..508973a50 100644 --- a/winjs/winjs-2.0.d.ts +++ b/winjs/winjs-2.0.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -372,6 +372,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -442,7 +448,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -549,7 +555,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -609,7 +615,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -617,7 +623,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -671,7 +677,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -724,6 +730,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -737,6 +744,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -944,30 +952,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?: any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1128,6 +1134,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1144,7 +1156,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1200,10 +1212,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1222,7 +1248,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1234,34 +1260,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1283,7 +1315,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1291,7 +1323,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1300,7 +1332,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1309,7 +1341,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1318,7 +1350,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1327,7 +1359,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1337,7 +1425,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1345,21 +1433,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1375,7 +1463,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: () => string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1399,8 +1488,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?: (request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1561,7 +1651,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1666,7 +1756,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1682,7 +1772,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1699,7 +1789,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1707,7 +1797,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1715,7 +1805,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1723,7 +1813,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1746,7 +1836,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1754,7 +1844,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function hidePanel(element: any, offset: any): Promise; + function hidePanel(element: any, offset?: any): Promise; /** * Performs an animation that removes pop-up user interface (UI). @@ -1784,7 +1874,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1792,7 +1882,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1800,7 +1890,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Performs a deselection animation in response to a swipe interaction. @@ -1816,7 +1906,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1832,7 +1922,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; //#endregion Functions @@ -2329,32 +2419,9 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events - + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2363,16 +2430,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + retain(): IItemPromise; //#endregion Methods @@ -3254,6 +3312,11 @@ declare module WinJS.UI { * Gets or sets whether the ListView item is focused and is showing its focus visual. **/ showFocus?: boolean; + + /** + * Gets the type, if any. + **/ + type?: WinJS.UI.ObjectType; } /** @@ -4264,7 +4327,7 @@ declare module WinJS.UI { * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; //#endregion Methods @@ -4350,6 +4413,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -4670,7 +4741,7 @@ declare module WinJS.UI { /** * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. **/ - zoomableView: IZoomableView; + zoomableView: IZoomableView; //#endregion Properties @@ -4919,6 +4990,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -5511,7 +5590,7 @@ declare module WinJS.UI { * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; /** * Shows the specified commands of the Menu. @@ -6136,9 +6215,10 @@ declare module WinJS.UI { /** * Creates a new Repeater control. * @constructor + * @param elemnt The DOM element that will host the new control. The Repeater will create an element if this value is null. * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". **/ - constructor(options?: any); + constructor(element?: HTMLElement, options?: any); //#endregion Constructors @@ -6411,6 +6491,8 @@ declare module WinJS.UI { //#endregion Properties + static createResultSuggestionImage(url: string): any; + } /** @@ -7110,6 +7192,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -7176,9 +7265,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -7278,6 +7367,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -7294,6 +7384,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -7315,7 +7406,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -7323,14 +7414,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -7338,7 +7429,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -7346,7 +7437,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -7364,11 +7455,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } //#endregion Objects @@ -7380,14 +7466,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -7397,7 +7483,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -7961,6 +8047,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -8015,7 +8107,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -8142,7 +8234,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -8150,7 +8242,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -8202,7 +8294,7 @@ declare module WinJS.Utilities { * @param element The element to mark as disposable. * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + function markDisposable(element: HTMLElement, disposeImpl?: Function): void; /** * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. @@ -8275,6 +8367,7 @@ declare module WinJS.Utilities { * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -8303,10 +8396,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { @@ -8470,6 +8563,15 @@ declare module WinJS.Utilities.Scheduler { //#endregion Interfaces + //#region Properties + + /** + * Gets the current priority at which the caller is executing. + **/ + var currentPriority: Priority; + + //#endregion Properties + //#region Functions /** diff --git a/winjs/winjs-2.1.d.ts b/winjs/winjs-2.1.d.ts index 66afeb69e..5c8f53641 100644 --- a/winjs/winjs-2.1.d.ts +++ b/winjs/winjs-2.1.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -378,6 +378,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -448,7 +454,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -555,7 +561,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -615,7 +621,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -623,7 +629,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -677,7 +683,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -730,6 +736,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -743,6 +750,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -950,30 +958,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?: any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1143,6 +1149,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1159,7 +1171,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1215,10 +1227,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1237,7 +1263,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1249,34 +1275,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1298,7 +1330,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1306,7 +1338,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1315,7 +1347,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1324,7 +1356,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1333,7 +1365,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1342,7 +1374,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1352,7 +1440,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1360,21 +1448,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1390,7 +1478,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: () => string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1414,8 +1503,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?: (request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1576,7 +1666,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1722,7 +1812,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1738,7 +1828,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1755,7 +1845,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1763,7 +1853,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1771,7 +1861,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1779,7 +1869,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1802,7 +1892,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1810,7 +1900,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function hidePanel(element: any, offset: any): Promise; + function hidePanel(element: any, offset?: any): Promise; /** * Performs an animation that removes pop-up user interface (UI). @@ -1840,7 +1930,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1848,7 +1938,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1856,7 +1946,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Slides elements off through the bottom of the screen. @@ -1926,7 +2016,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1971,7 +2061,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; //#endregion Functions @@ -2469,32 +2559,10 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2503,18 +2571,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; - - //#endregion Methods + retain(): IItemPromise; //#region Properties @@ -3394,6 +3451,11 @@ declare module WinJS.UI { * Gets or sets whether the ListView item is focused and is showing its focus visual. **/ showFocus?: boolean; + + /** + * Gets the type, if any. + **/ + type?: WinJS.UI.ObjectType; } /** @@ -4076,6 +4138,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -4462,6 +4532,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -5056,7 +5134,7 @@ declare module WinJS.UI { /** * Gets or sets the header for this PivotItem. **/ - header: HTMLElement; + header: string; //#endregion Properties } @@ -5070,9 +5148,10 @@ declare module WinJS.UI { /** * Creates a new Repeater control. * @constructor + * @param elemnt The DOM element that will host the new control. The Repeater will create an element if this value is null. * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". **/ - constructor(options?: any); + constructor(element?: HTMLElement, options?: any); //#endregion Constructors @@ -5544,6 +5623,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -5610,9 +5696,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -5719,6 +5805,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -5735,6 +5822,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -5756,7 +5844,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -5764,14 +5852,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -5779,7 +5867,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -5787,7 +5875,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -5805,12 +5893,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } - //#endregion Objects //#region Functions @@ -5821,14 +5903,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -5838,7 +5920,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -6402,6 +6484,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -6456,7 +6544,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -6583,7 +6671,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -6591,7 +6679,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -6643,7 +6731,7 @@ declare module WinJS.Utilities { * @param element The element to mark as disposable. * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + function markDisposable(element: HTMLElement, disposeImpl?: Function): void; /** * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. @@ -6716,6 +6804,7 @@ declare module WinJS.Utilities { * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -6749,10 +6838,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { @@ -6916,6 +7005,15 @@ declare module WinJS.Utilities.Scheduler { //#endregion Interfaces + //#region Properties + + /** + * Gets the current priority at which the caller is executing. + **/ + var currentPriority: Priority; + + //#endregion Properties + //#region Functions /** diff --git a/winjs/winjs.d.ts b/winjs/winjs.d.ts index 811e4893f..195ecb66e 100644 --- a/winjs/winjs.d.ts +++ b/winjs/winjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -372,6 +372,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -442,7 +448,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -549,7 +555,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -609,7 +615,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -617,7 +623,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -671,7 +677,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -724,6 +730,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -737,6 +744,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -944,30 +952,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?:any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1137,6 +1143,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1153,7 +1165,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1209,10 +1221,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1231,7 +1257,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1243,34 +1269,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1292,7 +1324,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1300,7 +1332,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1309,7 +1341,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1318,7 +1350,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1327,7 +1359,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1336,7 +1368,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1346,7 +1434,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1354,21 +1442,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1384,7 +1472,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: ()=>string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1408,8 +1497,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?:(request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1570,7 +1660,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1675,7 +1765,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1691,7 +1781,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1708,7 +1798,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1716,7 +1806,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1724,7 +1814,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1732,7 +1822,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1755,7 +1845,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1763,7 +1853,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function hidePanel(element: any, offset: any): Promise; + function hidePanel(element: any, offset?: any): Promise; /** * Performs an animation that removes pop-up user interface (UI). @@ -1793,7 +1883,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1801,7 +1891,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1809,7 +1899,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Performs a deselection animation in response to a swipe interaction. @@ -1825,7 +1915,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1841,7 +1931,122 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; + + /** + * Execute a slide up animation. + * @param incoming Single element or collection of elements to animate sliding up. + * @returns A Promise that completes when the animation is finished. + **/ + function slideUp(incoming: any): Promise; + + /** + * Execute a slide down animation. + * @param incoming Single element or collection of elements to animate sliding down. + * @returns A Promise that completes when the animation is finished. + **/ + function slideDown(incoming: any): Promise; + + /** + * Execute a slide in from right to left animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding in. + * @param second Second element or collection of elements to animate sliding in, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding in, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideLeftIn(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a slide out from right to left animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding out. + * @param second Second element or collection of elements to animate sliding out, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding out, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideLeftOut(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a slide in from left to right animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding in. + * @param second Second element or collection of elements to animate sliding in, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding in, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideRightIn(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a slide out from left to right animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding out. + * @param second Second element or collection of elements to animate sliding out, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding out, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideRightOut(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a continuum animation, scaling up the incoming page while scaling, rotating, and translating the incoming item. + * @param page Single element to be scaled up that is the page root and does not contain the incoming item. + * @param itemRoot Root of the item that will be translated as part of the continuum animation. + * @param itemContent Content of the item that will be scaled and rotated as part of the continuum animation. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumForwardIn(page: any, itemRoot: any, itemContent: any): Promise; + + /** + * Execute a continuum animation, scaling down the outgoing page while scaling, rotating, and translating the outgoing item. + * @param page Single element to be scaled down that is the page root and contains the outgoing item. + * @param item Single element to be scaled, rotated, and translated away from the outgoing page. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumForwardOut(page: any, item: any): Promise; + + /** + * Execute a continuum animation, scaling down the incoming page while scaling, rotating, and translating the incoming item. + * @param page Single element to be scaled down that is the page root and contains the incoming item. + * @param item Single element to be scaled, rotated, and translated into its final position on the page. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumBackwardIn(page: any, item: any): Promise; + + /** + * Execute a continuum animation, scaling down the outgoing page while. + * @param page Single element to be scaled down that is the page root. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumBackwardOut(page: any): Promise; + + /** + * Execute a turnstile forward in animation. + * @param incoming Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileForwardIn(incoming: any): Promise; + + /** + * Execute a turnstile forward out animation. + * @param outgoing Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileForwardOut(outgoing: any): Promise; + + /** + * Execute a turnstile backward in animation. + * @param incoming Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileBackwardIn(incoming: any): Promise; + + /** + * Execute a turnstile backward out animation. + * @param outgoing Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileBackwardOut(outgoing: any): Promise; + //#endregion Functions @@ -2338,32 +2543,10 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2372,16 +2555,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + retain(): IItemPromise; //#endregion Methods @@ -3263,6 +3437,11 @@ declare module WinJS.UI { * Gets or sets whether the ListView item is focused and is showing its focus visual. **/ showFocus?: boolean; + + /** + * Gets the type, if any. + **/ + type?: WinJS.UI.ObjectType; } /** @@ -3550,6 +3729,11 @@ declare module WinJS.UI { //#region Properties + /** + * Gets/Sets how AppBar will display itself while hidden. Values are "none" and "minimal". + **/ + closedDisplayMode: string; + /** * Sets the AppBarCommand objects that appear in the app bar. **/ @@ -4273,7 +4457,7 @@ declare module WinJS.UI { * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; //#endregion Methods @@ -4359,6 +4543,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -4679,7 +4871,7 @@ declare module WinJS.UI { /** * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. **/ - zoomableView: IZoomableView; + zoomableView: IZoomableView; //#endregion Properties @@ -4928,6 +5120,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -5428,6 +5628,157 @@ declare module WinJS.UI { } + /** + * A tab control that displays multiple items. +**/ + class Pivot { + //#region Constructors + + /** + * Creates a new Pivot. + * @constructor + * @param element The DOM element hosts the new Pivot. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when a PivotItem control's animation ends. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationend(eventInfo: Event): void; + + /** + * Raised when a PivotItem control's animation starts. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationstart(eventInfo: Event): void; + + /** + * Raised when the user navigates to a different PivotItem. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Pivot. Call this method when the Pivot is no longer needed. After calling this method, the Pivot becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Pivot control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Binding.List that contains the PivotItem objects that belong to this Pivot. + **/ + items: Binding.List; + + /** + * Gets or sets a value that specifies whether the Pivot control is locked to the current item. + **/ + locked: boolean; + + /** + * Gets or sets the index of the PivotItem control in view. + **/ + selectedIndex: number; + + /** + * Gets or sets the PivotItem control in view within the Pivot control. + **/ + selectedItem: PivotItem; + + /** + * Gets or sets the title displayed above the PivotItem controls. + **/ + title: string; + + //#endregion Properties + } + + /** + * An item within a Pivot control. + **/ + class PivotItem { + //#region Constructors + + /** + * Creates a new PivotItem. + * @constructor + * @param element The DOM element hosts the new PivotItem. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this PivotItem. Call this method when the PivotItem is no longer needed. After calling this method, the PivotItem becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the PivotItem control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the PivotItem control. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this PivotItem. + **/ + header: string; + + //#endregion Properties + } + /** * Represents a menu flyout for displaying commands. **/ @@ -5520,7 +5871,7 @@ declare module WinJS.UI { * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; /** * Shows the specified commands of the Menu. @@ -6145,9 +6496,10 @@ declare module WinJS.UI { /** * Creates a new Repeater control. * @constructor + * @param elemnt The DOM element that will host the new control. The Repeater will create an element if this value is null. * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". **/ - constructor(options?: any); + constructor(element?:HTMLElement, options?: any); //#endregion Constructors @@ -6420,6 +6772,8 @@ declare module WinJS.UI { //#endregion Properties + static createResultSuggestionImage(url: string): any; + } /** @@ -7119,6 +7473,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -7185,9 +7546,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -7294,6 +7655,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -7310,6 +7672,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -7331,7 +7694,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -7339,14 +7702,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -7354,7 +7717,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -7362,7 +7725,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -7380,12 +7743,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } - //#endregion Objects //#region Functions @@ -7396,14 +7753,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -7413,7 +7770,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -7977,6 +8334,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -8031,7 +8394,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -8158,7 +8521,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -8166,7 +8529,21 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; + + /** + * Gets the scrollLeft and scrollTop of the specified element, adjusting the scrollLeft to change from browser specific coordinates to logical coordinates when in RTL. + * @param element The element. + * @returns An object with two properties: scrollLeft and scrollTop + **/ + function getScrollPosition(element: HTMLElement): { scrollLeft: number; scrollTop: number}; + + /** + * Gets the tab index of the specified element. + * @param element The element + * @returns The tabIndex of the element. Returns -1 if the element cannot be tabbed to. + **/ + function getTabIndex(element: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -8218,7 +8595,7 @@ declare module WinJS.Utilities { * @param element The element to mark as disposable. * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + function markDisposable(element: HTMLElement, disposeImpl?: Function): void; /** * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. @@ -8286,11 +8663,19 @@ declare module WinJS.Utilities { **/ function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + /** + * Sets the scrollLeft and scrollTop of the specified element, changing the scrollLeft from logical coordinates to browser-specific coordinates when in RTL. + * @param element The element. + * @param position An object describing the position to set. + **/ + function setScrollPosition(element: HTMLElement, position: { scrollLeft: number; scrollTop: number}): void; + /** * Configures a logger that writes messages containing the specified tags to the JavaScript console. * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -8324,10 +8709,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { @@ -8491,6 +8876,15 @@ declare module WinJS.Utilities.Scheduler { //#endregion Interfaces + //#region Properties + + /** + * Gets the current priority at which the caller is executing. + **/ + var currentPriority: Priority; + + //#endregion Properties + //#region Functions /** From f8127f02237ae69960a27775a2b18f2fd7ff03ef Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 25 Sep 2014 01:13:47 +0100 Subject: [PATCH 111/149] Remove legacy node references The legacy node references have been removed to stop the global namespace being littered with old node definitions. --- winston/winston.d.ts | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/winston/winston.d.ts b/winston/winston.d.ts index c0e5a7a42..4cf5370ca 100644 --- a/winston/winston.d.ts +++ b/winston/winston.d.ts @@ -7,17 +7,6 @@ /// - -//////// Here for backwards compatibility to older Node definitions //////// -declare module NodeJS { - interface EventEmitter { } - interface ReadWriteStream { } -} - -interface NodeEventEmitter extends NodeJS.EventEmitter { } -interface ReadableStream extends NodeJS.ReadableStream { } -//////////////////////////////////////////////////////////////////////////// - declare module "winston" { export var transports: Transports; @@ -47,7 +36,7 @@ declare module "winston" { export function query(options: QueryOptions, callback?: (err: Error, results: any) => void): any; export function query(callback: (err: Error, results: any) => void): any; - export function stream(options?: any): ReadableStream; + export function stream(options?: any): NodeJS.ReadableStream; export function handleExceptions(...transports: TransportInstance[]): void; export function unhandleExceptions(...transports: TransportInstance[]): void; export function add(transport: TransportInstance, options?: TransportOptions, created?: boolean): LoggerInstance; @@ -63,7 +52,7 @@ declare module "winston" { new (options?: LoggerOptions); } - export interface LoggerInstance extends NodeEventEmitter { + export interface LoggerInstance extends NodeJS.EventEmitter { extend(target: any): LoggerInstance; log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; @@ -83,7 +72,7 @@ declare module "winston" { query(options: QueryOptions, callback?: (err: Error, results: any) => void): any; query(callback: (err: Error, results: any) => void): any; - stream(options?: any): ReadableStream; + stream(options?: any): NodeJS.ReadableStream; close(): void; handleExceptions(...transports: TransportInstance[]): void; unhandleExceptions(...transports: TransportInstance[]): void; @@ -114,7 +103,7 @@ declare module "winston" { new (options?: TransportOptions): TransportInstance; } - export interface TransportInstance extends TransportStatic, NodeEventEmitter { + export interface TransportInstance extends TransportStatic, NodeJS.EventEmitter { formatQuery(query: any): any; normalizeQuery(options: QueryOptions): QueryOptions; formatResults(results: any, options: any): any; From 0e05ddf68ee5df0109c616a484d437857a572ac9 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 25 Sep 2014 01:40:38 +0100 Subject: [PATCH 112/149] Update header info Add Carlos Ballesteros Velasco back into "Definitions by" header line. --- swig/swig.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index 4626fb9b9..4f2b22123 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -1,6 +1,6 @@ // Type definitions for swig // Project: http://github.com/paularmstrong/swig -// Definitions by: Peter Harris +// Definitions by: Peter Harris , Carlos Ballesteros Velasco // Definitions: https://github.com/borisyankov/DefinitelyTyped // API Documentation : http://paularmstrong.github.io/swig/docs/api/ From 9ca7d3f75700e9502ce8724684e4aa7fa30f6b36 Mon Sep 17 00:00:00 2001 From: Georgie Date: Wed, 24 Sep 2014 18:31:26 -0700 Subject: [PATCH 113/149] Changed SelectedCell back to VisualizationSelectionArray --- google.visualization/google.visualization.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index eb2d49469..d9d53ab2b 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -438,15 +438,15 @@ declare module google { groupWidth: any; // number | string } - export interface SelectedCell { + export interface VisualizationSelectionArray { column?: number; row?: number; } class ChartBase { constructor(element: Element); - getSelection(): SelectedCell[]; - setSelection(selection: SelectedCell[]): void; + getSelection(): VisualizationSelectionArray[]; + setSelection(selection: VisualizationSelectionArray[]): void; clearChart(): void; getImageURI(): string; } From de37f2dbbf86dc3c39ac8309cba8c16f40f47d4a Mon Sep 17 00:00:00 2001 From: Punyashloka Biswal Date: Tue, 23 Sep 2014 12:09:27 -0400 Subject: [PATCH 114/149] More precise type for $routeProvider.resolve --- angularjs/angular-route.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index ba6d0aac9..a71299e25 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -75,7 +75,7 @@ declare module ng.route { * - key - {string}: a name of a dependency to be injected into the controller. * - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead. */ - resolve?: any; + resolve?: {[key: string]: any}; /** * {(string|function())=} * Value to update $location path with and trigger route redirection. From f2b7b66b3e46ac2bcb24ffd2726cc55a0d8732d7 Mon Sep 17 00:00:00 2001 From: Adi Dahiya Date: Thu, 25 Sep 2014 12:25:02 -0400 Subject: [PATCH 115/149] Update interact.js typings to 1.0.25 --- interactjs/interact-tests.ts | 3 ++- interactjs/interact.d.ts | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/interactjs/interact-tests.ts b/interactjs/interact-tests.ts index e658f1275..b57a02c97 100644 --- a/interactjs/interact-tests.ts +++ b/interactjs/interact-tests.ts @@ -103,5 +103,6 @@ interact.deltaSource("page"); interact.restrict({ "drag": rectangle, "resize": rectangle, - "gesture": rectangle + "gesture": rectangle, + "elementRect": { top: 0, left: 0, bottom: 1, right: 1 } }); diff --git a/interactjs/interact.d.ts b/interactjs/interact.d.ts index 8189d6415..1ad864607 100644 --- a/interactjs/interact.d.ts +++ b/interactjs/interact.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Interacting for interact.js v1.0.17 +// Type definitions for Interacting for interact.js v1.0.25 // Project: https://github.com/taye/interact.js -// Definitions by: Douglas Eichelberger -// Definitions: https://github.com/borisyankov/DefinitelyType +// Definitions by: Douglas Eichelberger , Adi Dahiya +// Definitions: https://github.com/borisyankov/DefinitelyTyped // API documentation: http://interactjs.io/docs @@ -157,6 +157,7 @@ interface Restrict { drag?: any; gesture?: any; resize?: any; + elementRect?: {[direction: string]: number}; } interface InteractEvent { From 9f319d3c5b2e348283554aeb0832d56500544f4e Mon Sep 17 00:00:00 2001 From: Arkadiusz Filipczak Date: Fri, 26 Sep 2014 06:43:14 +0200 Subject: [PATCH 116/149] DbCreateOptions' w property should accept numbers --- mongodb/mongodb.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 05f71d20a..ce79324ec 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -178,7 +178,7 @@ declare module "mongodb" { // Current definition by documentation version 1.3.13 (28.08.2013) export interface DbCreateOptions { // the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = ‘majority’ or tag acknowledges the write. - w?: string; + w?: any; // set the timeout for waiting for write concern to finish (combines with w option). wtimeout?: number; From 3cc0a3ec6b9f323a5ef9148929652b9d4e3f000e Mon Sep 17 00:00:00 2001 From: Arkadiusz Filipczak Date: Fri, 26 Sep 2014 06:43:54 +0200 Subject: [PATCH 117/149] fixed typo readPreference(s) --- mongodb/mongodb.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index ce79324ec..83724c318 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -272,11 +272,11 @@ declare module "mongodb" { update(selector: Object, document: any, options: { safe?: boolean; upsert?: any; multi?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; distinct(key: string, query: Object, callback: (err: Error, result: any) => void): void; - distinct(key: string, query: Object, options: { readPreferences: string; }, callback: (err: Error, result: any) => void): void; + distinct(key: string, query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; count(callback: (err: Error, result: any) => void): void; count(query: Object, callback: (err: Error, result: any) => void): void; - count(query: Object, options: { readPreferences: string; }, callback: (err: Error, result: any) => void): void; + count(query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; drop(callback?: (err: Error, result: any) => void): void; @@ -429,7 +429,7 @@ declare module "mongodb" { showDiskLoc?: boolean; comment?: String; raw?: boolean; - readPreferences?: String; + readPreference?: String; partial?: boolean; } @@ -438,6 +438,6 @@ declare module "mongodb" { serializeFunctions?: any; raw?: boolean; pkFactory?: any; - readPreferences?: string; + readPreference?: string; } } From 880c9e258bb50e5febf7aea651ad15aa75a221d8 Mon Sep 17 00:00:00 2001 From: progre Date: Sat, 27 Sep 2014 11:21:39 +0900 Subject: [PATCH 118/149] fix: gulp don't pass compile2 pattern --- gulp/gulp-tests.ts | 10 +++++++++- gulp/gulp.d.ts | 9 ++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/gulp/gulp-tests.ts b/gulp/gulp-tests.ts index 50ebeebf0..0ba2d93d8 100644 --- a/gulp/gulp-tests.ts +++ b/gulp/gulp-tests.ts @@ -12,7 +12,15 @@ gulp.task('compile', function() .dest('out') }); -gulp.task('test', ['compile'], function() +gulp.task('compile2', function(callback: (err?: any) => void) +{ + gulp.src("**/*.ts") + .pipe(typescript) + .dest('out') + .on('end', callback); +}); + +gulp.task('test', ['compile', 'compile2'], function() { gulp.src("out/test/**/*.js") .pipe(jasmine); diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index d12c3edc1..25aa16337 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -173,15 +173,10 @@ declare module gulp { interface ITaskCallback { /** * Defines a task. - * Tasks may be made asynchronous if they return a promise or a stream. - */ - (): any; - - /** - * Defines an asynchronous task. + * Tasks may be made asynchronous if they are passing a callback or return a promise or a stream. * @param cb callback used to signal asynchronous completion. Caller includes err in case of error. */ - (cb:(err?:any)=>void): void; + (cb?:(err?:any)=>void): any; } interface EventEmitter { From 501792ee1374ebda22da12e035e1d46c1304c221 Mon Sep 17 00:00:00 2001 From: progre Date: Sat, 27 Sep 2014 11:57:45 +0900 Subject: [PATCH 119/149] add IGulpPlugin and fix tests --- gulp/gulp-tests.ts | 14 +++++++------- gulp/gulp.d.ts | 4 ++++ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/gulp/gulp-tests.ts b/gulp/gulp-tests.ts index 0ba2d93d8..7e07f25f7 100644 --- a/gulp/gulp-tests.ts +++ b/gulp/gulp-tests.ts @@ -2,28 +2,28 @@ import gulp = require("gulp"); -var typescript: any = null; // this would be the TypeScript compiler -var jasmine: any = null; // this would be the jasmine test runner +var typescript: IGulpPlugin = null; // this would be the TypeScript compiler +var jasmine: IGulpPlugin = null; // this would be the jasmine test runner gulp.task('compile', function() { gulp.src("**/*.ts") - .pipe(typescript) - .dest('out') + .pipe(typescript()) + .pipe(gulp.dest('out')) }); gulp.task('compile2', function(callback: (err?: any) => void) { gulp.src("**/*.ts") - .pipe(typescript) - .dest('out') + .pipe(typescript()) + .pipe(gulp.dest('out')) .on('end', callback); }); gulp.task('test', ['compile', 'compile2'], function() { gulp.src("out/test/**/*.js") - .pipe(jasmine); + .pipe(jasmine()); }); gulp.task('default', ['compile', 'test']); diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 25aa16337..7ec11def7 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -282,3 +282,7 @@ declare module "gulp" { var _tmp:gulp.Gulp; export = _tmp; } + +interface IGulpPlugin { + (...args: any[]): NodeJS.ReadWriteStream; +} From f2815732244615f26623e789173293b264a47246 Mon Sep 17 00:00:00 2001 From: Steve <_steve_@outlook.com> Date: Sat, 27 Sep 2014 10:48:55 +0200 Subject: [PATCH 120/149] node.d.ts support object type for Url.query --- node/node-tests.ts | 8 ++++++++ node/node.d.ts | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index e9ef58dbb..a8475a8dc 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -59,6 +59,10 @@ class Networker extends events.EventEmitter { } } +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + url.format(url.parse('http://www.example.com/xyz')); // https://google.com/search?q=you're%20a%20lizard%2C%20gary @@ -69,6 +73,10 @@ url.format({ query: { q: "you're a lizard, gary" } }); +var helloUrl = url.parse('http://example.com/?hello=world', true) +assert.equal(helloUrl.query.hello, 'world'); + + // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); diff --git a/node/node.d.ts b/node/node.d.ts index 4140a8c4b..7893f6fc6 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -658,7 +658,7 @@ declare module "url" { host: string; pathname: string; search: string; - query: string; + query: any; // string | Object slashes: boolean; hash?: string; path?: string; From ef080f1782406829ab94561d751e3b66604ec1c2 Mon Sep 17 00:00:00 2001 From: AdaskoTheBeAsT Date: Sat, 27 Sep 2014 13:59:35 +0200 Subject: [PATCH 121/149] Changed signature of functions: search, redraw_node Changed signature of functions: search, redraw_node --- jstree/jstree-tests.ts | 6 ++++++ jstree/jstree.d.ts | 21 ++++++++++++++------- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/jstree/jstree-tests.ts b/jstree/jstree-tests.ts index ce8280721..aa834e621 100644 --- a/jstree/jstree-tests.ts +++ b/jstree/jstree-tests.ts @@ -69,6 +69,12 @@ var advancedTree = $("#briefcasetree").jstree({ var a = $('a').jstree(); +// test search node +a.search('test', false, true); + +//test redraw node +a.redraw_node($('#node1'), false, false, false); + //tree with new unique plugin parameters var treeWithUnique = $('#treeWithUnique').jstree({ diff --git a/jstree/jstree.d.ts b/jstree/jstree.d.ts index 10eff8d75..f6cc14069 100644 --- a/jstree/jstree.d.ts +++ b/jstree/jstree.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jsTree v3.0.3 +// Type definitions for jsTree v3.0.4 // Project: http://www.jstree.com/ // Definitions by: Adam Pluciński // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -555,10 +555,9 @@ interface JSTreeStaticDefaultsSearch { case_sensitive: boolean; /** - * Indicates if the tree should be filtered to show only matching nodes - * (keep in mind this can be a heavy on large trees in old browsers). Default is `false`. - * @name $.jstree.defaults.search.show_only_matches - * @plugin search + * Indicates if the tree should be filtered (by default) to show only matching nodes + * (keep in mind this can be a heavy on large trees in old browsers). + * This setting can be changed at runtime when calling the search method. Default is `false`. */ show_only_matches: boolean; @@ -1183,8 +1182,15 @@ interface JSTree extends JQuery { show_icon: (obj: any) => void; /** + * redraws a single node. Used internally. + * @private + * @name redraw_node(node, deep, is_callback) + * @param {mixed} node the node to redraw + * @param {Boolean} deep should child nodes be redrawn too + * @param {Boolean} is_callback is this a recursion call + * @param {Boolean} force_render should children of closed parents be drawn anyway */ - redraw_node: (obj: any, deep: boolean, is_callback: boolean) => any; + redraw_node: (obj: any, deep?: boolean, is_callback?: boolean, force_render?: boolean) => any; /** * show the node checkbox icons @@ -1308,10 +1314,11 @@ interface JSTree extends JQuery { * @name search(str [, skip_async]) * @param {String} str the search string * @param {Boolean} skip_async if set to true server will not be queried even if configured + * @param {Boolean} show_only_matches if set to true only matching nodes will be shown (keep in mind this can be very slow on large trees or old browsers) * @plugin search * @trigger search.jstree */ - search: (str: string, skip_async?: boolean) => void; + search: (str: string, skip_async?: boolean, show_only_matches?: boolean) => void; /** * used to clear the last search (removes classes and shows all nodes if filtering is on) From 53ddc41a4b71d9dd78fedc64f80ee7defde54966 Mon Sep 17 00:00:00 2001 From: AdaskoTheBeAsT Date: Sat, 27 Sep 2014 14:03:34 +0200 Subject: [PATCH 122/149] Changed signature of functions: search, redraw_node. Comments fixed. Changed signature of functions: search, redraw_node. Comments fixed. --- jstree/jstree.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jstree/jstree.d.ts b/jstree/jstree.d.ts index f6cc14069..28297e555 100644 --- a/jstree/jstree.d.ts +++ b/jstree/jstree.d.ts @@ -558,6 +558,8 @@ interface JSTreeStaticDefaultsSearch { * Indicates if the tree should be filtered (by default) to show only matching nodes * (keep in mind this can be a heavy on large trees in old browsers). * This setting can be changed at runtime when calling the search method. Default is `false`. + * @name $.jstree.defaults.search.show_only_matches + * @plugin search */ show_only_matches: boolean; From 4393f0f09f1533c97827671e8d65c164696f2c27 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Sat, 27 Sep 2014 17:25:03 +0100 Subject: [PATCH 123/149] Update NodeBuffer to use Buffer Update NodeBuffer references to use Buffer, as NodeBuffer is deprecated. --- radius/radius-tests.ts | 5 +++-- radius/radius.d.ts | 12 ++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/radius/radius-tests.ts b/radius/radius-tests.ts index 5d06d2fcb..2ce4d2c0d 100644 --- a/radius/radius-tests.ts +++ b/radius/radius-tests.ts @@ -1,11 +1,12 @@ /// +/// import radius = require('radius'); var radius_secret: string = "shhhh" radius.add_dictionary("./"); -var encodedPacket: NodeBuffer = radius.encode({ +var encodedPacket: Buffer = radius.encode({ code: "Access-Request", secret: radius_secret, attributes: { @@ -20,7 +21,7 @@ var radiusPacket: radius.RadiusPacket = radius.decode({ secret: radius_secret }); -var response: NodeBuffer; +var response: Buffer; if (radiusPacket.attributes["User-Name"] == "me" && radiusPacket.attributes["User-Password"] == "its-a-secret") { response = radius.encode_response({ diff --git a/radius/radius.d.ts b/radius/radius.d.ts index b1079fafd..346b7b487 100644 --- a/radius/radius.d.ts +++ b/radius/radius.d.ts @@ -3,7 +3,7 @@ // Definitions by: Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface NodeBuffer { } +/// declare module "radius" { /** @@ -19,12 +19,12 @@ declare module "radius" { /** * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. **/ - export function encode(args: EncodeArgs): NodeBuffer; + export function encode(args: EncodeArgs): Buffer; /** * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. **/ - export function encode_response(args: EncodeResponseArgs): NodeBuffer; + export function encode_response(args: EncodeResponseArgs): Buffer; /** * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. @@ -49,7 +49,7 @@ declare module "radius" { * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. **/ interface DecodeArgs { - packet: NodeBuffer; + packet: Buffer; } /** @@ -91,8 +91,8 @@ declare module "radius" { * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. **/ interface VerifyResponseArgs { - request: NodeBuffer; - response: NodeBuffer; + request: Buffer; + response: Buffer; secret: string; } From 161395bce8a735fe7bcfc6517cf636780192b885 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Sat, 27 Sep 2014 18:19:07 +0100 Subject: [PATCH 124/149] Add precise definitions and tests. --- precise/precise-tests.ts | 9 +++++++++ precise/precise.d.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 precise/precise-tests.ts create mode 100644 precise/precise.d.ts diff --git a/precise/precise-tests.ts b/precise/precise-tests.ts new file mode 100644 index 000000000..029a69a3e --- /dev/null +++ b/precise/precise-tests.ts @@ -0,0 +1,9 @@ +/// + +import precise = require("precise"); + +var timer = precise().start(); + +setTimeout(function () { + console.log(timer.stop().diff()); +}, 1000); \ No newline at end of file diff --git a/precise/precise.d.ts b/precise/precise.d.ts new file mode 100644 index 000000000..3caba0297 --- /dev/null +++ b/precise/precise.d.ts @@ -0,0 +1,34 @@ +// Type definitions for precise +// Project: https://github.com/avoidwork/precise +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "precise" { + /** + * Precise factory + */ + function _precise(): _precise.Precise; + + module _precise { + class Precise { + constructor(); + + /** + * Starts a timer + */ + start(): Precise; + + /** + * Stops a timer + */ + stop(): Precise; + + /** + * Returns the nanoseconds from `start()` to `stop()` + */ + diff(): number; + } + } + + export = _precise; +} \ No newline at end of file From 1e386438ff5b2c4c3ccfea32c78a88d3b32d0abb Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Sat, 27 Sep 2014 21:16:12 +0100 Subject: [PATCH 125/149] Add bcrypt definitions and tests. --- bcrypt/bcrypt-tests.ts | 34 ++++++++++++++++++++++ bcrypt/bcrypt.d.ts | 65 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 bcrypt/bcrypt-tests.ts create mode 100644 bcrypt/bcrypt.d.ts diff --git a/bcrypt/bcrypt-tests.ts b/bcrypt/bcrypt-tests.ts new file mode 100644 index 000000000..b88d4fb7a --- /dev/null +++ b/bcrypt/bcrypt-tests.ts @@ -0,0 +1,34 @@ +/// + +import bcrypt = require("bcrypt"); + +var num: number; +var str: string; +var bool: boolean; + +str = bcrypt.genSaltSync(); +str = bcrypt.genSaltSync(num); + +bcrypt.genSalt(function (err: Error, salt: string): void { + str = salt; +}); +bcrypt.genSalt(num, function (err: Error, salt: string): void { + str = salt; +}); + +str = bcrypt.hashSync(str, str); +str = bcrypt.hashSync(str, num); + +bcrypt.hash(str, str, function (err: Error, encrypted: string):void { + str = encrypted; +}) +bcrypt.hash(str, num, function (err: Error, encrypted: string): void { + str = encrypted; +}); + +bool = bcrypt.compareSync(str, str); +bcrypt.compare(str, str, function (err: Error, same: boolean): void { + bool = same; +}); + +num = bcrypt.getRounds(str); \ No newline at end of file diff --git a/bcrypt/bcrypt.d.ts b/bcrypt/bcrypt.d.ts new file mode 100644 index 000000000..dd3c92c2b --- /dev/null +++ b/bcrypt/bcrypt.d.ts @@ -0,0 +1,65 @@ +// Type definitions for bcrypt +// Project: https://github.com/ncb000gt/node.bcrypt.js +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "bcrypt" { + /** + * @param rounds The cost of processing the data. Default 10. + */ + export function genSaltSync(rounds?: number): string; + + /** + * @param rounds The cost of processing the data. Default 10. + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ + export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; + /** + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ + export function genSalt(callback: (err: Error, salt: string) => void): void; + + /** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + */ + export function hashSync(data: any, salt: string): string; + /** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + */ + export function hashSync(data: any, rounds: number): string; + + /** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ + export function hash(data: any, salt: string, callback: (err: Error, encrypted: string) => void): void; + /** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ + export function hash(data: any, rounds: number, callback: (err: Error, encrypted: string) => void): void; + + /** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + */ + export function compareSync(data: any, encrypted: string): boolean; + + /** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + * @param callback A callback to be fire once the data has been compared. Uses eio making it asynchronous. + */ + export function compare(data: any, encrypted: string, callback: (err: Error, same: boolean) => void): void; + + /** + * Return the number of rounds used to encrypt a given hash + * + * @param encrypted Hash from which the number of rounds used should be extracted. + */ + export function getRounds(encrypted: string): number; +} \ No newline at end of file From b23ce3c58ab5799b2bb1004923663ea142cdff0a Mon Sep 17 00:00:00 2001 From: Quenio dos Santos Date: Sat, 27 Sep 2014 21:26:18 -0300 Subject: [PATCH 126/149] Setting optional value --- mongoose/mongoose.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index e9057abc7..abfd5625e 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -153,7 +153,7 @@ declare module "mongoose" { findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; From 10e63d9361dbdca0ed9f8cfb095165bce1a053e0 Mon Sep 17 00:00:00 2001 From: Mark Overholt Date: Sat, 27 Sep 2014 19:53:55 -0700 Subject: [PATCH 127/149] Add initial commit for CanvasJS Typin and test --- CONTRIBUTORS.md | 3 +- canvasjs/canvasjs-tests.ts | 248 ++++++++++ canvasjs/canvasjs.d.ts | 959 +++++++++++++++++++++++++++++++++++++ 3 files changed, 1209 insertions(+), 1 deletion(-) create mode 100644 canvasjs/canvasjs-tests.ts create mode 100644 canvasjs/canvasjs.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c41f9afed..4a860113c 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,4 +1,4 @@ -# Contributors +# Contributors This is a non-exhaustive list of definitions and their creators. If you created a definition but are not listed then feel free to send a pull request on this file with your name and url. @@ -48,6 +48,7 @@ All definitions files include a header with the author and editors, so at some p * [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) * [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) +* [CanvasJS](http://canvasjs.com) (by [Mark Overholt](https://github.com/mover5)) * [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) * [Chroma.js](https://github.com/gka/chroma.js) (by [Sebastian Brückner](https://github.com/invliD)) diff --git a/canvasjs/canvasjs-tests.ts b/canvasjs/canvasjs-tests.ts new file mode 100644 index 000000000..09b309f5e --- /dev/null +++ b/canvasjs/canvasjs-tests.ts @@ -0,0 +1,248 @@ +/// + +module CanvasJS.Tests { + // Column Chart + var columnChart = new CanvasJS.Chart("chartContainer", + { + title: { + text: "Top Oil Reserves", + }, + axisY: { + title: "Reserves(MMbbl)" + }, + legend: { + verticalAlign: "bottom", + horizontalAlign: "center" + }, + theme: "theme2", + data: [ + { + type: "column", + showInLegend: true, + legendMarkerColor: "grey", + legendText: "MMbbl = one million barrels", + dataPoints: [ + { y: 297571, label: "Venezuela" }, + { y: 267017, label: "Saudi" }, + { y: 175200, label: "Canada" }, + { y: 154580, label: "Iran" }, + { y: 116000, label: "Russia" }, + { y: 97800, label: "UAE" }, + { y: 20682, label: "US" }, + { y: 20350, label: "China" } + ] + } + ] + }); + columnChart.render(); + + // Line Chart + var lineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Earthquakes - per month" + }, + axisX: { + valueFormatString: "MMM", + interval: 1, + intervalType: "month" + + }, + axisY: { + includeZero: false + + }, + data: [ + { + type: "line", + //lineThickness: 3, + dataPoints: [ + { x: new Date(2012, 0, 1), y: 450 }, + { x: new Date(2012, 1, 1), y: 414 }, + { x: new Date(2012, 2, 1), y: 520, indexLabel: "highest", markerColor: "red", markerType: "triangle" }, + { x: new Date(2012, 3, 1), y: 460 }, + { x: new Date(2012, 4, 1), y: 450 }, + { x: new Date(2012, 5, 1), y: 500 }, + { x: new Date(2012, 6, 1), y: 480 }, + { x: new Date(2012, 7, 1), y: 480 }, + { x: new Date(2012, 8, 1), y: 410, indexLabel: "lowest", markerColor: "DarkSlateGrey", markerType: "cross" }, + { x: new Date(2012, 9, 1), y: 500 }, + { x: new Date(2012, 10, 1), y: 480 }, + { x: new Date(2012, 11, 1), y: 510 } + + ] + } + + + ] + }); + lineChart.render(); + + // Spline Chart + var splineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Game of Thrones, Viewers of the first airing on HBO" + }, + axisY: { + includeZero: false, + // suffix: " k", + valueFormatString: "#,,.", + suffix: " mn" + }, + toolTip: { + shared: true + }, + data: [ + { + type: "spline", + showInLegend: true, + name: "Season 2", + // markerSize: 0, + // color: "rgba(54,158,173,.6)", + dataPoints: [ + { label: "Ep. 1", y: 3858000 }, + { label: "Ep. 2", y: 3759000 }, + { label: "Ep. 3", y: 3766000 }, + { label: "Ep. 4", y: 3654000 }, + { label: "Ep. 5", y: 3903000 }, + { label: "Ep. 6", y: 3879000 }, + { label: "Ep. 7", y: 3694000 }, + { label: "Ep. 8", y: 3864000 }, + { label: "Ep. 9", y: 3384000 }, + { label: "Ep. 10", y: 4200000 } + + ] + }, + { + type: "spline", + showInLegend: true, + // markerSize: 0, + name: "Season 1", + dataPoints: [ + { label: "Ep. 1", y: 2220000 }, + { label: "Ep. 2", y: 2200000 }, + { label: "Ep. 3", y: 2440000 }, + { label: "Ep. 4", y: 2450000 }, + { label: "Ep. 5", y: 2580000 }, + { label: "Ep. 6", y: 2440000 }, + { label: "Ep. 7", y: 2400000 }, + { label: "Ep. 8", y: 2720000 }, + { label: "Ep. 9", y: 2660000 }, + { label: "Ep. 10", y: 3040000 } + + ] + } + ], + legend: { + cursor: "pointer", + itemclick: function (e) { + if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { + e.dataSeries.visible = false; + } + else { + e.dataSeries.visible = true; + } + splineChart.render(); + } + + }, + }); + splineChart.render(); + + // Bar Chart + var barChart = new CanvasJS.Chart("chartContainer", { + + title: { + text: "Fortune Global 500 Companies by Country" + }, + axisX: { + interval: 1, + gridThickness: 0, + labelFontSize: 10, + labelFontStyle: "normal", + labelFontWeight: "normal", + labelFontFamily: "Lucida Sans Unicode" + }, + axisY: { + interlacedColor: "rgba(1,77,101,.2)", + gridColor: "rgba(1,77,101,.1)" + }, + data: [ + { + type: "bar", + name: "companies", + axisYType: "secondary", + color: "#014D65", + dataPoints: [ + { y: 5, label: "Sweden" }, + { y: 6, label: "Taiwan" }, + { y: 7, label: "Russia" }, + { y: 8, label: "Spain" }, + { y: 8, label: "Brazil" }, + { y: 8, label: "India" }, + { y: 9, label: "Italy" }, + { y: 9, label: "Australia" }, + { y: 12, label: "Canada" }, + { y: 13, label: "South Korea" }, + { y: 13, label: "Netherlands" }, + { y: 15, label: "Switzerland" }, + { y: 28, label: "Britain" }, + { y: 32, label: "Germany" }, + { y: 32, label: "France" }, + { y: 68, label: "Japan" }, + { y: 73, label: "China" }, + { y: 132, label: "US" } + ] + } + ] + }); + barChart.render(); + + // Pie Chart + var pieChart = new CanvasJS.Chart("chartContainer", + { + title: { + text: "Desktop Search Engine Market Share, Dec-2012" + }, + legend: { + verticalAlign: "center", + horizontalAlign: "left", + fontSize: 20, + fontFamily: "Helvetica" + }, + theme: "theme2", + data: [ + { + type: "pie", + indexLabelFontFamily: "Garamond", + indexLabelFontSize: 20, + indexLabel: "{label} {y}%", + startAngle: -20, + showInLegend: true, + toolTipContent: "{legendText} {y}%", + dataPoints: [ + { y: 83.24, legendText: "Google", label: "Google" }, + { y: 8.16, legendText: "Yahoo!", label: "Yahoo!" }, + { y: 4.67, legendText: "Bing", label: "Bing" }, + { y: 1.67, legendText: "Baidu", label: "Baidu" }, + { y: 0.98, legendText: "Others", label: "Others" } + ] + } + ] + }); + pieChart.render(); + + addColorSet("MyColorSet", [ + "123456", + "blue", + "red", + "orange" + ]); + + addCultureInfo("js", { + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + }); +} \ No newline at end of file diff --git a/canvasjs/canvasjs.d.ts b/canvasjs/canvasjs.d.ts new file mode 100644 index 000000000..f572ce329 --- /dev/null +++ b/canvasjs/canvasjs.d.ts @@ -0,0 +1,959 @@ +// Type definitions for CanvasJS v1.5.1 GA +// Project: http://canvasjs.com/ +// Definitions by: Mark Overholt +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module CanvasJS { + class Chart { + + /** + * The current options of the chart. + */ + options: ChartOptions; + + /** + * Initializes a new instance of CanvasJS Chart. + * @param containerId the DOM ID of the location where the chart is to be rendered + * @param options the options used to render the chart + */ + constructor(containerId: string, options?: ChartOptions); + + /** + * Renders the chart. + * @param options an optional set of options that will override the constructed values. + */ + render(options?: ChartOptions): void; + } + + /** + * Adds a new chart color set + * @param the name of the color set + * @param an array of colors. + */ + function addColorSet(colorSetName: string, colorSetArray: string[]): void; + + + /** + * Adds a new culture info for your chart + * @param culture the name of the culture + * @param the information used by this culture + */ + function addCultureInfo(culture: string, info: CultureInfo): void; + + interface CultureInfo { + /** + * Character used to separate fractional part from the whole number. + */ + decimalSeparator?: string; + /** + * Also referred to as Thousand Separator + */ + digitGroupSeparator?: string; + /** + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + */ + zoomText?: string; + /** + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + */ + panText?: string; + /** + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + */ + resetText?: string; + /** + * Set text is shown instead of Save as PNG. + */ + savePNGText?: string; + /** + * Set text is shown instead of Save as JPG. + */ + saveJPGText?: string; + /** + * Tool Tip for Menu Button. + */ + menuText?: string; + /** + * Day names starting from Sunday. Should be exactly 7 in total. + */ + days?: string[]; + /** + * Short Day names starting from Sunday. Should be exactly 7 in total. + */ + shortDays?: string[]; + /** + * Month Names starting from January + */ + months?: string[]; + /** + * Short Month Names starting from January + */ + shortMonths?: string[]; + } + + interface ChartOptions { + /** + * Enables / Disables Chart interactivity like toolTip, mouse and touch events + * Default: true + * Example: false, true + */ + interactivityEnabled?: boolean; + /** + * Enables Animation while rendering the Chart. + * Default: true + * Example: false, true + */ + animationEnabled?: boolean; + /** + * While exporting any chart, “Chart” is used as the default fine name with corresponding extension “jpg” or “png”. You can override this name using exportFileName property. + * Default: Chart + */ + exportFileName?: string; + /** + * Setting exportEnabled to true enables the export feature. As of now JPG & PNG formats are supported. Export feature is available in all Chart Types. + * Default: false + * Options: true, false + */ + exportEnabled?: boolean; + /** + * Setting zoomEnabled to true enables zooming and panning feature of Chart. This way you can zoom into an area of interest when there is a large amount of data. This will also allow you to pan through the chart. If not set, the property is automatically enabled for large number of dataPoints. You can switch between zooming & panning using the toolbar that appears on the chart. After Zooming in, you can reset the chart by clicking the reset button. + * Default: false + * Options: true, false + */ + zoomEnabled?: boolean; + /** + * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. + * Default: “theme1″ + * Options: “theme1″,”theme2″, “theme3″ + */ + theme?: string; + /** + * Sets the background color of entire Chart Area. Values can be “HTML Color Name”, “hex code” or “rgba values” + * Default: “white” + * Example: “yellow”, “#F5DEB3″.. + */ + backgroundColor?: string; + /** + * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. You can either choose from the pre-defined Color Sets or define your own Color Set. + * Default: “colorset1″ or as defined in the selected theme + * Example: “colorSet1″, “colorSet2″, “colorSet3″ + */ + colorSet?: string; + /** + * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). By default CanvasJS is set to Neutral English Culture – “en”. + * Default: “en” + */ + culture?: string; + /** + * Sets the width of the Chart. + * Default: Takes chart container’s width by default. If the width is not set for the chart container, defaults to 500. + * Example: 380, 500, 720 + */ + width?: number; + /** + * Sets the width of the Chart + * Default: Takes chart container’s height by default. If the height is not set for the chart container, defaults to 400. + * Example: 260, 300, 400 + */ + height?: number; + /** + * Title allows you to set content, appearance and position of Chart’s Title. + */ + title: ChartTitleOptions; + /** + * Whenever the chart contains multiple dataSeries, it is recommended to represent each dataSeries in a legend. This way it becomes easier for the user to know what exactly is represented by each of the dataSeries. In case of Pie and Doughnut charts, an entry is created for each dataPoint and in rest of the chart types entries are created for each dataSeries. + * You can selectively show or hide a dataSeries in the Legend using showInLegend property of dataSeries. + */ + legend?: ChartLegendOptions; + /** + * axisX object lets you set various parameters of X Axis like interval, grid lines, etc. It is mostly horizontal, except when we are working with Bar Charts, where axisX is vertical. + */ + axisX?: ChartAxisXOptions; + /** + * axisY object lets you set various parameters of Y Axis like interval, grid lines, etc. It is mostly vertical, except when we are working with Bar Charts, where axisY is horizontal. + */ + axisY?: ChartAxisYOptions; + /** + * toolTip object lets user set behaviour of toolTip at global level like enabling/disabling animation, setting Border Color, sharing toolTip between multiple dataSeries, etc. You can also disable the toolTip by setting enabled property to false. + */ + toolTip?: ChartToolTipOptions; + /** + * data is an array of dataSeries Objects. + */ + data: ChartDataOptions[]; + } + + interface ChartTitleOptions { + /** + * Sets the Title’s text. + * Default: null + * Example: “Chart title” + */ + text?: string; + /** + * This property lets you align the Chart Title vertically. + * Default: “top” + * Options: “top”, “center”, “bottom” + */ + verticalAlign?: string; + /** + * This property lets you align the Chart Title horizontally. + * Default: “center” + * Options: “left”, “right”, “center” + */ + horizontalAlign?: string; + /** + * Sets the font Size of Chart Title in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16,18,22 .. + */ + fontSize?: number; + /** + * Sets the Font Family of Chart Title. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “arial” , “tahoma”, “verdana” .. + */ + fontFamily?: string; + /** + * Sets the Font Weight used in the Chart Title. + * Default: “bold” + * Options: “lighter”, “normal”, “bold” , “bolder” + */ + fontWeight?: string; + /** + * Sets the font color of Chart Title. The value of fontColor can be a “HTML Color Name” or “hex” code . + * Default: “#3A3A3A” + * Example: “red”, “#FAC003″ .. + */ + fontColor?: string; + /** + * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. + * Default: “normal” + * Options: “normal”, “italic” , “oblique” + */ + fontStyle?: string; + /** + * Sets the thickness of border around the Title in pixels. To display border around title, set the borderThickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ + borderThickness?: number; + /** + * To display rounded borders around the title, set the cornerRadius of title. Higher the value, more rounded are the corners. + * Default: 0 + * Options: 5,8 .. + */ + cornerRadius?: number; + /** + * Sets the color of border around Chart Title. Values of borderColor can be “HTML Color Name” or “hex” code . + * Default: “black” + * Example: “red”, “#FF0000″ .. + */ + borderColor?: string; + /** + * Sets the background color of Chart Title. Values can be “HTML Color Name” or “hex” code. + * Default: null + * Example: “red”, “#FF0000″ .. + */ + backgroundColor?: string; + /** + * This property lets you set margin around the Chart Title in pixels. + * Default: 10 + * Example: 4,12 .. + */ + margin?: number; + /** + * This property allows you to set the padding for Chart Title + * Default: 0 + * Example: 5, 8 .. + */ + padding?: number; + } + + interface ChartLegendOptions { + /** + * Sets the font Size of Legend Text in pixels. + * Default: 12 + * Example: 16,18,22 .. + */ + fontSize?: number; + /** + * Sets the Font Family of Legend Text. + * Default: “calibri” + * Example: “arial” , “tahoma”, “verdana” .. + */ + fontFamily?: string; + /** + * Sets the font color of Legend Text . The value of fontColor can be a “HTML Color Name” or “hex” code . + * Default: “black” + * Example: “red”, “#FAC003″ .. + */ + fontColor?: string; + /** + * Sets the Font Weight of Legend Text. + * Default: “normal” + * Example: “lighter”, “normal”, “bold” , “bolder” + */ + fontWeight?: string; + /** + * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. + * Default: “normal” + * Example: “normal”, “italic” , “oblique” + */ + fontStyle?: string; + /** + * This property lets you align the Legend Position vertically. + * Default: “bottom” + * Example: “top”, “center”, “bottom” + */ + verticalAlign?: string; + /** + * This property lets you align the Legend Position horizontally. + * Default: “right” + * Example: “left”, “right”, “center” + */ + horizontalAlign?: string; + /** + * Sets the mouseover event handler for the legend, which is triggered when the user moves the mouse(input device) over a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmouseover?: (event: ChartEvent) => void; + /** + * Sets the mousemove event handler for the legend, which is triggered when the user moves the mouse(input device) within a legend item. When the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmousemove?: (event: ChartEvent) => void; + /** + * Sets the mouseout event handler for the legend, which is triggered when the user moves the mouse pointer outside a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmouseout?: (event: ChartEvent) => void; + /** + * Sets the click event handler for the legend, which is triggered when the user clicks on a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemclick?: (event: ChartEvent) => void; + } + + interface ChartEvent { + /** + * The x value of the item + */ + x: any; + /** + * The y value of the item + */ + y: number; + /** + * The chart object + */ + chart: Chart; + /** + * The datapoint options + */ + dataPoint: ChartDataPoint; + /** + * The data series options + */ + dataSeries: ChartDataOptions; + /** + * The index of the data point + */ + dataPointIndex: number; + /** + * The index of the data series + */ + dataSeriesIndex: number; + } + + interface ChartAxisXOptions { + /** + * Sets the Axis Title. + * Default: null + * Example: “Axis X Title” + */ + title?: string; + /** + * Sets the Font Color of Axis Title. The value of titleFontColor can be a “HTML Color Name” or “hex” code . + * Default: “#666666″ + * Example: “red”, “#006400″ . + */ + titleFontColor?: string; + /** + * Sets the Font Size of Axis Title in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16, 25 .. + */ + titleFontSize?: number; + /** + * Sets the Font Family of Axis Title. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma, “verdana” .. + */ + titleFontFamily?: string; + /** + * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. + * Default: “normal” + * Options: “lighter”, “normal”, “bold” , “bolder” + */ + titleFontWeight?: string; + /** + * Sets the Font Style of Axis Title. It can be set to one of the below options. + * Default: “normal” + * Options: “normal”, “italic” , “oblique” + */ + titleFontStyle?: string; + /** + * This property lets you set margin between chart’s boundary and Axis. + * Default: 2 + * Example: 8, 10.. + */ + margin?: number; + /** + * Sets the angle for Axis Labels. + * Default: null + * Example: 20, 45, -30 .. + */ + labelAngle?: number; + /** + * Sets the Axis Label color. The value of labelFontColor can be a “HTML Color Name” or “hex” code . + * Default: “grey” + * Example: “red”, “#FAC003″ .. + */ + labelFontColor?: string; + /** + * Sets the Axis Label Font Size in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16, 18, 22.. + */ + labelFontSize?: number; + /** + * Sets the Font Family of Axis labels. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma”, “verdana” .. + */ + labelFontFamily?: string; + /** + * Set the font Weight used in Axis Labels. It can be set to one of the options below. + * Default: “normal” + * Options: “lighter”, “normal”, “bold” , “bolder” + */ + labelFontWeight?: string; + /** + * Sets the Font Style of Axis Labels. It can be set to one of the below options. + * Default: “normal” + * Options: “italic”, “oblique”, “normal” + */ + labelFontStyle?: string; + /** + * A string that prepends all the labels on axisX. + * Default: null + * Example: “$”,”cat”.. + */ + prefix?: string; + /** + * A string that appends all the labels on axisX. + * Default: null + * Example: “$”,”cat”.. + */ + suffix?: string; + /** + * Defines how values must be formatted before they appear on Axis X. You can format numbers and date time values using this property. Below you will find descriptive table explaining various specifiers with example. + */ + valueFormatString?: string; + /** + * Sets the minimum value of Axis. Values smaller than minimum are clipped. + * Default: Automatically Calculated based on the data + * Example: 100, 350.. + */ + minimum?: number; + /** + * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. + * Default: Automatically Calculated based on the data + * Example: 100, 350.. + */ + maximum?: number; + /** + * Sets the distance between Tick Marks, Grid Lines and Interlaced Colors. + * Default: Automatically Calculated + * Example: 50, 75.. + */ + interval?: number; + /** + * intervalType is the unit of interval property. intervalType is by default set to “number” and hence you need to specify the interval type (eg “week”, “month”, etc) depending on the type of interval you intend to set. If required interval is 3 months, you need to provide interval as 3 and intervalType as “month” + * Default: Automatically handled when interval property is not set. Defaults to “number” when you set the interval. + * Option: “number”,”millisecond” ,”second”,” minute”, “hour”, “day”, “month” ,”year” + * Example: for interval as 15 minutes, set interval as 15, and set intervalType as “minute”, + */ + intervalType?: string; + /** + * Sets the length of Tick Marks that are drawn on the Axis. + * Default: 5 + * Example: 10, 14.. + */ + tickLength?: number; + /** + * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a “HTML Color Name” or “hex” code . + * Default: “#BBBBBB” + * Example: “red”, “#006400″. + */ + tickColor?: string; + /** + * Sets the thickness of the Tick Marks in pixels. + * Default: 2 + * Example: 3, 4.. + */ + tickThickness?: number; + /** + * Sets the color of Axis line. Axis line color can be a “HTML Color Name” or “hex” code . + * Default: “#BBBBBB” + * Example: “blue”,”#21AB13″.. + */ + lineColor?: string; + /** + * Sets the Thickness of Axis line in pixels. + * Default: 2 + * Example: 2, 4.. + */ + lineThickness?: string; + /** + * Sets the Interlacing Color that alternates between the set interval. If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a “HTML Color Name” or “hex” code . + * Default: null + * Example: “#F8F1E4″, “#FEFDDF” …. + */ + interlaceColor?: string; + /** + * Sets the Thickness of Grid Lines. To display grid on Axis X, set the Grid Thickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ + gridThickness?: number; + /** + * Sets the Color of Grid Lines. Value of gridColor can be a “HTML Color Name” or “hex” code . + * Default: “#BBBBBB” + * Example: “red”, “#FEFDDF” .. + */ + gridColor?: string; + /** + * Strip Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are sometimes referred to as trend lines. + * If you want to just mark a certain position on the axis, you can set the value attribute and it’ll draw a line at that position with the set thickness. If you want to shade a region instead, you need to set startValue and endValue attributes. This will fill the area within the specified range. + * In the case you set startValue and endValue attributes, value and thickness attributes are ignored (as either a single thread of line can exist, or a shaded region between two given points). + * Strip Lines can be displayed using AxisX or AxisY’s stripLines array. This allows you to have one or more strip lines on both x & y axis. + */ + stripLines?: ChartStripLines; + } + + interface ChartStripLines { + /** + * Sets the point where the stripLine has to be plotted or drawn along the axis X. + * Default: null + * Example: 20,30,100,50 + */ + value?: number; + /** + * Sets the point where the stripLine’s shaded region begins on the x-axis. + * Default: null + * Example: 20,30,100,50 + */ + startValue?: number; + /** + * Sets the point where the stripLine’s shaded region ends on the x-axis. + * Default: null + * Example: 50,60,200,300 + */ + endValue?: number; + /** + * Sets the thickness of the stripLine in pixels. + * Default: 2 + * Example: 2,4,5,6 + */ + thickness?: number; + /** + * Sets the color of the stripLine. + * Default: “orange” + * Example: “green”, “#23EA23″ + */ + color?: string; + /** + * Sets the label of the stripLine. These are shown on top of axis labels. + * Default: “” (empty string) + * Example: “Threshold”, “Deaths in 1920″ + */ + label?: string; + /** + * Sets the background color of stripLine’s label. + * Default: “#eeeeee” + * Example: “red”,”#fabd76″ + */ + labelBackgroundColor?: string; + /** + * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. + * Default: “arial” + * Example: “Arial, Trebuchet MS, Tahoma, sans-serif” + */ + labelFontFamily?: string; + /** + * Sets the font color of label. + * Default: “orange” + * Example: “blue”,”#4135e9″ + */ + labelFontColor?: string; + /** + * Sets the font size of the label in pixels. + * Default: 12 + * Example: 18,19,20,22 + */ + labelFontSize?: number; + /** + * Sets the font weight of stripLine’s label. + * Default: “normal” + * Example: “lighter”,”normal”,”bold”,”bolder” + */ + labelFontWeight?: string; + /** + * Sets the font style of stripLine’s label. + * Default: “normal” + * Example: “normal”,”italic”,”oblique” + */ + labelFontStyle?: string; + } + + interface ChartAxisYOptions extends ChartAxisXOptions { + /** + * When includeZero is set to true, axisY sets the range in such a way that Zero is a part of it. It is set to true by default. But, whenever y values are very big and difference among dataPoints are hard to judge, setting includeZero to false makes axisY to set a range that makes the differences prominently visible. + * Default: true + * Example: true, false + */ + includeZero?: boolean; + } + + interface ChartToolTipOptions { + /** + * Enables or Disables the toolTip for the chart. + * Default: True + * Example: True, False + */ + enabled?: boolean; + /** + * In a Multi-Series or a Combination Chart, it is often required to display all values common to x value in a single bubble. Setting shared to true will show in a common bubble all the values of y from each series next to their name. + * Default: True + * Example: True, False + */ + shared?: boolean; + /** + * toolTip for entire chart can be set by adding content at toolTip object. content can either be a string or a custom function that returns HTML/String to be displayed inside the toolTip. + * Default: auto + */ + content?: string; + /** + * While mouse hovers from one dataPoint to another there is a smooth transition in toolTip. This effect can be controlled by animationEnabled Property. Setting it to false, will disable the animation and toolTip will directly switch from one dataPoint to the other. + * Default: True + * Example: True, False + */ + animationEnabled?: boolean; + /** + * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. + * Default: dataSeries color/ dataPoint color + * Example: “red”, “#808080″.. + */ + borderColor?: string; + } + + interface ChartDataCommon { + /** + * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. + * Default: Automatically Named (“dataPoint 1″, “dataPoint 2″ .. ) + * Example: “apple”, “mango” .. + */ + name?: string; + /** + * Sets the color of dataSeries. The value of tickColor can be a “HTML Color Name” or “Hex Code”. + * Default: Automatically set from Theme. + * Example: “red”, “green” .. + */ + color?: string; + /** + * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. + * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. + * eg: indexLabel: “{x}: {y[#index]}” + * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. + * Default: null + * Example: “{label}”, “Win”, “x: {x}, y: {y} ” + */ + indexLabel?: string; + /** + * Using this property you can define whether to render indexLabel “inside” or “outside” the dataPoint. + * Default: “outside” + * Example: “outside”, “inside” + */ + indexLabelPlacement?: string; + /** + * Sets the Orientation of indexLabel to “horizontal” or “vertical”. + * Default: “horizontal” + * Options: “horizontal”, “vertical” + */ + indexLabelOrientation?: string; + /** + * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a “HTML Color Name” or “Hex Code”. + * Default: null + * Example: “red”, “#FAC003″ .. + */ + indexLabelBackgroundColor?: string; + /** + * Sets the Index Label’s Font Style. It can be set to one of the below options. + * Default: “normal” + * Options: “italic”, “oblique”, “normal” + */ + indexLabelFontStyle?: string; + /** + * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a “HTML Color Name” or “Hex Code”. + * Default: “grey” + * Example: “red”, “#FAC003″ .. + */ + indexLabelFontColor?: string; + /** + * Sets the Index Label’s Font Size in pixels. + * Default: 18 + * Example: 12, 16, 22.. + */ + indexLabelFontSize?: number; + /** + * Sets the Index Label’s Font Family. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma”, “verdana”.. + */ + indexLabelFontFamily?: string; + /** + * Sets the Index Label’s Font Weight. It can be set to one of the below options. + * Default: “normal” + * Example: “lighter”, “normal” ,”bold” , “bolder” + */ + indexLabelFontWeight?: string; + /** + * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. The value of indexLineColor can be a “HTML Color Name” or “Hex Code”. + * Default: “lightgrey” + * Example: “red”, “#FAC003″ .. + */ + indexLabelLineColor?: string; + /** + * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacement is set to “outside”. + * Default: 2 + * Example: 4, 6 + */ + indexLabelLineThickness?: string; + /** + * Default Tooltip can be modified at dataSeries or dataPoint level. You can add content to be displayed in toolTip using toolTipContent. toolTipContent set at dataPoint will override toolTipContent set at dataSeries level. + * Default: auto set depending on chart type. + */ + toolTipContent?: string; + /** + * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. + * Same marker type is also used in legend unless overridden by legendMarkerType property. + * Default: “circle” + * Options: “none”, “circle”, “square”, “triangle” and “cross” + */ + markerType?: string; + /** + * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. + * Default: dataSeries Color + * Example: “red”, “#008000″ .. + */ + markerColor?: string; + /** + * Sets the Size of the marker that is drawn. To display marker in area Chart, set markerSize to a value greater than zero. For line, scatter chart, size it is automatically set unless overridden. + * Default: auto. Zero for area chart + * Example: 5, 10.. + */ + markerSize?: number; + /** + * Sets the border color around marker. Value of markerBorderColor can be “HTML Color Name” or “hex code”. + * Default: dataSeries color. + * Example: “red”, “#008000″ .. + */ + markerBorderColor?: string; + /** + * Sets the thickness of the Marker’s Border in pixels. + * Default: 1 + * Example: 2,4 .. + */ + markerBorderThickness?: number; + /** + * Sets the text that describes the dataSeries in legend. + * Default: “DataSeries 1″, “DataSeries 2″ ..etc + * Example: “2010″, “2011″.. + */ + legendText?: string; + /** + * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. + * Default: same as markerType + * Options: “circle”, “square”, “cross” and “triangle” + */ + legendMarkerType?: string; + /** + * Sets the click event handler for dataSeries which is triggered when user clicks on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + click?: (event: ChartEvent) => void; + /** + * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. Value of legendMarkerColor can be “HTML Color Name” or “hex code”. + * Default: dataSeries marker color + * Example: “red”, “#008000″ .. + */ + legendMarkerColor?: string; + /** + * Sets the mouseover event handler for dataSeries which is triggered when user moves Mouse Over a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mouseover?: (event: ChartEvent) => void; + /** + * Sets the mousemove event handler for dataSeries which is triggered when user Moves mouse on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mousemove?: (event: ChartEvent) => void; + /** + * Sets the mouseout event handler for dataSeries which is triggered when user moves mouse out of a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mouseout?: (event: ChartEvent) => void; + } + + interface ChartDataOptions extends ChartDataCommon { + /** + * Sets the visibility of dataSeries. Data Series is visible by default and you can hide the same by setting visible property to false. + * Default: true + * Example: true, false + */ + visible?: boolean; + /** + * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. + * Default: “column” + * Options: + * “line” + * “column” + * “bar” + * “area” + * “spline” + * “splineArea” + * “stepLine” + * “scatter” + * “bubble” + * “stackedColumn” + * “stackedBar” + * “stackedArea” + * “stackedColumn100″ + * “stackedBar100″ + * “stackedArea100″ + * “pie” + * “doughnut” + */ + type?: string; + /** + * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing “secondary” Axis you can plot the series against axisY2. + * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. + * Default: “primary” + * Options: “primary”, “secondary” + */ + axisYType?: string; + /** + * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to “dateTime”. + * Default: Automatically Calculated + * Options: “number”, “dateTime” + */ + xValueType?: string; + /** + * Defines how y axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ + yValueFormatString?: string; + /** + * Defines how x axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ + xValueFormatString?: string; + /** + * Defines how z values is formatted before they appear on the indexLabel or toolTip. You can format numbers using this property. + */ + zValueFormatString?: string; + /** + * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. + * Default: “true” + * Example: “true”, “false” + */ + bevelEnabled?: boolean; + /** + * Sets opacity of the filled color. + * Default: .7 for Area Charts and 1 for all other chart types. + */ + fillOpacity?: number; + /** + * Sets the starting Angle of the Pie or Doughnut Chart in degrees. + * Default: 0 + * Example: 30, 240, -100.. + */ + startAngle?: number; + /** + * Sets the thickness of line in line charts and area charts. + * Default: 2 + * Example: 3,4.. + */ + lineThickness?: number; + /** + * Setting this property to true makes the dataSeries to appear in legend. In case of pie/ doughnut chart, dataPoints of the single series chart appear in legend. + * Default: false + * Options: false, true + */ + showInLegend?: boolean; + /** + * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. + * Default: “white” + * Options: “red”, “#DD7E86″, etc. + */ + risingColor?: string; + /** + * It represents collection dataPoint inside dataSeries . + */ + dataPoints: ChartDataPoint[]; + } + + interface ChartDataPoint extends ChartDataCommon { + /** + * Sets the x value. It determines the position of the dataPoint on X Axis. It can be numeric or a dateTime value. Values can be positive or Negative. + * Default: null + * Example: 10, 20, 30 .. + * new Date(2011, 08, 01) + */ + x?: any; + /** + * Sets the y value of dataPoint. It determines the position of dataPoint on Y Axis. Values can be positive or Negative + * Default: null + * Example: 5, 20, -30 .. + */ + y?: number; + /** + * Sets the z value of dataPoint. It is only applicable in case of Bubble chart. This value determines the size of the bubble. + * Default: 1 + * Example: 10, 20, 35.. + */ + z?: number; + /** + * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. + * Default: x value + * Example: “label1″, “label2″.. + */ + label?: string; + /** + * Sets the exploded value of dataPoint. It is applicable only in case of Pie and Doughnut Charts. This property causes the Pie/Doughnut slice to separate out. + * Default: true + * Example: true, false + */ + exploded?: boolean; + /** + * Sets the color of marker that is displayed on legend. This property works only with Pie and Doughnut charts. Value of legendMarkerColor can be “HTML Color Name” or “hex” code. + * Default: dataSeries marker color + * Example: “red”, “#008000″.. + */ + legendMarkerColor?: string; + } +} \ No newline at end of file From 802b27946a68d0456916ec1832323e03f24f9bee Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Mon, 29 Sep 2014 08:17:34 +0100 Subject: [PATCH 128/149] Create chart.d.ts --- chartjs/chart.d.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 chartjs/chart.d.ts diff --git a/chartjs/chart.d.ts b/chartjs/chart.d.ts new file mode 100644 index 000000000..6fdfbacc8 --- /dev/null +++ b/chartjs/chart.d.ts @@ -0,0 +1,46 @@ +// Type definitions for Chart.js +// Project: https://github.com/nnnick/Chart.js +// Definitions by: Steve Fenton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface ChartDataSet { + label: string; + fillColor: string; + strokeColor: string; + /* Line, Radar */ + pointColor?: string; + pointStrokeColor?: string; + pointHighlightFill?: string; + pointHighlightStroke?: string; + + /* Bar */ + highlightFill?: string; + highlightStroke?: string; + data: number[]; +} + +interface LinearChartData { + labels: string[]; + datasets: ChartDataSet[]; +} + +interface CircularChartData { + value: number; + color: string; + highlight: string; + label: string; +} + +interface Chart { + new (context: CanvasRenderingContext2D): Chart; + Line(data: LinearChartData, options?: {}); + Bar(data: LinearChartData, options?: {}); + Radar(data: LinearChartData, options?: {}); + + PolarArea(data: CircularChartData[], options?: {}); + Pie(data: CircularChartData[], options?: {}); + Doughnut(data: CircularChartData[], options?: {}); + +} + +declare var Chart: Chart; From 975a3b10b6d665366a53b3b7d8604219ab979411 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Mon, 29 Sep 2014 08:18:39 +0100 Subject: [PATCH 129/149] Create chart-tests.ts --- chartjs/chart-tests.ts | 140 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 chartjs/chart-tests.ts diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts new file mode 100644 index 000000000..585770334 --- /dev/null +++ b/chartjs/chart-tests.ts @@ -0,0 +1,140 @@ +var lineData: LinearChartData = { + labels: ['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00'], + datasets: [ + { + label: 'Accepted', + fillColor: 'rgba(220,220,220,0.2)', + strokeColor: 'rgba(220,220,220,1)', + pointColor: 'rgba(220,220,220,1)', + pointStrokeColor: '#fff', + pointHighlightFill: '#fff', + pointHighlightStroke: 'rgba(220,220,220,1)', + data: [65, 59, 80, 81, 56, 55, 40] + }, + { + label: 'Quarantined', + fillColor: 'rgba(151,187,205,0.2)', + strokeColor: 'rgba(151,187,205,1)', + pointColor: 'rgba(151,187,205,1)', + pointStrokeColor: '#fff', + pointHighlightFill: '#fff', + pointHighlightStroke: 'rgba(151,187,205,1)', + data: [28, 48, 40, 19, 86, 27, 90] + } + ] +}; + +var barData: LinearChartData = { + labels: ["January", "February", "March", "April", "May", "June", "July"], + datasets: [ + { + label: "My First dataset", + fillColor: "rgba(220,220,220,0.5)", + strokeColor: "rgba(220,220,220,0.8)", + highlightFill: "rgba(220,220,220,0.75)", + highlightStroke: "rgba(220,220,220,1)", + data: [65, 59, 80, 81, 56, 55, 40] + }, + { + label: "My Second dataset", + fillColor: "rgba(151,187,205,0.5)", + strokeColor: "rgba(151,187,205,0.8)", + highlightFill: "rgba(151,187,205,0.75)", + highlightStroke: "rgba(151,187,205,1)", + data: [28, 48, 40, 19, 86, 27, 90] + } + ] +}; + +var myBarChart = new Chart(ctx).Bar(barData); + +var radarData: LinearChartData = { + labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], + datasets: [ + { + label: "My First dataset", + fillColor: "rgba(220,220,220,0.2)", + strokeColor: "rgba(220,220,220,1)", + pointColor: "rgba(220,220,220,1)", + pointStrokeColor: "#fff", + pointHighlightFill: "#fff", + pointHighlightStroke: "rgba(220,220,220,1)", + data: [65, 59, 90, 81, 56, 55, 40] + }, + { + label: "My Second dataset", + fillColor: "rgba(151,187,205,0.2)", + strokeColor: "rgba(151,187,205,1)", + pointColor: "rgba(151,187,205,1)", + pointStrokeColor: "#fff", + pointHighlightFill: "#fff", + pointHighlightStroke: "rgba(151,187,205,1)", + data: [28, 48, 40, 19, 96, 27, 100] + } + ] +}; + +var myRadarChart = new Chart(ctx).Radar(radarData); + +var polarAreaData: CircularChartData[] = [ + { + value: 300, + color: "#F7464A", + highlight: "#FF5A5E", + label: "Red" + }, + { + value: 50, + color: "#46BFBD", + highlight: "#5AD3D1", + label: "Green" + }, + { + value: 100, + color: "#FDB45C", + highlight: "#FFC870", + label: "Yellow" + }, + { + value: 40, + color: "#949FB1", + highlight: "#A8B3C5", + label: "Grey" + }, + { + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" + } + +]; + +var myPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData); + +var pieData: CircularChartData[] = [ + { + value: 300, + color: "#F7464A", + highlight: "#FF5A5E", + label: "Red" + }, + { + value: 50, + color: "#46BFBD", + highlight: "#5AD3D1", + label: "Green" + }, + { + value: 100, + color: "#FDB45C", + highlight: "#FFC870", + label: "Yellow" + } +]; + +// For a pie chart +var myPieChart = new Chart(ctx[0]).Pie(pieData); + +// And for a doughnut chart +var myDoughnutChart = new Chart(ctx[1]).Doughnut(pieData); From 1b1fb403ab22d7df23b58698c0eea3f31b7a05a8 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Mon, 29 Sep 2014 18:18:00 +1000 Subject: [PATCH 130/149] precise : prefer npm project link --- precise/precise.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/precise/precise.d.ts b/precise/precise.d.ts index 3caba0297..e8af2245f 100644 --- a/precise/precise.d.ts +++ b/precise/precise.d.ts @@ -1,5 +1,5 @@ // Type definitions for precise -// Project: https://github.com/avoidwork/precise +// Project: https://www.npmjs.org/package/precise // Definitions by: Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -31,4 +31,4 @@ declare module "precise" { } export = _precise; -} \ No newline at end of file +} From 30f566d3c9569cbfa6a97da863bdfa58853ca29a Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Mon, 29 Sep 2014 18:19:55 +1000 Subject: [PATCH 131/149] brcryp: perfer npmjs project link --- bcrypt/bcrypt.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bcrypt/bcrypt.d.ts b/bcrypt/bcrypt.d.ts index dd3c92c2b..98d68b773 100644 --- a/bcrypt/bcrypt.d.ts +++ b/bcrypt/bcrypt.d.ts @@ -1,5 +1,5 @@ // Type definitions for bcrypt -// Project: https://github.com/ncb000gt/node.bcrypt.js +// Project: https://www.npmjs.org/package/bcrypt // Definitions by: Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -62,4 +62,4 @@ declare module "bcrypt" { * @param encrypted Hash from which the number of rounds used should be extracted. */ export function getRounds(encrypted: string): number; -} \ No newline at end of file +} From c3da47bb1faa7c83ed3ec3541f9db29ef5b7c0d6 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Mon, 29 Sep 2014 10:03:33 +0100 Subject: [PATCH 132/149] Update chart.d.ts --- chartjs/chart.d.ts | 181 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 170 insertions(+), 11 deletions(-) diff --git a/chartjs/chart.d.ts b/chartjs/chart.d.ts index 6fdfbacc8..7364c6525 100644 --- a/chartjs/chart.d.ts +++ b/chartjs/chart.d.ts @@ -7,6 +7,7 @@ interface ChartDataSet { label: string; fillColor: string; strokeColor: string; + /* Line, Radar */ pointColor?: string; pointStrokeColor?: string; @@ -31,16 +32,174 @@ interface CircularChartData { label: string; } -interface Chart { - new (context: CanvasRenderingContext2D): Chart; - Line(data: LinearChartData, options?: {}); - Bar(data: LinearChartData, options?: {}); - Radar(data: LinearChartData, options?: {}); - - PolarArea(data: CircularChartData[], options?: {}); - Pie(data: CircularChartData[], options?: {}); - Doughnut(data: CircularChartData[], options?: {}); - +interface ChartSettings { + animation: boolean; + animationSteps: number; + animationEasing: string; + showScale: boolean; + scaleOverride: boolean; + scaleSteps: number; + scaleStepWidth: number; + scaleStartValue: number; + scaleLineColor: string; + scaleLineWidth: number; + scaleShowLabels: boolean; + scaleLabel: string; + scaleIntegersOnly: boolean; + scaleBeginAtZero: boolean; + scaleFontFamily: string; + scaleFontSize: number; + scaleFontStyle: string; + scaleFontColor: string; + responsive: boolean; + maintainAspectRatio: boolean; + showTooltips: boolean; + tooltipEvents: string[]; + tooltipFillColor: string; + tooltipFontFamily: string; + tooltipFontSize: number; + tooltipFontStyle: string; + tooltipFontColor: string; + tooltipTitleFontFamily: string; + tooltipTitleFontSize: number; + tooltipTitleFontStyle: string; + tooltipTitleFontColor: string; + tooltipYPadding: number; + tooltipXPadding: number; + tooltipCaretSize: number; + tooltipCornerRadius: number; + tooltipXOffset: number; + tooltipTemplate: string; + multiTooltipTemplate: string; + onAnimationProgress: () => any; + onAnimationComplete: () => any; } -declare var Chart: Chart; +interface ChartOptions { + scaleShowGridLines?: boolean; + scaleGridLineColor?: string; + scaleGridLineWidth?: number; + legendTemplate?: string; +} + +interface PointsAtEvent { + value: number; + label: string; + datasetLabel: string; + strokeColor: string; + fillColor: string; + highlightFill: string; + highlightStroke: string; + x: number; + y: number; +} + +interface ChartInstance { + clear: () => void; + stop: () => void; + resize: () => void; + destroy: () => void; + toBase64Image: () => string; + generateLegend: () => string; +} + +interface LinearInstance extends ChartInstance { + getPointsAtEvent: (event: Event) => PointsAtEvent[]; + update: () => void; + addData: (valuesArray: number[], label: string) => void; + removeData: () => void; +} + +interface CircularInstance extends ChartInstance { + getSegmentsAtEvent: (event: Event) => {}[]; + update: () => void; + addData: (valuesArray: CircularChartData[], index: number) => void; + removeData: (index: number) => void; +} + +interface LineChartOptions extends ChartOptions { + bezierCurve?: boolean; + bezierCurveTension?: number; + pointDot?: boolean; + pointDotRadius?: number; + pointDotStrokeWidth?: number; + pointHitDetectionRadius?: number; + datasetStroke?: boolean; + datasetStrokeWidth?: number; + datasetFill?: boolean; +} + +interface BarChartOptions extends ChartOptions { + scaleBeginAtZero?: boolean; + barShowStroke?: boolean; + barStrokeWidth?: number; + barValueSpacing?: number; + barDatasetSpacing?: number; +} + +interface RadarChartOptions { + scaleShowLine?: boolean; + angleShowLineOut?: boolean; + scaleShowLabels?: boolean; + scaleBeginAtZero?: boolean; + angleLineColor?: string; + angleLineWidth?: number; + pointLabelFontFamily?: string; + pointLabelFontStyle?: string; + pointLabelFontSize?: number; + pointLabelFontColor?: string; + pointDot?: boolean; + pointDotRadius?: number; + pointDotStrokeWidth?: number; + pointHitDetectionRadius?: number; + datasetStroke?: boolean; + datasetStrokeWidth?: number; + datasetFill?: boolean; + legendTemplate?: string; +} + +interface PolarAreaChartOptions { + scaleShowLabelBackdrop?: boolean; + scaleBackdropColor?: string; + scaleBeginAtZero?: boolean; + scaleBackdropPaddingY?: number; + scaleBackdropPaddingX?: number; + scaleShowLine?: boolean; + segmentShowStroke?: boolean; + segmentStrokeColor?: string; + segmentStrokeWidth?: number; + animationSteps?: number; + animationEasing?: string; + animateRotate?: boolean; + animateScale?: boolean; + legendTemplate?: string; +} + +interface PieChartOptions { + segmentShowStroke?: boolean; + segmentStrokeColor?: string; + segmentStrokeWidth?: number; + percentageInnerCutout?: number; + animationSteps?: number; + animationEasing?: string; + animateRotate?: boolean; + animateScale?: boolean; + legendTemplate?: string; +} + +interface Chart { + Line(data: LinearChartData, options?: LineChartOptions): LinearInstance; + Bar(data: LinearChartData, options?: BarChartOptions): LinearInstance; + Radar(data: LinearChartData, options?: RadarChartOptions): LinearInstance; + + PolarArea(data: CircularChartData[], options?: PolarAreaChartOptions): CircularInstance; + Pie(data: CircularChartData[], options?: PieChartOptions): CircularInstance; + Doughnut(data: CircularChartData[], options?: PieChartOptions): CircularInstance; +} + +declare var Chart: { + new (context: CanvasRenderingContext2D): Chart; + defaults: { + global: ChartSettings; + } +}; From a03690e46efc245e3cb85cfa2480f05a7759cca2 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Mon, 29 Sep 2014 10:03:53 +0100 Subject: [PATCH 133/149] Update chart-tests.ts --- chartjs/chart-tests.ts | 210 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 205 insertions(+), 5 deletions(-) diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts index 585770334..58dead8f9 100644 --- a/chartjs/chart-tests.ts +++ b/chartjs/chart-tests.ts @@ -1,3 +1,48 @@ +/// + +Chart.defaults.global = { + animation: true, + animationSteps: 60, + animationEasing: "easeOutQuart", + showScale: true, + scaleOverride: false, + scaleSteps: null, + scaleStepWidth: null, + scaleStartValue: null, + scaleLineColor: "rgba(0,0,0,.1)", + scaleLineWidth: 1, + scaleShowLabels: true, + scaleLabel: "<%=value%>", + scaleIntegersOnly: true, + scaleBeginAtZero: false, + scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + scaleFontSize: 12, + scaleFontStyle: "normal", + scaleFontColor: "#666", + responsive: false, + maintainAspectRatio: true, + showTooltips: true, + tooltipEvents: ["mousemove", "touchstart", "touchmove"], + tooltipFillColor: "rgba(0,0,0,0.8)", + tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + tooltipFontSize: 14, + tooltipFontStyle: "normal", + tooltipFontColor: "#fff", + tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + tooltipTitleFontSize: 14, + tooltipTitleFontStyle: "bold", + tooltipTitleFontColor: "#fff", + tooltipYPadding: 6, + tooltipXPadding: 6, + tooltipCaretSize: 8, + tooltipCornerRadius: 6, + tooltipXOffset: 10, + tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>", + multiTooltipTemplate: "<%= value %>", + onAnimationProgress: function () { }, + onAnimationComplete: function () { } +} + var lineData: LinearChartData = { labels: ['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00'], datasets: [ @@ -24,6 +69,32 @@ var lineData: LinearChartData = { ] }; +var myLineChart = new Chart(ctx).Line(lineData, { + scaleShowGridLines: true, + scaleGridLineColor: "rgba(0,0,0,.05)", + scaleGridLineWidth: 1, + bezierCurve: true, + bezierCurveTension: 0.4, + pointDot: true, + pointDotRadius: 4, + pointDotStrokeWidth: 1, + pointHitDetectionRadius: 20, + datasetStroke: true, + datasetStrokeWidth: 2, + datasetFill: true, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" +}); + +var myLineChartLegend: string = myLineChart.generateLegend(); +var myLineChartImage: string = myLineChart.toBase64Image(); +myLineChart.addData([1, 2, 3, 4, 5, 6, 7], 'new'); +myLineChart.clear(); +myLineChart.removeData(); +myLineChart.resize(); +myLineChart.update(); +myLineChart.stop(); +myLineChart.destroy(); + var barData: LinearChartData = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ @@ -46,7 +117,27 @@ var barData: LinearChartData = { ] }; -var myBarChart = new Chart(ctx).Bar(barData); +var myBarChart = new Chart(ctx).Bar(barData, { + scaleBeginAtZero: true, + scaleShowGridLines: true, + scaleGridLineColor: "rgba(0,0,0,.05)", + scaleGridLineWidth: 1, + barShowStroke: true, + barStrokeWidth: 2, + barValueSpacing: 5, + barDatasetSpacing: 1, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" +}); + +var myBarChartLegend: string = myBarChart.generateLegend(); +var myBarChartImage: string = myBarChart.toBase64Image(); +myBarChart.addData([1, 2, 3, 4, 5, 6, 7], 'new'); +myBarChart.clear(); +myBarChart.removeData(); +myBarChart.resize(); +myBarChart.update(); +myBarChart.stop(); +myBarChart.destroy(); var radarData: LinearChartData = { labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], @@ -74,7 +165,36 @@ var radarData: LinearChartData = { ] }; -var myRadarChart = new Chart(ctx).Radar(radarData); +var myRadarChart = new Chart(ctx).Radar(radarData, { + scaleShowLine: true, + angleShowLineOut: true, + scaleShowLabels: false, + scaleBeginAtZero: true, + angleLineColor: "rgba(0,0,0,.1)", + angleLineWidth: 1, + pointLabelFontFamily: "'Arial'", + pointLabelFontStyle: "normal", + pointLabelFontSize: 10, + pointLabelFontColor: "#666", + pointDot: true, + pointDotRadius: 3, + pointDotStrokeWidth: 1, + pointHitDetectionRadius: 20, + datasetStroke: true, + datasetStrokeWidth: 2, + datasetFill: true, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" +}); + +var myRadarChartLegend: string = myRadarChart.generateLegend(); +var myRadarChartImage: string = myRadarChart.toBase64Image(); +myRadarChart.addData([1, 2, 3, 4, 5, 6, 7], 'new'); +myRadarChart.clear(); +myRadarChart.removeData(); +myRadarChart.resize(); +myRadarChart.update(); +myRadarChart.stop(); +myRadarChart.destroy(); var polarAreaData: CircularChartData[] = [ { @@ -110,7 +230,37 @@ var polarAreaData: CircularChartData[] = [ ]; -var myPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData); +var myPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, { + scaleShowLabelBackdrop: true, + scaleBackdropColor: "rgba(255,255,255,0.75)", + scaleBeginAtZero: true, + scaleBackdropPaddingY: 2, + scaleBackdropPaddingX: 2, + scaleShowLine: true, + segmentShowStroke: true, + segmentStrokeColor: "#fff", + segmentStrokeWidth: 2, + animationSteps: 100, + animationEasing: "easeOutBounce", + animateRotate: true, + animateScale: false, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
  • <%}%>
" +}); + +var myPolarAreaChartLegend: string = myPolarAreaChart.generateLegend(); +var myPolarAreaChartImage: string = myPolarAreaChart.toBase64Image(); +myPolarAreaChart.addData([{ + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" +}], 0); +myPolarAreaChart.clear(); +myPolarAreaChart.removeData(0); +myPolarAreaChart.resize(); +myPolarAreaChart.update(); +myPolarAreaChart.stop(); +myPolarAreaChart.destroy(); var pieData: CircularChartData[] = [ { @@ -134,7 +284,57 @@ var pieData: CircularChartData[] = [ ]; // For a pie chart -var myPieChart = new Chart(ctx[0]).Pie(pieData); +var myPieChart = new Chart(ctx[0]).Pie(pieData, { + segmentShowStroke: true, + segmentStrokeColor: "#fff", + segmentStrokeWidth: 2, + percentageInnerCutout: 0, + animationSteps: 100, + animationEasing: "easeOutBounce", + animateRotate: true, + animateScale: false, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
  • <%}%>
" +}); + +var myPieChartLegend: string = myPieChart.generateLegend(); +var myPieChartImage: string = myPieChart.toBase64Image(); +myPieChart.addData([{ + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" +}], 0); +myPieChart.clear(); +myPieChart.removeData(0); +myPieChart.resize(); +myPieChart.update(); +myPieChart.stop(); +myPieChart.destroy(); // And for a doughnut chart -var myDoughnutChart = new Chart(ctx[1]).Doughnut(pieData); +var myDoughnutChart = new Chart(ctx[1]).Doughnut(pieData, { + segmentShowStroke: true, + segmentStrokeColor: "#fff", + segmentStrokeWidth: 2, + percentageInnerCutout: 50, + animationSteps: 100, + animationEasing: "easeOutBounce", + animateRotate: true, + animateScale: false, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
  • <%}%>
" +}); + +var myDoughnutChartLegend: string = myDoughnutChart.generateLegend(); +var myDoughnutChartImage: string = myDoughnutChart.toBase64Image(); +myPieChart.addData([{ + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" +}], 0); +myDoughnutChart.clear(); +myDoughnutChart.removeData(0); +myDoughnutChart.resize(); +myDoughnutChart.update(); +myDoughnutChart.stop(); +myDoughnutChart.destroy(); From 8da8bce0b120440a080842e5d4289eed120499ef Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Mon, 29 Sep 2014 10:07:57 +0100 Subject: [PATCH 134/149] Update chart-tests.ts --- chartjs/chart-tests.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts index 58dead8f9..79a2692c2 100644 --- a/chartjs/chart-tests.ts +++ b/chartjs/chart-tests.ts @@ -1,5 +1,7 @@ /// +var ctx = canvas.getContext('2d'); + Chart.defaults.global = { animation: true, animationSteps: 60, @@ -284,7 +286,7 @@ var pieData: CircularChartData[] = [ ]; // For a pie chart -var myPieChart = new Chart(ctx[0]).Pie(pieData, { +var myPieChart = new Chart(ctx).Pie(pieData, { segmentShowStroke: true, segmentStrokeColor: "#fff", segmentStrokeWidth: 2, @@ -312,7 +314,7 @@ myPieChart.stop(); myPieChart.destroy(); // And for a doughnut chart -var myDoughnutChart = new Chart(ctx[1]).Doughnut(pieData, { +var myDoughnutChart = new Chart(ctx).Doughnut(pieData, { segmentShowStroke: true, segmentStrokeColor: "#fff", segmentStrokeWidth: 2, From ad1e185b4c4ea3c122f918f66e604dd91e44c926 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Mon, 29 Sep 2014 10:10:51 +0100 Subject: [PATCH 135/149] Update chart-tests.ts --- chartjs/chart-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts index 79a2692c2..2374b6228 100644 --- a/chartjs/chart-tests.ts +++ b/chartjs/chart-tests.ts @@ -1,5 +1,6 @@ /// +var canvas = document.getElementById('example-chart'); var ctx = canvas.getContext('2d'); Chart.defaults.global = { From 035fea44c6aff1ae4062a86add61dc1c65b20391 Mon Sep 17 00:00:00 2001 From: Andrew Bradley Date: Mon, 29 Sep 2014 06:11:53 -0400 Subject: [PATCH 136/149] Updates sinon-chai definition and tests to support loading sinon-chai as a chai plugin. - usage is as follows: import sinonChai = require('sinon-chai'); chai.use(sinonChai); - Also updates the tests to compile with --noImplicitAny --- sinon-chai/sinon-chai-tests.ts | 11 ++++++++--- sinon-chai/sinon-chai.d.ts | 5 +++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/sinon-chai/sinon-chai-tests.ts b/sinon-chai/sinon-chai-tests.ts index b250b142d..48ac47ee9 100644 --- a/sinon-chai/sinon-chai-tests.ts +++ b/sinon-chai/sinon-chai-tests.ts @@ -3,12 +3,17 @@ declare var expect: chai.ExpectStatic; +import chai = require('chai'); +import sinonChai = require('sinon-chai'); + +chai.use(sinonChai); + function test() { var spy: Function; var anotherSpy: Function; - var context; - var match; - + var context: any; + var match: any; + expect(spy).to.have.been.called; expect(spy).to.have.been.calledOnce; expect(spy).to.have.been.calledTwice; diff --git a/sinon-chai/sinon-chai.d.ts b/sinon-chai/sinon-chai.d.ts index f8166d4d6..0f639abb7 100644 --- a/sinon-chai/sinon-chai.d.ts +++ b/sinon-chai/sinon-chai.d.ts @@ -26,3 +26,8 @@ declare module chai { always: Expect; } } + +declare module "sinon-chai" { + function exports(_chai: typeof chai, utils: any): void; + export = exports; +} From 5651488586642eb5c764ddfa1f12f6fa05c69f20 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 29 Sep 2014 15:04:46 +0200 Subject: [PATCH 137/149] Fixed bug in typeahead definition --- typeahead/typeahead-tests.ts | 245 ++++++++++++++++++++++++++++++++--- typeahead/typeahead.d.ts | 5 +- 2 files changed, 233 insertions(+), 17 deletions(-) diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index 3c8495f86..bc8d734c3 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -4,7 +4,6 @@ // // Examples from http://twitter.github.com/typeahead.js/examples // -declare var Hogan: string; var substringMatcher = function (strs: any) { return function findMatches(q: any, cb: any) { @@ -24,11 +23,11 @@ var substringMatcher = function (strs: any) { // JavaScript object, refer to typeahead docs for more info matches.push({ value: str }); } -}); + }); cb(matches); - }; -}; + } +} var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', @@ -41,18 +40,234 @@ var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; -$('#the-basics .typeahead').typeahead({ - hint: true, - highlight: true, - minLength: 1 -}, -{ - name: 'states', - displayKey: 'value', - source: substringMatcher(states) -}); -module valueTest { +function test_method_names() { + $('#the-basics .typeahead').typeahead('destroy'); + $('#the-basics .typeahead').typeahead('open'); + $('#the-basics .typeahead').typeahead('close'); + $('#the-basics .typeahead').typeahead('val'); + $('#the-basics .typeahead').typeahead('val', 'test value'); +} + + +function test_options() { + + var dataSets: Twitter.Typeahead.Dataset[] = []; + + function with_empty_options() { + $('#the-basics .typeahead').typeahead({}, dataSets); + } + + function with_hint_option() { + $('#the-basics .typeahead').typeahead({ hint: true }, dataSets); + } + + function with_highlight_option() { + $('#the-basics .typeahead').typeahead({ highlight: true }, dataSets); + } + + function with_minLength_option() { + $('#the-basics .typeahead').typeahead({ minLength: 1 }, dataSets); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead({ + hint: true, + highlight: true, + minLength: 1 + }, + dataSets + ); + } +} + +function test_datasets_array() { + + var options: Twitter.Typeahead.Options = {}; + + function with_only_source() { + $('#the-basics .typeahead').typeahead(options, [{ + source: substringMatcher(states) + }]); + } + + function with_name_option() { + + $('#the-basics .typeahead').typeahead(options, [{ + name: 'states', + source: substringMatcher(states), + }]); + } + + function with_displayKey_option() { + $('#the-basics .typeahead').typeahead(options, [{ + displayKey: 'value', + source: substringMatcher(states) + }] + ); + } + + function with_templates_option() { + $('#the-basics .typeahead').typeahead(options, [{ + templates: {}, + source: substringMatcher(states) + }] + ); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead(options, [{ + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + }] + ); + } + + function with_multiple_datasets() { + $('#the-basics .typeahead').typeahead(options, [ + { + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + }, + { + name: 'states alternative', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + } + ]); + } +} + + +function test_datasets_objects() { + + var options: Twitter.Typeahead.Options = {}; + + function with_only_source() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states) + }); + } + + function with_name_option() { + + $('#the-basics .typeahead').typeahead(options, { + name: 'states', + source: substringMatcher(states), + }); + } + + function with_displayKey_option() { + $('#the-basics .typeahead').typeahead(options, + { + displayKey: 'value', + source: substringMatcher(states) + } + ); + } + + function with_templates_option() { + $('#the-basics .typeahead').typeahead(options, + { + templates: {}, + source: substringMatcher(states) + } + ); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead(options, + { + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + } + ); + } + + function with_multiple_objects() { + $('#the-basics .typeahead').typeahead(options, + { + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + }, + { + name: 'states alternative', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + } + ); + } +} + +function test_dataset_templates() { + + var options: Twitter.Typeahead.Options = {}; + + function with_no_options() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: {} + }); + } + + function with_empty_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { empty: 'no results' } + }); + } + + function with_footer_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { footer: 'custom footer' } + }); + } + + function with_header_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { header: 'custom header' } + }); + } + + function with_suggestion_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { + suggestion: function(context) { + return context.name; + } + } + }); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { + empty: 'no results', + footer: 'custom footer', + header: 'custom header', + suggestion: function(context) { + return context.name; + } + } + }); + } +} + +function test_value() { var value: string = $('foo').typeahead('val'); $('foo').typeahead('val', value); } \ No newline at end of file diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index 34ea56597..58dabf75c 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -107,7 +107,7 @@ declare module Twitter.Typeahead { */ source: (query: string, cb: (result: any) => void) => void; - /** + /** * The name of the dataset. * This will be appended to tt-dataset- to form the class name of the containing DOM element. * Must only consist of underscores, dashes, letters (a-z), and numbers. @@ -159,7 +159,7 @@ declare module Twitter.Typeahead { * The associated suggestion object will serve as the context. * Defaults to the value of displayKey wrapped in a p tag i.e.

{{value}}

. */ - suggestion?: string; + suggestion?: (context: any) => string; } @@ -186,6 +186,7 @@ declare module Twitter.Typeahead { minLength?: number; } } + declare module Bloodhound { interface BloodhoundOptions From 7c74debc97a95abad3a97aa9854d35a91c10895b Mon Sep 17 00:00:00 2001 From: SomaticIT Date: Wed, 24 Sep 2014 16:33:48 +0200 Subject: [PATCH 138/149] Rename 'node-tar' to 'tar' to match npm package name --- node-tar/node-tar-tests.ts => tar/tar-tests.ts | 2 +- node-tar/node-tar.d.ts => tar/tar.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename node-tar/node-tar-tests.ts => tar/tar-tests.ts (93%) rename node-tar/node-tar.d.ts => tar/tar.d.ts (99%) diff --git a/node-tar/node-tar-tests.ts b/tar/tar-tests.ts similarity index 93% rename from node-tar/node-tar-tests.ts rename to tar/tar-tests.ts index 727dbc08c..3a7783d52 100644 --- a/node-tar/node-tar-tests.ts +++ b/tar/tar-tests.ts @@ -5,7 +5,7 @@ */ /// -/// +/// import tar = require("tar"); import fs = require("fs"); diff --git a/node-tar/node-tar.d.ts b/tar/tar.d.ts similarity index 99% rename from node-tar/node-tar.d.ts rename to tar/tar.d.ts index fc9bf3256..6b25a02a7 100644 --- a/node-tar/node-tar.d.ts +++ b/tar/tar.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-tar v1.0.1 +// Type definitions for tar v1.0.1 // Project: https://github.com/npm/node-tar // Definitions by: Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped From 67762b395175362ed52d794e7279fc75f412f029 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Mon, 29 Sep 2014 20:32:50 +0100 Subject: [PATCH 139/149] Update createClient method to better adhere to docs See: https://github.com/mranney/node_redis#rediscreateclient --- redis/redis.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/redis/redis.d.ts b/redis/redis.d.ts index e31b130ac..e7a7f29bf 100644 --- a/redis/redis.d.ts +++ b/redis/redis.d.ts @@ -6,7 +6,9 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/redis.d.ts declare module "redis" { - export function createClient(port_arg: number, host_arg: string, options: ClientOpts): RedisClient; + export function createClient(port_arg: number, host_arg?: string, options?: ClientOpts): RedisClient; + export function createClient(unix_socket: string, options?: ClientOpts): RedisClient; + export function createClient(options?: ClientOpts): RedisClient; export function print(err: Error, reply: any): void; export var debug_mode: boolean; From a920b0cb8c2094acf44872e3c7d99a6a0fa29c5e Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Mon, 29 Sep 2014 22:20:23 +0100 Subject: [PATCH 140/149] Fix Redis defs to better describe API. - Merge all callback interfaces into a generic interface. - Add CommandT generic interface for future use, to not have to explicitly define all command signatures. At the moment a duplicate definition is thrown is used, as commands like ```get``` have additional signatures defined. - Add rest parameter array to all commands, as all command accept either an array or paramarray (see: https://github.com/mranney/node_redis#sending-commands) - Update tests to test that paramarray is working as expected. - TODO: Add CAPITALISED versions of commands. - Add myself to header info. --- redis/redis-tests.ts | 4 +- redis/redis.d.ts | 485 +++++++++++++++++++++++++++---------------- 2 files changed, 309 insertions(+), 180 deletions(-) diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index 98ed2371b..e64fa7378 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -47,7 +47,7 @@ client.bitcount(str, numCallback); client.bitcount(str, num, num, numCallback); client.set(str, str, strCallback); client.get(str, strCallback); -client.exists(str, str, numCallback); +client.exists(str, numCallback); client.publish(str, value); client.subscribe(str); @@ -60,3 +60,5 @@ client.get(args); client.get(args, resCallback); client.set(args); client.set(args, resCallback); + +client.incr(str, resCallback); \ No newline at end of file diff --git a/redis/redis.d.ts b/redis/redis.d.ts index e7a7f29bf..913257d7c 100644 --- a/redis/redis.d.ts +++ b/redis/redis.d.ts @@ -1,6 +1,6 @@ // Type definitions for redis // Project: https://github.com/mranney/node_redis -// Definitions by: Carlos Ballesteros Velasco +// Definitions by: Carlos Ballesteros Velasco , Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/redis.d.ts @@ -16,17 +16,14 @@ declare module "redis" { (channel: string, message: any): void; } - interface ResCallback { - (err: Error, res: any): void; - } + interface CommandT { //This is a placeholder to be used eventually, to not have to define each command twice, or four times if all caps versions are to be implemented. + (args: any[], callback?: ResCallbackT): void; + (...args: any[]): void; + } - interface NumCallback { - (err: Error, reply: number): void; - } - - interface StringCallback { - (err: Error, reply: string): void; - } + interface ResCallbackT { + (err: Error, res: R): void; + } interface ServerInfo { redis_version: string; @@ -47,180 +44,310 @@ declare module "redis" { } interface RedisClient { - // event: connect - // event: error - // event: message - // event: pmessage - // event: subscribe - // event: psubscribe - // event: unsubscribe - // event: punsubscribe + // event: connect + // event: error + // event: message + // event: pmessage + // event: subscribe + // event: psubscribe + // event: unsubscribe + // event: punsubscribe - connected: boolean; - retry_delay: number; - retry_backoff: number; - command_queue: any[]; - offline_queue: any[]; - server_info: ServerInfo; + connected: boolean; + retry_delay: number; + retry_backoff: number; + command_queue: any[]; + offline_queue: any[]; + server_info: ServerInfo; - end(): void; + end(): void; - // Connection (http://redis.io/commands#connection) - auth(password: string, callback?: ResCallback): void; - ping(callback?: NumCallback): void; + // Connection (http://redis.io/commands#connection) + auth(password: string, callback?: ResCallbackT): void; + ping(callback?: ResCallbackT): void; - // Strings (http://redis.io/commands#strings) - append(key: string, value: string, callback?: NumCallback): void; - bitcount(key: string, callback?: NumCallback): void; - bitcount(key: string, start: number, end: number, callback?: NumCallback): void; - set(key: string, value: string, callback?: StringCallback): void; - get(key: string, callback?: StringCallback): void; - exists(key: string, value: string, callback?: NumCallback): void; + // Strings (http://redis.io/commands#strings) + append(key: string, value: string, callback?: ResCallbackT): void; + bitcount(key: string, callback?: ResCallbackT): void; + bitcount(key: string, start: number, end: number, callback?: ResCallbackT): void; + set(key: string, value: string, callback?: ResCallbackT): void; + get(key: string, callback?: ResCallbackT): void; + exists(key: string, value: string, callback?: ResCallbackT): void; - publish(channel: string, value: any): void; - subscribe(channel: string): void; - on(channel: string, handler: MessageHandler): void; + publish(channel: string, value: any): void; + subscribe(channel: string): void; + on(channel: string, handler: MessageHandler): void; - /* - commands = set_union([ - "get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", - "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", - "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", - "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", - "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", - "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", - "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", - "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", - "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", - "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); - */ + /* + commands = set_union([ + "get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", + "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", + "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", + "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", + "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", + "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", + "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", + "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", + "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", + "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); + */ - get(args: any[], callback?: ResCallback): void; - set(args: any[], callback?: ResCallback): void; - setnx(args: any[], callback?: ResCallback): void; - setex(args: any[], callback?: ResCallback): void; - append(args: any[], callback?: ResCallback): void; - strlen(args: any[], callback?: ResCallback): void; - del(args: any[], callback?: ResCallback): void; - exists(args: any[], callback?: ResCallback): void; - setbit(args: any[], callback?: ResCallback): void; - getbit(args: any[], callback?: ResCallback): void; - setrange(args: any[], callback?: ResCallback): void; - getrange(args: any[], callback?: ResCallback): void; - substr(args: any[], callback?: ResCallback): void; - incr(args: any[], callback?: ResCallback): void; - decr(args: any[], callback?: ResCallback): void; - mget(args: any[], callback?: ResCallback): void; - rpush(args: any[], callback?: ResCallback): void; - lpush(args: any[], callback?: ResCallback): void; - rpushx(args: any[], callback?: ResCallback): void; - lpushx(args: any[], callback?: ResCallback): void; - linsert(args: any[], callback?: ResCallback): void; - rpop(args: any[], callback?: ResCallback): void; - lpop(args: any[], callback?: ResCallback): void; - brpop(args: any[], callback?: ResCallback): void; - brpoplpush(args: any[], callback?: ResCallback): void; - blpop(args: any[], callback?: ResCallback): void; - llen(args: any[], callback?: ResCallback): void; - lindex(args: any[], callback?: ResCallback): void; - lset(args: any[], callback?: ResCallback): void; - lrange(args: any[], callback?: ResCallback): void; - ltrim(args: any[], callback?: ResCallback): void; - lrem(args: any[], callback?: ResCallback): void; - rpoplpush(args: any[], callback?: ResCallback): void; - sadd(args: any[], callback?: ResCallback): void; - srem(args: any[], callback?: ResCallback): void; - smove(args: any[], callback?: ResCallback): void; - sismember(args: any[], callback?: ResCallback): void; - scard(args: any[], callback?: ResCallback): void; - spop(args: any[], callback?: ResCallback): void; - srandmember(args: any[], callback?: ResCallback): void; - sinter(args: any[], callback?: ResCallback): void; - sinterstore(args: any[], callback?: ResCallback): void; - sunion(args: any[], callback?: ResCallback): void; - sunionstore(args: any[], callback?: ResCallback): void; - sdiff(args: any[], callback?: ResCallback): void; - sdiffstore(args: any[], callback?: ResCallback): void; - smembers(args: any[], callback?: ResCallback): void; - zadd(args: any[], callback?: ResCallback): void; - zincrby(args: any[], callback?: ResCallback): void; - zrem(args: any[], callback?: ResCallback): void; - zremrangebyscore(args: any[], callback?: ResCallback): void; - zremrangebyrank(args: any[], callback?: ResCallback): void; - zunionstore(args: any[], callback?: ResCallback): void; - zinterstore(args: any[], callback?: ResCallback): void; - zrange(args: any[], callback?: ResCallback): void; - zrangebyscore(args: any[], callback?: ResCallback): void; - zrevrangebyscore(args: any[], callback?: ResCallback): void; - zcount(args: any[], callback?: ResCallback): void; - zrevrange(args: any[], callback?: ResCallback): void; - zcard(args: any[], callback?: ResCallback): void; - zscore(args: any[], callback?: ResCallback): void; - zrank(args: any[], callback?: ResCallback): void; - zrevrank(args: any[], callback?: ResCallback): void; - hset(args: any[], callback?: ResCallback): void; - hsetnx(args: any[], callback?: ResCallback): void; - hget(args: any[], callback?: ResCallback): void; - hmset(args: any[], callback?: ResCallback): void; - hmget(args: any[], callback?: ResCallback): void; - hincrby(args: any[], callback?: ResCallback): void; - hdel(args: any[], callback?: ResCallback): void; - hlen(args: any[], callback?: ResCallback): void; - hkeys(args: any[], callback?: ResCallback): void; - hvals(args: any[], callback?: ResCallback): void; - hgetall(args: any[], callback?: ResCallback): void; - hexists(args: any[], callback?: ResCallback): void; - incrby(args: any[], callback?: ResCallback): void; - decrby(args: any[], callback?: ResCallback): void; - getset(args: any[], callback?: ResCallback): void; - mset(args: any[], callback?: ResCallback): void; - msetnx(args: any[], callback?: ResCallback): void; - randomkey(args: any[], callback?: ResCallback): void; - select(args: any[], callback?: ResCallback): void; - move(args: any[], callback?: ResCallback): void; - rename(args: any[], callback?: ResCallback): void; - renamenx(args: any[], callback?: ResCallback): void; - expire(args: any[], callback?: ResCallback): void; - expireat(args: any[], callback?: ResCallback): void; - keys(args: any[], callback?: ResCallback): void; - dbsize(args: any[], callback?: ResCallback): void; - auth(args: any[], callback?: ResCallback): void; - ping(args: any[], callback?: ResCallback): void; - echo(args: any[], callback?: ResCallback): void; - save(args: any[], callback?: ResCallback): void; - bgsave(args: any[], callback?: ResCallback): void; - bgrewriteaof(args: any[], callback?: ResCallback): void; - shutdown(args: any[], callback?: ResCallback): void; - lastsave(args: any[], callback?: ResCallback): void; - type(args: any[], callback?: ResCallback): void; - multi(args: any[], callback?: ResCallback): void; - exec(args: any[], callback?: ResCallback): void; - discard(args: any[], callback?: ResCallback): void; - sync(args: any[], callback?: ResCallback): void; - flushdb(args: any[], callback?: ResCallback): void; - flushall(args: any[], callback?: ResCallback): void; - sort(args: any[], callback?: ResCallback): void; - info(args: any[], callback?: ResCallback): void; - monitor(args: any[], callback?: ResCallback): void; - ttl(args: any[], callback?: ResCallback): void; - persist(args: any[], callback?: ResCallback): void; - slaveof(args: any[], callback?: ResCallback): void; - debug(args: any[], callback?: ResCallback): void; - config(args: any[], callback?: ResCallback): void; - subscribe(args: any[], callback?: ResCallback): void; - unsubscribe(args: any[], callback?: ResCallback): void; - psubscribe(args: any[], callback?: ResCallback): void; - punsubscribe(args: any[], callback?: ResCallback): void; - publish(args: any[], callback?: ResCallback): void; - watch(args: any[], callback?: ResCallback): void; - unwatch(args: any[], callback?: ResCallback): void; - cluster(args: any[], callback?: ResCallback): void; - restore(args: any[], callback?: ResCallback): void; - migrate(args: any[], callback?: ResCallback): void; - dump(args: any[], callback?: ResCallback): void; - object(args: any[], callback?: ResCallback): void; - client(args: any[], callback?: ResCallback): void; - eval(args: any[], callback?: ResCallback): void; - evalsha(args: any[], callback?: ResCallback): void; + get(args: any[], callback?: ResCallbackT): void; + get(...args: any[]): void; + set(args: any[], callback?: ResCallbackT): void; + set(...args: any[]): void; + setnx(args: any[], callback?: ResCallbackT): void; + setnx(...args: any[]): void; + setex(args: any[], callback?: ResCallbackT): void; + setex(...args: any[]): void; + append(args: any[], callback?: ResCallbackT): void; + append(...args: any[]): void; + strlen(args: any[], callback?: ResCallbackT): void; + strlen(...args: any[]): void; + del(args: any[], callback?: ResCallbackT): void; + del(...args: any[]): void; + exists(args: any[], callback?: ResCallbackT): void; + exists(...args: any[]): void; + setbit(args: any[], callback?: ResCallbackT): void; + setbit(...args: any[]): void; + getbit(args: any[], callback?: ResCallbackT): void; + getbit(...args: any[]): void; + setrange(args: any[], callback?: ResCallbackT): void; + setrange(...args: any[]): void; + getrange(args: any[], callback?: ResCallbackT): void; + getrange(...args: any[]): void; + substr(args: any[], callback?: ResCallbackT): void; + substr(...args: any[]): void; + incr(args: any[], callback?: ResCallbackT): void; + incr(...args: any[]): void; + decr(args: any[], callback?: ResCallbackT): void; + decr(...args: any[]): void; + mget(args: any[], callback?: ResCallbackT): void; + mget(...args: any[]): void; + rpush(...args: any[]): void; + lpush(args: any[], callback?: ResCallbackT): void; + lpush(...args: any[]): void; + rpushx(args: any[], callback?: ResCallbackT): void; + rpushx(...args: any[]): void; + lpushx(args: any[], callback?: ResCallbackT): void; + lpushx(...args: any[]): void; + linsert(args: any[], callback?: ResCallbackT): void; + linsert(...args: any[]): void; + rpop(args: any[], callback?: ResCallbackT): void; + rpop(...args: any[]): void; + lpop(args: any[], callback?: ResCallbackT): void; + lpop(...args: any[]): void; + brpop(args: any[], callback?: ResCallbackT): void; + brpop(...args: any[]): void; + brpoplpush(args: any[], callback?: ResCallbackT): void; + brpoplpush(...args: any[]): void; + blpop(args: any[], callback?: ResCallbackT): void; + blpop(...args: any[]): void; + llen(args: any[], callback?: ResCallbackT): void; + llen(...args: any[]): void; + lindex(args: any[], callback?: ResCallbackT): void; + lindex(...args: any[]): void; + lset(args: any[], callback?: ResCallbackT): void; + lset(...args: any[]): void; + lrange(args: any[], callback?: ResCallbackT): void; + lrange(...args: any[]): void; + ltrim(args: any[], callback?: ResCallbackT): void; + ltrim(...args: any[]): void; + lrem(args: any[], callback?: ResCallbackT): void; + lrem(...args: any[]): void; + rpoplpush(args: any[], callback?: ResCallbackT): void; + rpoplpush(...args: any[]): void; + sadd(args: any[], callback?: ResCallbackT): void; + sadd(...args: any[]): void; + srem(args: any[], callback?: ResCallbackT): void; + srem(...args: any[]): void; + smove(args: any[], callback?: ResCallbackT): void; + smove(...args: any[]): void; + sismember(args: any[], callback?: ResCallbackT): void; + sismember(...args: any[]): void; + scard(args: any[], callback?: ResCallbackT): void; + scard(...args: any[]): void; + spop(args: any[], callback?: ResCallbackT): void; + spop(...args: any[]): void; + srandmember(args: any[], callback?: ResCallbackT): void; + srandmember(...args: any[]): void; + sinter(args: any[], callback?: ResCallbackT): void; + sinter(...args: any[]): void; + sinterstore(args: any[], callback?: ResCallbackT): void; + sinterstore(...args: any[]): void; + sunion(args: any[], callback?: ResCallbackT): void; + sunion(...args: any[]): void; + sunionstore(args: any[], callback?: ResCallbackT): void; + sunionstore(...args: any[]): void; + sdiff(args: any[], callback?: ResCallbackT): void; + sdiff(...args: any[]): void; + sdiffstore(args: any[], callback?: ResCallbackT): void; + sdiffstore(...args: any[]): void; + smembers(args: any[], callback?: ResCallbackT): void; + smembers(...args: any[]): void; + zadd(args: any[], callback?: ResCallbackT): void; + zadd(...args: any[]): void; + zincrby(args: any[], callback?: ResCallbackT): void; + zincrby(...args: any[]): void; + zrem(args: any[], callback?: ResCallbackT): void; + zrem(...args: any[]): void; + zremrangebyscore(args: any[], callback?: ResCallbackT): void; + zremrangebyscore(...args: any[]): void; + zremrangebyrank(args: any[], callback?: ResCallbackT): void; + zremrangebyrank(...args: any[]): void; + zunionstore(args: any[], callback?: ResCallbackT): void; + zunionstore(...args: any[]): void; + zinterstore(args: any[], callback?: ResCallbackT): void; + zinterstore(...args: any[]): void; + zrange(args: any[], callback?: ResCallbackT): void; + zrange(...args: any[]): void; + zrangebyscore(args: any[], callback?: ResCallbackT): void; + zrangebyscore(...args: any[]): void; + zrevrangebyscore(args: any[], callback?: ResCallbackT): void; + zrevrangebyscore(...args: any[]): void; + zcount(args: any[], callback?: ResCallbackT): void; + zcount(...args: any[]): void; + zrevrange(args: any[], callback?: ResCallbackT): void; + zrevrange(...args: any[]): void; + zcard(args: any[], callback?: ResCallbackT): void; + zcard(...args: any[]): void; + zscore(args: any[], callback?: ResCallbackT): void; + zscore(...args: any[]): void; + zrank(args: any[], callback?: ResCallbackT): void; + zrank(...args: any[]): void; + zrevrank(args: any[], callback?: ResCallbackT): void; + zrevrank(...args: any[]): void; + hset(args: any[], callback?: ResCallbackT): void; + hset(...args: any[]): void; + hsetnx(args: any[], callback?: ResCallbackT): void; + hsetnx(...args: any[]): void; + hget(args: any[], callback?: ResCallbackT): void; + hget(...args: any[]): void; + hmset(args: any[], callback?: ResCallbackT): void; + hmset(key: string, hash: any, callback?: ResCallbackT): void; + hmset(...args: any[]): void; + hmget(args: any[], callback?: ResCallbackT): void; + hmget(...args: any[]): void; + hincrby(args: any[], callback?: ResCallbackT): void; + hincrby(...args: any[]): void; + hdel(args: any[], callback?: ResCallbackT): void; + hdel(...args: any[]): void; + hlen(args: any[], callback?: ResCallbackT): void; + hlen(...args: any[]): void; + hkeys(args: any[], callback?: ResCallbackT): void; + hkeys(...args: any[]): void; + hvals(args: any[], callback?: ResCallbackT): void; + hvals(...args: any[]): void; + hgetall(args: any[], callback?: ResCallbackT): void; + hgetall(...args: any[]): void; + hgetall(key: string, callback?: ResCallbackT): void; + hexists(args: any[], callback?: ResCallbackT): void; + hexists(...args: any[]): void; + incrby(args: any[], callback?: ResCallbackT): void; + incrby(...args: any[]): void; + decrby(args: any[], callback?: ResCallbackT): void; + decrby(...args: any[]): void; + getset(args: any[], callback?: ResCallbackT): void; + getset(...args: any[]): void; + mset(args: any[], callback?: ResCallbackT): void; + mset(...args: any[]): void; + msetnx(args: any[], callback?: ResCallbackT): void; + msetnx(...args: any[]): void; + randomkey(args: any[], callback?: ResCallbackT): void; + randomkey(...args: any[]): void; + select(args: any[], callback?: ResCallbackT): void; + select(...args: any[]): void; + move(args: any[], callback?: ResCallbackT): void; + move(...args: any[]): void; + rename(args: any[], callback?: ResCallbackT): void; + rename(...args: any[]): void; + renamenx(args: any[], callback?: ResCallbackT): void; + renamenx(...args: any[]): void; + expire(args: any[], callback?: ResCallbackT): void; + expire(...args: any[]): void; + expireat(args: any[], callback?: ResCallbackT): void; + expireat(...args: any[]): void; + keys(args: any[], callback?: ResCallbackT): void; + keys(...args: any[]): void; + dbsize(args: any[], callback?: ResCallbackT): void; + dbsize(...args: any[]): void; + auth(args: any[], callback?: ResCallbackT): void; + auth(...args: any[]): void; + ping(args: any[], callback?: ResCallbackT): void; + ping(...args: any[]): void; + echo(args: any[], callback?: ResCallbackT): void; + echo(...args: any[]): void; + save(args: any[], callback?: ResCallbackT): void; + save(...args: any[]): void; + bgsave(args: any[], callback?: ResCallbackT): void; + bgsave(...args: any[]): void; + bgrewriteaof(args: any[], callback?: ResCallbackT): void; + bgrewriteaof(...args: any[]): void; + shutdown(args: any[], callback?: ResCallbackT): void; + shutdown(...args: any[]): void; + lastsave(args: any[], callback?: ResCallbackT): void; + lastsave(...args: any[]): void; + type(args: any[], callback?: ResCallbackT): void; + type(...args: any[]): void; + multi(args: any[], callback?: ResCallbackT): void; + multi(...args: any[]): void; + exec(args: any[], callback?: ResCallbackT): void; + exec(...args: any[]): void; + discard(args: any[], callback?: ResCallbackT): void; + discard(...args: any[]): void; + sync(args: any[], callback?: ResCallbackT): void; + sync(...args: any[]): void; + flushdb(args: any[], callback?: ResCallbackT): void; + flushdb(...args: any[]): void; + flushall(args: any[], callback?: ResCallbackT): void; + flushall(...args: any[]): void; + sort(args: any[], callback?: ResCallbackT): void; + sort(...args: any[]): void; + info(args: any[], callback?: ResCallbackT): void; + info(...args: any[]): void; + monitor(args: any[], callback?: ResCallbackT): void; + monitor(...args: any[]): void; + ttl(args: any[], callback?: ResCallbackT): void; + ttl(...args: any[]): void; + persist(args: any[], callback?: ResCallbackT): void; + persist(...args: any[]): void; + slaveof(args: any[], callback?: ResCallbackT): void; + slaveof(...args: any[]): void; + debug(args: any[], callback?: ResCallbackT): void; + debug(...args: any[]): void; + config(args: any[], callback?: ResCallbackT): void; + config(...args: any[]): void; + subscribe(args: any[], callback?: ResCallbackT): void; + subscribe(...args: any[]): void; + unsubscribe(args: any[], callback?: ResCallbackT): void; + unsubscribe(...args: any[]): void; + psubscribe(args: any[], callback?: ResCallbackT): void; + psubscribe(...args: any[]): void; + punsubscribe(args: any[], callback?: ResCallbackT): void; + punsubscribe(...args: any[]): void; + publish(args: any[], callback?: ResCallbackT): void; + publish(...args: any[]): void; + watch(args: any[], callback?: ResCallbackT): void; + watch(...args: any[]): void; + unwatch(args: any[], callback?: ResCallbackT): void; + unwatch(...args: any[]): void; + cluster(args: any[], callback?: ResCallbackT): void; + cluster(...args: any[]): void; + restore(args: any[], callback?: ResCallbackT): void; + restore(...args: any[]): void; + migrate(args: any[], callback?: ResCallbackT): void; + migrate(...args: any[]): void; + dump(args: any[], callback?: ResCallbackT): void; + dump(...args: any[]): void; + object(args: any[], callback?: ResCallbackT): void; + object(...args: any[]): void; + client(args: any[], callback?: ResCallbackT): void; + client(...args: any[]): void; + eval(args: any[], callback?: ResCallbackT): void; + eval(...args: any[]): void; + evalsha(args: any[], callback?: ResCallbackT): void; + evalsha(...args: any[]): void; + quit(args: any[], callback?: ResCallbackT): void; + quit(...args: any[]): void; } } From bfeb9b276e0e99f7f277b7c9725a970419f0a6bd Mon Sep 17 00:00:00 2001 From: Evgenus Date: Tue, 30 Sep 2014 03:06:45 +0300 Subject: [PATCH 141/149] bigint: Documentation enhanced --- bigint/bigint-tests.ts | 2 +- bigint/bigint.d.ts | 502 +++++++++++++++++++++++++++++++---------- 2 files changed, 389 insertions(+), 115 deletions(-) diff --git a/bigint/bigint-tests.ts b/bigint/bigint-tests.ts index 8ccf2ba4b..14cdd5b12 100644 --- a/bigint/bigint-tests.ts +++ b/bigint/bigint-tests.ts @@ -49,7 +49,7 @@ bi = BigInt.trim(bi, num); BigInt.addInt_(bi, num); BigInt.add_(bi, bi); BigInt.copy_(bi, bi); -num = BigInt.copyInt_(bi, num); +BigInt.copyInt_(bi, num); BigInt.GCD_(bi, bi); b = BigInt.inverseMod_(bi, bi); BigInt.mod_(bi, bi); diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts index b70f20fa4..a2a8ed417 100644 --- a/bigint/bigint.d.ts +++ b/bigint/bigint.d.ts @@ -1,8 +1,11 @@ -// Type definitions for BigInt v5.5.1 +// Type definitions for BigInt v5.5.3 // Project: https://github.com/Evgenus/BigInt // Definitions by: Eugene Chernyshov // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Development repository: https://github.com/Evgenus/bigint-typescript-definitions +// For answers, fixes and cutting edge version please see development repository. + declare module BigInt { export interface BigInt extends Array { } @@ -11,361 +14,632 @@ declare module BigInt { (): number; } + /** + * Sets a random number generator. + * + * @param {IRandom} random function that returns random number. + */ export function setRandom(random: IRandom): void; /** - * bigInt add(x,y) * return (x+y) for bigInts x and y. + * + * @param {BigInt} x The BigInt augend. + * @param {BigInt} y The BigInt addend. + * + * @return {BigInt} A sum as BigInt. */ export function add(x: BigInt, y: BigInt): BigInt; /** - * bigInt addInt(x,n) * return (x+n) where x is a bigInt and n is an integer. + * + * @param {BigInt} x The BigInt augend. + * @param {number} n The number addend. + * + * @return {BigInt} A sum as BigInt. */ export function addInt(x: BigInt, n: number): BigInt; - interface bigInt2str_T { - /** - * string bigInt2str(x,base) - * return a string form of bigInt x in a given base, with 2 <= base <= 95 - */ - (x: BigInt, base: T): string; - } - - interface bigInt2strSignature extends bigInt2str_T, bigInt2str_T{ - } - - export var bigInt2str: bigInt2strSignature; + /** + * return a string form of bigInt x in a given base, with 2 <= base <= 95. + * + * @param {BigInt} x The BigInt to stringify. + * @param {number} base The base as radix number. + * + * @return {string} A string representation of given BigInt. + */ + export function bigInt2str(x: BigInt, base: number): string; /** - * int bitSize(x) - * return how many bits long the bigInt x is, not counting leading zeros + * return a string form of bigInt x in a given base, with 2 <= base <= 95. + * + * @param {BigInt} x The BigInt to stringify. + * @param {string} base The base as vocabulary of characters. + * + * @return {string} A string representation of given BigInt. + */ + export function bigInt2str(x: BigInt, base: string): string; + + /** + * return how many bits long the bigInt x is, not counting leading zeros. + * + * @param {BigInt} x The BigInt to process. + * + * @return {number} A size in BigInt as number. */ export function bitSize(x: BigInt): number; /** - * bigInt dup(x) - * return a copy of bigInt x + * return a copy of bigInt x. + * + * @param {BigInt} x Source BigInt to be copied. + * + * @return {BigInt} A copy of this object. */ export function dup(x: BigInt): BigInt; /** - * boolean equals(x,y) * is the bigInt x equal to the bigint y? + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * + * @return {boolean} true if the objects are considered equal, false if they are not. */ export function equals(x: BigInt, y: BigInt): boolean; /** - * boolean equalsInt(x,y) * is bigint x equal to integer y? + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * + * @return {boolean} true if the objects are considered equal, false if not. */ export function equalsInt(x: BigInt, y: number): boolean; /** - * bigInt expand(x,n) - * return a copy of x with at least n elements, adding leading zeros if needed + * return a copy of x with at least n elements, adding leading zeros if needed. + * + * @param {BigInt} value The source object to copy. + * @param {number} n The minimal number of elements. + * + * @return {BigInt} A copy of given BigInt. */ export function expand(value: BigInt, n: number): BigInt; /** - * Array findPrimes(n) - * return array of all primes less than integer n + * return array of all primes less than integer n. + * + * @param {number} n Upper limit of search. + * + * @return {Array} The found primes as Array. */ export function findPrimes(n: number): number[]; /** - * bigInt GCD(x,y) * return greatest common divisor of bigInts x and y (each with same number of elements). + * + * @param {BigInt} x The BigInt to process. + * @param {BigInt} y The BigInt to process. + * + * @return {BigInt} A greatest common divisor as BigInt. */ export function GCD(x: BigInt, y: BigInt): BigInt; /** - * boolean greater(x,y) * is x>y? (x and y are nonnegative bigInts) + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * + * @return {boolean} true if x is greater, false if it's not. */ export function greater(x: BigInt, y: BigInt): boolean; /** - * boolean greaterShift(x,y,shift) * is (x <<(shift*bpe)) > y? + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * @param {number} shift The shift amount in bits. + * + * @return {boolean} true if x is greater, false if it's not. */ export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean; /** - * bigInt int2bigInt(t,n,m) - * return a bigInt equal to integer t, with at least n bits and m array elements + * return a bigInt equal to integer t, with at least n bits and m array elements. + * + * @param {number} t The number to process. + * @param {number=} n (Optional) the number to process. + * @param {number=} m (Optional) the number to process. + * + * @return {BigInt} A BigInt equivalent of given number. */ export function int2bigInt(t: number, n?: number, m?: number): BigInt; /** - * bigInt inverseMod(x,n) - * return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + * return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null. + * + * @param {BigInt} x The BigInt base. + * @param {BigInt} n The BigInt divisor. + * + * @return {BigInt} A BigInt remainder. */ export function inverseMod(x: BigInt, n: BigInt): BigInt; /** - * int inverseModInt(x,n) - * return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + * return x**(-1) mod n, for integers x and n. + * Return 0 if there is no inverse. + * + * @param {number} x The BigInt base. + * @param {number} n The BigInt divisor. + * + * @return {BigInt} A BigInt remainder. */ export function inverseModInt(x: number, n: number): BigInt; /** - * boolean isZero(x) * is the bigInt x equal to zero? + * + * @param {BigInt} x BigInt to be compared. + * + * @return {boolean} true if zero, false if not. */ export function isZero(x: BigInt): boolean; /** - * boolean millerRabin(x,b) - * does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1=1). If s=1, then the most significant of those n bits is set to 1. + * return an n-bit random BigInt (n>=1). + * If s=1, then the most significant of those n bits is set to 1. + * + * @param {number} n The number of bits (n>=1). + * @param {number} s The sign bit. + * + * @return {BigInt} A new random BigInt. */ export function randBigInt(n: number, s: number): BigInt; /** - * bigInt randTruePrime(k) * return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + * + * @param {number} k The number of bits. + * + * @return {BigInt} A new random BigInt. */ export function randTruePrime(k: number): BigInt; /** - * bigInt randProbPrime(k) - * return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + * return a new, random, k-bit, probable prime bigInt. + * Probability it's composite less than 2^- 80. + * + * @param {number} k The number of bits. + * + * @return {BigInt} A new probably random BigInt. */ export function randProbPrime(k: number): BigInt; - interface str2bigInt_T { - /** - * bigInt str2bigInt(s,b,n,m) - * return a bigInt for number represented in string s in base b with at least n bits and m array elements - */ - (s: string, b: T, n?: number, m?: number): BigInt; - } - - interface str2bigIntSignature extends str2bigInt_T, str2bigInt_T { - } - - export var str2bigInt: str2bigIntSignature; + /** + * return a bigInt for number represented in string s in base b with at least n bits and m array + * elements. + * + * @param {string} s The string representation of number. + * @param {number} b The base as radix number. + * @param {number=} n (Optional) minimal bit length as number. + * @param {number=} m (Optional) the number of array elements as number. + * + * @return {BigInt} A parsed BigInt. + */ + export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt; /** - * bigInt sub(x,y) - * return (x-y) for bigInts x and y. Negative answers will be 2s complement + * return a bigInt for number represented in string s in base b with at least n bits and m array + * elements. + * + * @param {string} s The string representation of number. + * @param {string} b The base as string vocabulary of characters. + * @param {number=} n (Optional) minimal bit length as number. + * @param {number=} m (Optional) the number of array elements as number. + * + * @return {BigInt} A parsed BigInt. + */ + export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt; + + /** + * return (x-y) for bigInts x and y. + * Negative answers will be 2s complement. + * + * @param {BigInt} x The minuend as BigInt. + * @param {BigInt} y The subtrahend as BigInt. + * + * @return {BigInt} A difference BigInt. */ export function sub(x: BigInt, y: BigInt): BigInt; /** - * bigInt trim(x,k) - * return a copy of x with exactly k leading zero elements + * return a copy of x with exactly k leading zero elements. + * + * @param {BigInt} x The BigInt to be copied. + * @param {number} k The number of zeroes. + * + * @return {BigInt} A copy BigInt. */ export function trim(x: BigInt, k: number): BigInt; /** - * void addInt_(x,n) - * do x=x+n where x is a bigInt and n is an integer + * do x=x+n where x is a bigInt and n is an integer. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt accumulator. + * @param {number} n The number addend. */ export function addInt_(x: BigInt, n: number): void; /** - * void add_(x,y) - * do x=x+y for bigInts x and y + * do x=x+y for bigInts x and y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt accumulator. + * @param {BigInt} y The BigInt addend. */ export function add_(x: BigInt, y: BigInt): void; /** - * void copy_(x,y) - * do x=y on bigInts x and y + * do x=y on bigInts x and y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt destination. + * @param {BigInt} y The BigInt source. */ export function copy_(x: BigInt, y: BigInt): void; /** - * void copyInt_(x,n) - * do x=n on bigInt x and integer n + * do x=n on bigInt x and integer n. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt destination. + * @param {number} n The number source. */ - export function copyInt_(x: BigInt, n: number): number; + export function copyInt_(x: BigInt, n: number): void; /** - * void GCD_(x,y) - * set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + * set x to the greatest common divisor of bigInts x and y, (y is destroyed). + * This never overflows its array. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt first dividend. + * @param {BigInt} y The BigInt second dividend. */ export function GCD_(x: BigInt, y: BigInt): void; /** - * boolean inverseMod_(x,n) - * do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + * do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt base and the remainder result. + * @param {BigInt} n The BigInt divisor. + * + * @return {boolean} true if inverse does exist, false if doesn't. */ export function inverseMod_(x: BigInt, n: BigInt): boolean; /** - * void mod_(x,n) * do x=x mod n for bigInts x and n. (This never overflows its array). + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt dividend and the remainder result. + * @param {BigInt} n The BigInt divisor. */ export function mod_(x: BigInt, n: BigInt): void; /** - * void mult_(x,y) * do x=x*y for bigInts x and y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt multiplicand and the product result. + * @param {BigInt} y The BigInt multiplier. */ export function mult_(x: BigInt, y: BigInt): void; /** - * void multMod_(x,y,n) - * do x=x*y mod n for bigInts x,y,n. + * do x=x*y mod n for bigInts x,y,n. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt multiplicand and the remainder result. + * @param {BigInt} y The BigInt multiplier. + * @param {BigInt} n The BigInt divisor. */ export function multMod_(x: BigInt, y: BigInt, n: BigInt): void; /** - * void powMod_(x,y,n) - * do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + * do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. + * 0**0=1. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt base and the remainder result. + * @param {BigInt} y The BigInt exponent. + * @param {BigInt} n The BigInt divisor. */ export function powMod_(x: BigInt, y: BigInt, n: BigInt): void; /** - * void randBigInt_(b,n,s) - * do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + * do b = an n-bit random BigInt. + * if s=1, then nth bit (most significant bit) is set to 1. n>=1. + * + * @private Intend to be internal function. + * + * @param {BigInt} b The BigInt destination. + * @param {number} n The number of bits. + * @param {number} s The sign bit number. */ export function randBigInt_(b: BigInt, n: number, s: number): void; /** - * void randTruePrime_(ans,k) * do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + * + * @private Intend to be internal function. + * + * @param {BigInt} ans The destination. + * @param {number} k The number of bits. */ export function randTruePrime_(ans: BigInt, k: number): void; /** - * void sub_(x,y) * do x=x-y for bigInts x and y. Negative answers will be 2s complement. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt minuend and the result difference. + * @param {BigInt} y The BigInt subtrahend . */ export function sub_(x: BigInt, y: BigInt): void; /** - * void addShift_(x,y,ys) * do x=x+(y<<(ys*bpe)) + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt accumulator. + * @param {BigInt} y The BigInt addend to be shifted. + * @param {number} ys The number of shift amount. */ export function addShift_(x: BigInt, y: BigInt, ys: number): void; /** - * void carry_(x) * do carries and borrows so each element of the bigInt x fits in bpe bits. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt to process. */ export function carry_(x: BigInt): void; /** - * void divide_(x,y,q,r) - * divide x by y giving quotient q and remainder r + * divide x by y giving quotient q and remainder r. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt dividend. + * @param {BigInt} y The BigInt divisor. + * @param {BigInt} q The BigInt quotient. + * @param {BigInt} r The BigInt remainder. */ export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void; /** - * int divInt_(x,n) - * do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + * do x=floor(x/n) for bigInt x and integer n, and return the remainder. + * This never overflows its array. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt dividend and the quotient result. + * @param {number} n The number divisor. + * + * @return {number} A number remainder. */ export function divInt_(x: BigInt, n: number): number; /** - * void eGCD_(x,y,d,a,b) - * sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + * sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt to process. + * @param {BigInt} y The BigInt to process. + * @param {BigInt} d The BigInt to process. + * @param {BigInt} a The BigInt to process. + * @param {BigInt} b The BigInt to process. */ export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void; /** - * void halve_(x) - * do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + * do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. + * This never overflows its array. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt to process. */ export function halve_(x: BigInt): void; /** - * void leftShift_(x,n) * left shift bigInt x by n bits. n Date: Tue, 30 Sep 2014 06:00:25 +0000 Subject: [PATCH 142/149] Update angular-translate.d.ts Version 2.4.0 changes --- angular-translate/angular-translate.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 7aa71c577..135ac75ad 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate v2.3.0 (pascalprecht.translate module) +// Type definitions for Angular Translate v2.4.0 (pascalprecht.translate module) // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -50,6 +50,8 @@ declare module ng.translate { use(): string; use(key: string): ng.IPromise; useFallbackLanguage(langKey?: string): void; + versionInfo(): string; + loaderCache(): any; } interface ITranslateProvider extends ng.IServiceProvider { @@ -89,5 +91,6 @@ declare module ng.translate { determinePreferredLanguage(fn?: () => void): ITranslateProvider; registerAvailableLanguageKeys(): string[]; registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider; + useLoaderCache(cache?: any): ITranslateProvider; } } From 0a6d75d4a1534a90d782c4d6cb49852548de4539 Mon Sep 17 00:00:00 2001 From: Xiaohan Zhang Date: Tue, 30 Sep 2014 13:55:24 -0700 Subject: [PATCH 143/149] Add StringStream definition for codemirror taken from https://codemirror.net/doc/manual.html#modeapi Eventually we'll need to add in the actual mode object but that's a whole different beast. I couldn't find documentation on lastColumnPos, lastColumnValue, or lineStart. Let me know if it's alright to just leave them undocumented. Thanks! --- codemirror/codemirror.d.ts | 110 +++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index af4b32046..08005eb67 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -806,4 +806,114 @@ declare module CodeMirror { By default, a marker appears only in its target document. */ shared?: boolean; } + + interface StringStream { + lastColumnPos: number; + lastColumnValue: number; + lineStart: number; + + /** + * Current position in the string. + */ + pos: number; + + /** + * Where the stream's position was when it was first passed to the token function. + */ + start: number; + + /** + * The current line's content. + */ + string: string; + + /** + * Number of spaces per tab character. + */ + tabSize: number; + + /** + * Returns true only if the stream is at the end of the line. + */ + eol(): boolean; + + /** + * Returns true only if the stream is at the start of the line. + */ + sol(): boolean; + + /** + * Returns the next character in the stream without advancing it. Will return an null at the end of the line. + */ + peek(): string; + + /** + * Returns the next character in the stream and advances it. Also returns null when no more characters are available. + */ + next(): string; + + /** + * match can be a character, a regular expression, or a function that takes a character and returns a boolean. + * If the next character in the stream 'matches' the given argument, it is consumed and returned. + * Otherwise, undefined is returned. + */ + eat(match: string): string; + eat(match: RegExp): string; + eat(match: (char: string) => boolean): string; + + /** + * Repeatedly calls eat with the given argument, until it fails. Returns true if any characters were eaten. + */ + eatWhile(match: string): boolean; + eatWhile(match: RegExp): boolean; + eatWhile(match: (char: string) => boolean): boolean; + + /** + * Shortcut for eatWhile when matching white-space. + */ + eatSpace(): boolean; + + /** + * Moves the position to the end of the line. + */ + skipToEnd(): void; + + /** + * Skips to the next occurrence of the given character, if found on the current line (doesn't advance the stream if + * the character does not occur on the line). + * + * Returns true if the character was found. + */ + skipTo(ch: string): boolean; + + /** + * Act like a multi-character eat - if consume is true or not given - or a look-ahead that doesn't update the stream + * position - if it is false. pattern can be either a string or a regular expression starting with ^. When it is a + * string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular + * expression, the returned value will be the array returned by match, in case you need to extract matched groups. + */ + match(pattern: string, consume?: boolean, caseFold?: boolean): boolean; + match(pattern: RegExp, consume?: boolean): string[]; + + /** + * Backs up the stream n characters. Backing it up further than the start of the current token will cause things to + * break, so be careful. + */ + backUp(n: number): void; + + /** + * Returns the column (taking into account tabs) at which the current token starts. + */ + column(): number; + + /** + * Tells you how far the current line has been indented, in spaces. Corrects for tab characters. + */ + indentation(): number; + + /** + * Get the string between the start of the current token and the current stream position. + */ + current(): string; + } } From 6e5bc3c5149e253d7922aa9615c3929666e6f18b Mon Sep 17 00:00:00 2001 From: Brandon Luong Date: Tue, 30 Sep 2014 14:20:57 -0700 Subject: [PATCH 144/149] Correcting typing for d3.map.entries --- d3/d3.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index e2bf337e4..6a38ecc2b 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -841,6 +841,11 @@ declare module D3 { entries(values: any[]): NestKeyValue[]; } + export interface MapKeyValue { + key: string; + value: T; + } + export interface Map { has(key: string): boolean; get(key: string): T; @@ -848,7 +853,7 @@ declare module D3 { remove(key: string): boolean; keys(): string[]; values(): T[]; - entries(): any[][]; // Actually of form [key: string, val: T][], but this is inexpressible in Typescript + entries(): KeyValue[]; forEach(func: (key: string, value: T) => void ): void; empty(): boolean; size(): number; From da6dfc85a7be239dceaa66d5259d4406ee88f9ef Mon Sep 17 00:00:00 2001 From: Brandon Luong Date: Tue, 30 Sep 2014 14:22:23 -0700 Subject: [PATCH 145/149] KeyValue -> MapKeyValue --- d3/d3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 6a38ecc2b..15df19464 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -853,7 +853,7 @@ declare module D3 { remove(key: string): boolean; keys(): string[]; values(): T[]; - entries(): KeyValue[]; + entries(): MapKeyValue[]; forEach(func: (key: string, value: T) => void ): void; empty(): boolean; size(): number; From adec547b22bd74c934286d45d4432d19d5930307 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 30 Sep 2014 15:54:40 -0700 Subject: [PATCH 146/149] Made `scheduler` parameter of `Observable.timer` optional (fixes Reactive-Extensions/RxJS#282). --- rx.time-lite.d.ts | 4 ++-- rx.time.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/rx.time-lite.d.ts b/rx.time-lite.d.ts index a5b102827..7a7d8f46f 100644 --- a/rx.time-lite.d.ts +++ b/rx.time-lite.d.ts @@ -49,8 +49,8 @@ declare module Rx { interface ObservableStatic { interval(period: number, scheduler?: IScheduler): Observable; interval(dutTime: number, period: number, scheduler?: IScheduler): Observable; - timer(dueTime: number, period: number, scheduler: IScheduler): Observable; - timer(dueTime: number, scheduler: IScheduler): Observable; + timer(dueTime: number, period: number, scheduler?: IScheduler): Observable; + timer(dueTime: number, scheduler?: IScheduler): Observable; generateWithRelativeTime( initialState: TState, condition: (state: TState) => boolean, diff --git a/rx.time.d.ts b/rx.time.d.ts index 6efd7d9cf..2cdb1d56a 100644 --- a/rx.time.d.ts +++ b/rx.time.d.ts @@ -17,8 +17,8 @@ declare module Rx { } interface ObservableStatic { - timer(dueTime: Date, period: number, scheduler: IScheduler): Observable; - timer(dueTime: Date, scheduler: IScheduler): Observable; + timer(dueTime: Date, period: number, scheduler?: IScheduler): Observable; + timer(dueTime: Date, scheduler?: IScheduler): Observable; generateWithAbsoluteTime( initialState: TState, From 7cdf2946399a3c631327ecc6f9b2300b1131de8c Mon Sep 17 00:00:00 2001 From: Justin Lan Date: Tue, 30 Sep 2014 17:35:58 -0700 Subject: [PATCH 147/149] Update signature of arguments to defined() The function passed in can take the index. --- d3/d3.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 3250f9c1e..f8ed80415 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1902,13 +1902,13 @@ declare module D3 { /** * Get the accessor function that controls where the line is defined. */ - (): (data: any, index ?: number) => boolean; + (): (data: any, index?: number) => boolean; /** * Set the accessor function that controls where the area is defined. * * @param defined The new accessor function */ - (defined: (data: any) => boolean): Line; + (defined: (data: any, index?: number) => boolean): Line; }; } @@ -2198,13 +2198,13 @@ declare module D3 { /** * Get the accessor function that controls where the area is defined. */ - (): (data: any) => any; + (): (data: any, index?: number) => any; /** * Set the accessor function that controls where the area is defined. * * @param defined The new accessor function */ - (defined: (data: any) => any): Area; + (defined: (data: any, index?: number) => any): Area; }; } From 30e71c2dab97fc0a15233ae7ad2a53c3690ef73c Mon Sep 17 00:00:00 2001 From: yar3333 Date: Wed, 1 Oct 2014 13:52:02 +0400 Subject: [PATCH 148/149] Update three.d.ts --- threejs/three.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index a9c33693c..f7593abe7 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -5604,7 +5604,7 @@ declare module THREE { cone: Mesh; setDirection(dir: Vector3): void; - setLength(length: number): void; + setLength(length: number, headLength?: number, headWidth?: number): void; setColor(hex: number): void; } From f5e81d0f098923bc4c1237b55d62e8fbc2e644e4 Mon Sep 17 00:00:00 2001 From: yar3333 Date: Wed, 1 Oct 2014 14:00:33 +0400 Subject: [PATCH 149/149] Box2 & Box3 fixes --- threejs/three.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index f7593abe7..9408fad57 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -2378,7 +2378,7 @@ declare module THREE { set(min: Vector2, max: Vector2): Box2; setFromPoints(points: Vector2[]): Box2; - setFromCenterAndSize(center: Vector2, size: number): Box2; + setFromCenterAndSize(center: Vector2, size: Vector2): Box2; copy(box: Box2): Box2; makeEmpty(): Box2; empty(): boolean; @@ -2408,7 +2408,7 @@ declare module THREE { set(min: Vector3, max: Vector3): Box3; setFromPoints(points: Vector3[]): Box3; - setFromCenterAndSize(center: Vector3, size: number): Box3; + setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; copy(box: Box3): Box3; makeEmpty(): Box3;