diff --git a/README.md b/README.md index 5c218aaa19..b188982fbf 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi * Directly from the GitHub repos * [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped) -* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd) +* [Typings - TypeScript Definition Manager](https://github.com/typings/typings) ## List of definitions @@ -32,7 +32,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi ## Requested definitions -Here is are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). +Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). ## License diff --git a/adal-angular/adal-tests.ts b/adal-angular/adal-tests.ts index 598134d0a0..3b9e46c961 100644 --- a/adal-angular/adal-tests.ts +++ b/adal-angular/adal-tests.ts @@ -12,4 +12,12 @@ var config : adal.Config = { var auth = new AuthenticationContext(config); +Logging.log = (message: string) => { + console.log(message); +} + +Logging.level = 4; + +auth.info("Logging message"); + var userName: string = auth.getCachedUser().userName; \ No newline at end of file diff --git a/adal-angular/adal.d.ts b/adal-angular/adal.d.ts index c5a64efd0b..76b86e7150 100644 --- a/adal-angular/adal.d.ts +++ b/adal-angular/adal.d.ts @@ -4,9 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var AuthenticationContext: adal.AuthenticationContextStatic; +declare var Logging: adal.Logging; declare module 'adal' { - export = AuthenticationContext; + export = { AuthenticationContext, Logging }; } declare namespace adal { @@ -36,6 +37,18 @@ declare namespace adal { stateResponse: string, requestType: string } + + interface Logging { + log: (message: string) => void; + level: LoggingLevel; + } + + enum LoggingLevel { + ERROR = 0, + WARNING = 1, + INFO = 2, + VERBOSE = 3 + } interface AuthenticationContextStatic { new (config: Config): AuthenticationContext; diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 4af35c6701..50389b9c72 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -95,6 +95,7 @@ declare namespace angular.material { onComplete?: Function; onRemoving?: Function; fullscreen?: boolean; + skipHide?: boolean; } interface IDialogService { diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 045f2f5994..51946281ce 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -72,7 +72,7 @@ declare namespace angular.translate { } interface ITranslateProvider extends angular.IServiceProvider { - translations(): ITranslationTable; + translations(key?: string): ITranslationTable; translations(key: string, translationTable: ITranslationTable): ITranslateProvider; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index f68cd60d14..60f595672f 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -43,7 +43,7 @@ declare namespace angular.animate { * @param container the container element that will capture each of the animation events that are fired on itself as well as among its children * @param callback the callback function that will be fired when the listener is triggered */ - on(event: string, container: JQuery, callback: Function): void; + on(event: string, container: JQuery, callback: (element?: JQuery, phase?: string) => any): void; /** * Deregisters an event listener based on the event which has been associated with the provided element. @@ -52,7 +52,7 @@ declare namespace angular.animate { * @param container the container element the event listener was placed on * @param callback the callback function that was registered as the listener */ - off(event: string, container?: JQuery, callback?: Function): void; + off(event: string, container?: JQuery, callback?: (element?: JQuery, phase?: string) => any): void; /** * Associates the provided element with a host parent element to allow the element to be animated even if it exists outside of the DOM structure of the Angular application. diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index c804519727..7eaf0be763 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -869,7 +869,7 @@ angular.module('docsTabsExample', []) angular.module('componentExample', []) .component('counter', { - require: ['^ctrl'], + require: {'ctrl': '^ctrl'}, bindings: { count: '=' }, diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 94d6678a24..1ae64c8e45 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -156,7 +156,7 @@ declare namespace angular { noop(...args: any[]): void; reloadWithDebugInfo(): void; - toJson(obj: any, pretty?: boolean): string; + toJson(obj: any, pretty?: boolean | number): string; uppercase(str: string): string; version: { full: string; @@ -1716,7 +1716,7 @@ declare namespace angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean | string | {[slot: string]: string}; - require?: string | string[] | {[controller: string]: string}; + require?: {[controller: string]: string}; } interface IComponentTemplateFn { diff --git a/applicationinsights-js/applicationinsights-js-tests.ts b/applicationinsights-js/applicationinsights-js-tests.ts index a852259539..b8f5ba7bec 100644 --- a/applicationinsights-js/applicationinsights-js-tests.ts +++ b/applicationinsights-js/applicationinsights-js-tests.ts @@ -27,7 +27,26 @@ var config: Microsoft.ApplicationInsights.IConfig = { cookieDomain: "" }; -var appInsights = new Microsoft.ApplicationInsights.AppInsights(config); +var appInsights: Microsoft.ApplicationInsights.IAppInsights = { + config: config, + context: null, + queue: null, + + startTrackPage(name?: string) { return null; }, + stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; }, + startTrackEvent(name: string) { return null }, + stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, + trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, + trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null }, + trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null }, + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null }, + trackTrace(message: string, properties?: { [name: string]: string; }) { return null }, + flush() { return null }, + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null }, + clearAuthenticatedUserContext() { return null }, + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null } +}; // trackPageView appInsights.trackPageView("page1"); @@ -68,7 +87,7 @@ appInsights.config.instrumentationKey = ""; // TelementryContext -var context = appInsights.context; +var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context; context.application.ver = "v0.0.0"; context.application.build = "1.1.1"; @@ -93,4 +112,46 @@ var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, context.track(envelope); -context.addTelemetryInitializer((envelope) => false); \ No newline at end of file +context.addTelemetryInitializer((envelope) => false); + +// track event +var eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null); +var eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj); +var eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType); +context.track(eventEnvelope); + +// track exception +var exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical); +var exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Exception.dataType, exceptionObj); +var exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType); +context.track(exceptionEnvelope); + +// track metric +var metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null); +var metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj); +var metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType); +context.track(metricEnvelope); + +// track page view +var pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null); +var pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj); +var pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType); +context.track(pageViewEnvelope); + +// track page view performance +var pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null); +var pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerfObj); +var pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType); +context.track(pageViewPerfEnvelope); + +// track remote dependency +var remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET"); +var remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, remoteDepObj); +var remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType); +context.track(pageViewPerfEnvelope); + +// track trace +var traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null); +var traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj); +var traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType); +context.track(traceEnvelope); \ No newline at end of file diff --git a/applicationinsights-js/applicationinsights-js.d.ts b/applicationinsights-js/applicationinsights-js.d.ts index f49863b35a..d9ad3c1c9d 100644 --- a/applicationinsights-js/applicationinsights-js.d.ts +++ b/applicationinsights-js/applicationinsights-js.d.ts @@ -3,146 +3,228 @@ // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module AI { + enum SeverityLevel { + Verbose = 0, + Information = 1, + Warning = 2, + Error = 3, + Critical = 4, + } + + enum DependencyKind { + SQL = 0, + Http = 1, + Other = 2, + } + + enum DependencySourceType { + Undefined = 0, + Aic = 1, + Apmc = 2, + } + + class StackFrame { + level: number; + method: string; + assembly: string; + fileName: string; + line: number; + constructor(); + } + + class ExceptionDetails { + id: number; + outerId: number; + typeName: string; + message: string; + hasFullStack: boolean; + stack: string; + parsedStack: StackFrame[]; + constructor(); + } + + enum DataPointType { + Measurement = 0, + Aggregation = 1, + } + + class DataPoint { + name: string; + kind: AI.DataPointType; + value: number; + count: number; + min: number; + max: number; + stdDev: number; + constructor(); + } + + class EventData extends Microsoft.Telemetry.Domain { + ver: number; + name: string; + properties: any; + measurements: any; + constructor(); + } + + class PageViewData extends AI.EventData { + ver: number; + url: string; + name: string; + duration: string; + referrer: string; + referrerData: string; + properties: any; + measurements: any; + constructor(); + } + + class PageViewPerfData extends AI.PageViewData { + ver: number; + url: string; + perfTotal: string; + name: string; + duration: string; + networkConnect: string; + referrer: string; + sentRequest: string; + referrerData: string; + receivedResponse: string; + domProcessing: string; + properties: any; + measurements: any; + constructor(); + } + + class RemoteDependencyData extends Microsoft.Telemetry.Domain { + ver: number; + name: string; + id: string; + resultCode: string; + kind: AI.DataPointType; + value: number; + count: number; + min: number; + max: number; + stdDev: number; + dependencyKind: AI.DependencyKind; + success: boolean; + async: boolean; + dependencySource: AI.DependencySourceType; + commandName: string; + dependencyTypeName: string; + properties: any; + constructor(); + } + + class MessageData extends Microsoft.Telemetry.Domain { + ver: number; + message: string; + severityLevel: AI.SeverityLevel; + properties: any; + constructor(); + } +} + declare module Microsoft.ApplicationInsights.Context { - class Application { + interface IApplication { /** * The application version. */ ver: string; - /** * The application build version. */ build: string; } - class Device { + interface IDevice { /** * The type for the current device. */ type: string; - /** * A device unique ID. */ id: string; - /** * The device OEM for the current device. */ oemName: string; - /** * The device model for the current device. */ model: string; - /** * The IANA interface type for the internet connected network adapter. */ network: number; - /** * The application screen resolution. */ resolution: string; - /** * The current display language of the operating system. */ locale: string; - /** * The IP address. */ ip: string; - /** * The device language. */ language: string; - /** * The OS name. */ os: string; - /** * The OS version. */ osversion: string; - - /** - * Constructs a new instance of the Device class - */ - constructor(); } - class User { + interface ILocation { /** - * The user ID. + * Client IP address for reverse lookup */ - id: string; + ip: string; + } + interface IInternal { /** - * Authenticated user id - */ - authenticatedId: string; - - /** - * The account ID. - */ - accountId: string; - - /** - * The account acquisition date. - */ - accountAcquisitionDate: string; - - /** - * The user agent string. - */ - agent: string; - - /** - * The store region. - */ - storeRegion: string; - - /** - * Sets the autheticated user id and the account id in this session. - * - * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. - * @param accountId {string} - An optional string to represent the account associated with the authenticated user. + * The SDK version used to create this telemetry item. */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): void; - + sdkVersion: string; /** - * Clears the authenticated user id and the account id from the user context. - * @returns {} + * The SDK agent version. */ - clearAuthenticatedUserContext(): void; - - constructor(config: ITelemetryConfig); + agentVersion: string; } - class Session { + interface ISample { /** - * The session ID. - */ - id: string; + * Sample rate + */ + sampleRate: number; + } + interface ISession { + /** + * The session ID. + */ + id: string; /** * The true if this is the first session */ isFirst: boolean; - /** * The date at which this guid was genereated. * Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time. */ acquisitionDate: number; - /** * The date at which this session ID was last reported. * This value should be updated whenever telemetry is sent using this ID. @@ -151,251 +233,449 @@ declare module Microsoft.ApplicationInsights.Context { renewalDate: number; } - class Location { + interface IOperation { /** - * Client IP address for reverse lookup - */ - ip: string; - } - - class Operation { - /** - * Unique id + * Operation id */ id: string; - - name: string; - - parentId: string; - - rootId: string; - /** - * String identifying the bot or test agent. + * Operation name + */ + name: string; + /** + * Parent operation id + */ + parentId: string; + /** + * Root operation id + */ + rootId: string; + /** + * Synthetic source of the operation */ syntheticSource: string; } + + interface IUser { + /** + * The telemetry configuration. + */ + config: any; + /** + * The user ID. + */ + id: string; + /** + * Authenticated user id + */ + authenticatedId: string; + /** + * The account ID. + */ + accountId: string; + /** + * The account acquisition date. + */ + accountAcquisitionDate: string; + /** + * The user agent string. + */ + agent: string; + /** + * The store region. + */ + storeRegion: string; + } } declare module Microsoft.Telemetry { - export class Base { - public baseType: string; - constructor() + class Domain { + constructor(); } - class Envelope { - public ver: number; - public name: string; - public time: string; - public sampleRate: number; - public seq: string; - public iKey: string; - public flags: number; - public deviceId: string; - public os: string; - public osVer: string; - public appId: string; - public appVer: string; - public userId: string; - public tags: any; - public data: Base; + class Base { + baseType: string; + constructor(); + } + class Data extends Microsoft.Telemetry.Base { + baseType: string; + baseData: TDomain; constructor(); } } +declare module Microsoft.ApplicationInsights.Telemetry { + + class Event implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + ver: number; + name: string; + properties: any; + measurements: any; + aiDataContract: { + ver: Microsoft.ApplicationInsights.FieldType; + name: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + measurements: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Constructs a new instance of the EventTelemetry object + */ + constructor(name: string, properties?: Object, measurements?: Object); + } + + class Exception implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + ver: number; + handledAt: string; + exceptions: AI.ExceptionDetails[]; + severityLevel: AI.SeverityLevel; + problemId: string; + crashThreadId: number; + properties: any; + measurements: any; + aiDataContract: { + ver: Microsoft.ApplicationInsights.FieldType; + handledAt: Microsoft.ApplicationInsights.FieldType; + exceptions: Microsoft.ApplicationInsights.FieldType; + severityLevel: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + measurements: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Constructs a new isntance of the ExceptionTelemetry object + */ + constructor(exception: Error, handledAt?: string, properties?: Object, measurements?: Object, severityLevel?: AI.SeverityLevel); + /** + * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. + */ + static CreateSimpleException(message: string, typeName: string, assembly: string, fileName: string, details: string, line: number, handledAt?: string): Telemetry.Exception; + } + + class Metric implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + ver: number; + metrics: AI.DataPoint[]; + properties: any; + aiDataContract: { + ver: Microsoft.ApplicationInsights.FieldType; + metrics: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Constructs a new instance of the MetricTelemetry object + */ + constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: Object); + } + + class PageView extends AI.PageViewData implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + aiDataContract: { + ver: Microsoft.ApplicationInsights.FieldType; + name: Microsoft.ApplicationInsights.FieldType; + url: Microsoft.ApplicationInsights.FieldType; + duration: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + measurements: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Constructs a new instance of the PageEventTelemetry object + */ + constructor(name?: string, url?: string, durationMs?: number, properties?: any, measurements?: any); + } + + class PageViewPerformance extends AI.PageViewPerfData implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + aiDataContract: { + ver: Microsoft.ApplicationInsights.FieldType; + name: Microsoft.ApplicationInsights.FieldType; + url: Microsoft.ApplicationInsights.FieldType; + duration: Microsoft.ApplicationInsights.FieldType; + perfTotal: Microsoft.ApplicationInsights.FieldType; + networkConnect: Microsoft.ApplicationInsights.FieldType; + sentRequest: Microsoft.ApplicationInsights.FieldType; + receivedResponse: Microsoft.ApplicationInsights.FieldType; + domProcessing: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + measurements: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Field indicating whether this instance of PageViewPerformance is valid and should be sent + */ + private isValid; + /** + * Indicates whether this instance of PageViewPerformance is valid and should be sent + */ + getIsValid(): boolean; + private durationMs; + /** + * Gets the total duration (PLT) in milliseconds. Check getIsValid() before using this method. + */ + getDurationMs(): number; + /** + * Constructs a new instance of the PageEventTelemetry object + */ + constructor(name: string, url: string, unused: number, properties?: any, measurements?: any); + static getPerformanceTiming(): PerformanceTiming; + /** + * Returns true is window performance timing API is supported, false otherwise. + */ + static isPerformanceTimingSupported(): PerformanceTiming; + /** + * As page loads different parts of performance timing numbers get set. When all of them are set we can report it. + * Returns true if ready, false otherwise. + */ + static isPerformanceTimingDataReady(): boolean; + static getDuration(start: any, end: any): number; + } + + class RemoteDependencyData extends AI.RemoteDependencyData implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + aiDataContract: { + id: Microsoft.ApplicationInsights.FieldType; + ver: Microsoft.ApplicationInsights.FieldType; + name: Microsoft.ApplicationInsights.FieldType; + kind: Microsoft.ApplicationInsights.FieldType; + value: Microsoft.ApplicationInsights.FieldType; + count: Microsoft.ApplicationInsights.FieldType; + min: Microsoft.ApplicationInsights.FieldType; + max: Microsoft.ApplicationInsights.FieldType; + stdDev: Microsoft.ApplicationInsights.FieldType; + dependencyKind: Microsoft.ApplicationInsights.FieldType; + success: Microsoft.ApplicationInsights.FieldType; + async: Microsoft.ApplicationInsights.FieldType; + dependencySource: Microsoft.ApplicationInsights.FieldType; + commandName: Microsoft.ApplicationInsights.FieldType; + dependencyTypeName: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + resultCode: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Constructs a new instance of the RemoteDependencyData object + */ + constructor(id: string, absoluteUrl: string, commandName: string, value: number, success: boolean, resultCode: number, method?: string); + private formatDependencyName(method, absoluteUrl); + } + + class Trace extends AI.MessageData implements Microsoft.ApplicationInsights.ISerializable { + static envelopeType: string; + static dataType: string; + aiDataContract: { + ver: Microsoft.ApplicationInsights.FieldType; + message: Microsoft.ApplicationInsights.FieldType; + severityLevel: Microsoft.ApplicationInsights.FieldType; + measurements: Microsoft.ApplicationInsights.FieldType; + properties: Microsoft.ApplicationInsights.FieldType; + }; + /** + * Constructs a new instance of the MetricTelemetry object + */ + constructor(message: string, properties?: Object); + } +} + declare module Microsoft.ApplicationInsights.Telemetry.Common { - class Envelope extends Microsoft.Telemetry.Envelope { + class Base extends Microsoft.Telemetry.Base implements Microsoft.ApplicationInsights.ISerializable { + /** + * The data contract for serializing this object. + */ + aiDataContract: {}; + } + + class Data extends Microsoft.Telemetry.Data implements Microsoft.ApplicationInsights.ISerializable { + /** + * The data contract for serializing this object. + */ + aiDataContract: { + baseType: FieldType; + baseData: FieldType; + }; + /** + * Constructs a new instance of telemetry data. + */ + constructor(type: string, data: TDomain); + } + + class Envelope implements IEnvelope { + ver: number; + name: string; + time: string; + sampleRate: number; + seq: string; + iKey: string; + flags: number; + deviceId: string; + os: string; + osVer: string; + appId: string; + appVer: string; + userId: string; + tags: any; + data: Base; + /** * The data contract for serializing this object. */ aiDataContract: any; - /** * Constructs a new instance of telemetry data. */ constructor(data: Microsoft.Telemetry.Base, name: string); } + + class DataSanitizer { + static sanitizeKeyAndAddUniqueness(key: any, map: any): any; + static sanitizeKey(name: any): any; + static sanitizeString(value: any): any; + static sanitizeUrl(url: any): any; + static sanitizeMessage(message: any): any; + static sanitizeException(exception: any): any; + static sanitizeProperties(properties: any): any; + static sanitizeMeasurements(measurements: any): any; + static padNumber(num: any): string; + } } - declare module Microsoft.ApplicationInsights { - - var Version: string; - interface IConfig { - // The key of your Application Insights resource in Azure - instrumentationKey: string; - - // The Application Insights server - endpointUrl: string; - - emitLineDelimitedJson: boolean; - - accountId: string; - - // A session is logged if the user is inactive for this time in milliseconds. Default 30 mins. - sessionRenewalMs: number; - - // A session is logged if it has continued for this time in milliseconds. Default 24h. - sessionExpirationMs: number; - - //Default 100k - maxBatchSizeInBytes: number; - - // Default 15s - maxBatchInterval: number; - - // If true, data is sent immediately and not batched. - enableDebug: boolean; - - // If true, telemetry data is not collected or sent. Default false. - disableTelemetry: boolean; - - verboseLogging: boolean; - - // Default 10s: - diagnosticLogInterval: number; - - samplingPercentage: number; - - autoTrackPageVisitTime: boolean; - - // If true, exceptions are not monitored. - disableExceptionTracking: boolean; - - // If true, ajax calls are not monitored. - disableAjaxTracking: boolean; - - // If true, default behavior of trackPageView is changed to record end of page view duration interval when - // trackPageView is called. If false and no custom duration is provided to trackPageView, the page view - // performance is calculated using the navigation timing API. - overridePageViewDuration: boolean; - - // Default 500 - controls how many ajax calls will be monitored per page view. - // Set to -1 to monitor all ajax calls on the page. - maxAjaxCallsPerView: number; - - disableDataLossAnalysis: boolean; - - disableCorrelationHeaders: boolean; - - disableFlushOnBeforeUnload: boolean; - - enableSessionStorageBuffer: boolean; - - // Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. - cookieDomain: string; + instrumentationKey?: string; + endpointUrl?: string; + emitLineDelimitedJson?: boolean; + accountId?: string; + sessionRenewalMs?: number; + sessionExpirationMs?: number; + maxBatchSizeInBytes?: number; + maxBatchInterval?: number; + enableDebug?: boolean; + disableExceptionTracking?: boolean; + disableTelemetry?: boolean; + verboseLogging?: boolean; + diagnosticLogInterval?: number; + samplingPercentage?: number; + autoTrackPageVisitTime?: boolean; + disableAjaxTracking?: boolean; + overridePageViewDuration?: boolean; + maxAjaxCallsPerView?: number; + disableDataLossAnalysis?: boolean; + disableCorrelationHeaders?: boolean; + disableFlushOnBeforeUnload?: boolean; + enableSessionStorageBuffer?: boolean; + cookieDomain?: string; + url?: string; } - interface ISenderConfig { + /** + * Enum is used in aiDataContract to describe how fields are serialized. + * For instance: (Fieldtype.Required | FieldType.Array) will mark the field as required and indicate it's an array + */ + enum FieldType { + Default = 0, + Required = 1, + Array = 2, + Hidden = 4, + } + + interface ISerializable { /** - * The url to which payloads will be sent + * The set of fields for a serializeable object. + * This defines the serialization order and a value of true/false + * for each field defines whether the field is required or not. */ - endpointUrl: () => string; + aiDataContract: any; + } + + interface IEnvelope extends ISerializable { + ver: number; + name: string; + time: string; + sampleRate: number; + seq: string; + iKey: string; + flags: number; + deviceId: string; + os: string; + osVer: string; + appId: string; + appVer: string; + userId: string; + tags: { + [name: string]: any; + }; + } + + interface ITelemetryContext { /** - * The JSON format (normal vs line delimited). True means line delimited JSON. + * The object describing a component tracked by this object. */ - emitLineDelimitedJson: () => boolean; - /** - * The maximum size of a batch in bytes - */ - maxBatchSizeInBytes: () => number; - /** - * The maximum interval allowed between calls to batchInvoke - */ - maxBatchInterval: () => number; - /** - * The master off switch. Do not send any data if set to TRUE - */ - disableTelemetry: () => boolean; - /** - * Store a copy of a send buffer in the session storage - */ - enableSessionStorageBuffer: () => boolean; - } - - interface ITelemetryConfig extends ISenderConfig { - instrumentationKey: () => string; - accountId: () => string; - sessionRenewalMs: () => number; - sessionExpirationMs: () => number; - sampleRate: () => number; - endpointUrl: () => string; - cookieDomain: () => string; - } - - - class TelemetryContext { - /** - * The object describing a component tracked by this object. - */ - application: Context.Application; - + application: Context.IApplication; /** * The object describing a device tracked by this object. */ - device: Context.Device; - + device: Context.IDevice; /** - * The object describing a user tracked by this object. - */ - user: Context.User; - - /** - * The object describing a session tracked by this object. - */ - session: Context.Session; - + * The object describing internal settings. + */ + internal: Context.IInternal; /** * The object describing a location tracked by this object. */ - location: Context.Location; - + location: Context.ILocation; /** * The object describing a operation tracked by this object. */ - operation: Context.Operation; - + operation: Context.IOperation; /** - * Use Sender.ts to send telemetry object to the endpoint + * The object describing sampling settings. + */ + sample: Context.ISample; + /** + * The object describing a user tracked by this object. */ - track(envelope: Telemetry.Common.Envelope): Telemetry.Common.Envelope; - + user: Context.IUser; + /** + * The object describing a session tracked by this object. + */ + session: Context.ISession; /** * Adds telemetry initializer to the collection. Telemetry initializers will be called one by one * before telemetry item is pushed for sending and in the order they were added. */ - addTelemetryInitializer(telemetryInitializer: (envelope: Telemetry.Common.Envelope) => boolean): void; + addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean): any; + /** + * Tracks telemetry object. + */ + track(envelope: Microsoft.ApplicationInsights.IEnvelope): any; } - /** - * The main API that sends telemetry to Application Insights. - * Learn more: http://go.microsoft.com/fwlink/?LinkID=401493 - */ - class AppInsights { - constructor(config: IConfig); - + interface IAppInsights { config: IConfig; - - context: TelemetryContext; - + context: ITelemetryContext; + queue: (() => void)[]; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. - * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. - */ - startTrackPage(name?: string): void; - + * Starts timing how long the user views a page or other item. Call this when the page opens. + * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. + */ + startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. - * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. - * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - stopTrackPage(name?: string, url?: string, properties?: Object, measurements?: Object): void; - + * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. + * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. + * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + stopTrackPage(name?: string, url?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; /** * Logs that a page or other item was viewed. * @param name The string you used as the name in startTrackPage. Defaults to the document title. @@ -404,39 +684,61 @@ declare module Microsoft.ApplicationInsights { * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. * @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. */ - trackPageView(name?: string, url?: string, properties?: Object, measurements?: Object, duration?: number): void; - + trackPageView(name?: string, url?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }, duration?: number): any; /** * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. * @param name A string that identifies this event uniquely within the document. */ - startTrackEvent(name: string): void; - + startTrackEvent(name: string): any; /** * Log an extended event that you started timing with {@link startTrackEvent}. * @param name The string you used to identify this event in startTrackEvent. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ - stopTrackEvent(name: string, properties?: Object, measurements?: Object): void; - + stopTrackEvent(name: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; /** - * Log a user action or other occurrence. - * @param name A string to identify this event in the portal. - * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - trackEvent(name: string, properties?: Object, measurements?: Object): void; - - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): void; - + * Log a user action or other occurrence. + * @param name A string to identify this event in the portal. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + trackEvent(name: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; + /** + * Log an AJAX request + * @param id Event id + * @param absoluteUrl Full url + * @param pathName Leave this parameter blank + * @param totalTime Total time it took for AJAX request to complete + * @param success Whether AJAX request succeeded or failed + * @param resultCode Result code returned from AJAX call + * @param method HTTP verb that was used (GET, POST) + */ + trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + * @param severityLevel AI.SeverityLevel - severity level */ - trackException(exception: Error, handledAt?: string, properties?: Object, measurements?: Object): void; + trackException(exception: Error, handledAt?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }, severityLevel?: AI.SeverityLevel): any; /** * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the @@ -447,34 +749,34 @@ declare module Microsoft.ApplicationInsights { * @param min The smallest measurement in the sample. Defaults to the average. * @param max The largest measurement in the sample. Defaults to the average. */ - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: Object): void; - + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { + [name: string]: string; + }): any; /** * Log a diagnostic message. * @param message A message string * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ - trackTrace(message: string, properties?: Object): void; - + trackTrace(message: string, properties?: { + [name: string]: string; + }): any; /** * Immediately send all queued telemetry. */ - flush(): void; - + flush(): any; /** - * Sets the autheticated user id and the account id in this session. - * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. - * - * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. - * @param accountId {string} - An optional string to represent the account associated with the authenticated user. - */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): void; - + * Sets the autheticated user id and the account id in this session. + * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. + * + * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. + * @param accountId {string} - An optional string to represent the account associated with the authenticated user. + */ + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; /** * Clears the authenticated user id and the account id from the user context. */ - clearAuthenticatedUserContext(): void; - + clearAuthenticatedUserContext(): any; + downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void; /** * The custom error handler for Application Insights * @param {string} message - The error message @@ -483,6 +785,6 @@ declare module Microsoft.ApplicationInsights { * @param {number} columnNumber - The column number for the line where the error was raised * @param {Error} error - The Error object */ - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): void; + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any; } } diff --git a/avoscloud-sdk/avoscloud-sdk.d.ts b/avoscloud-sdk/avoscloud-sdk.d.ts index c3bd03e570..af904a6c8c 100644 --- a/avoscloud-sdk/avoscloud-sdk.d.ts +++ b/avoscloud-sdk/avoscloud-sdk.d.ts @@ -797,3 +797,8 @@ declare module "avoscloud-sdk" { export = AV; } + +declare module 'leanengine' { + import alias = require('avoscloud-sdk'); + export = alias; +} diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index a13e03fe7a..5946d25982 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -18,6 +18,10 @@ declare module "aws-sdk" { accessKeyId: string; } + export class EnvironmentCredentials extends Credentials { + constructor(profile: string); + } + export interface Logger { write?: (chunk: any, encoding?: string, callback?: () => void) => void; log?: (...messages: any[]) => void; @@ -86,6 +90,8 @@ declare module "aws-sdk" { export interface ClientConfigPartial extends Services { credentials?: Credentials; region?: string; + accessKeyId: string; + secretAccessKey: string; computeChecksums?: boolean; convertResponseTypes?: boolean; logger?: Logger; @@ -138,9 +144,9 @@ declare module "aws-sdk" { export class SNS { constructor(options?: any); - public client: Sns.Client; + publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; } - + export class SimpleWorkflow { constructor(options?: any); public client: Swf.Client; @@ -152,6 +158,51 @@ declare module "aws-sdk" { getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; } + export class STS{ + constructor(options?: any); + + /** + * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you can use to access AWS resources that you might not normally have access to. + */ + assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: any) => void): void; + + /** + * Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response. + */ + assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void; + + /** + * Returns a set of temporary security credentials for users who have been authenticated in a mobile or web application with a web identity provider, such as Amazon Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible identity provider. + */ + assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void; + + /** + * Creates a credentials object from STS response data containing credentials information. + */ + credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void; + + /** + * Decodes additional information about the authorization status of a request from an encoded message returned in response to an AWS request. + */ + decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void; + + /** + * Returns details about the IAM identity whose credentials are used to call the API. + */ + getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void; + + /** + * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) for a federated user. + */ + getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void; + + /** + * Returns a set of temporary credentials for an AWS account or IAM user. + */ + getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void; + + } + export class ECS { constructor(options?: any); /** @@ -1345,4 +1396,60 @@ declare module "aws-sdk" { taskDefinition: string; } } + + export module sts { + export interface AssumeRoleParams { + RoleArn: string; + RoleSessionName: string; + DurationSeconds?: number; + ExternalId?: string; + Policy?: string; + SerialNumber?: string; + TokenCode?: string; + } + + export interface AssumeRoleWithSAMLParams { + PrincipalArn: string; + RoleArn: string; + SAMLAssertion: string; + DurationSeconds?: number; + Policy?: string; + } + + export interface AssumeRoleWithWebIdentityParams { + RoleArn: string; + RoleSessionName: string; + WebIdentityToken: string; + DurationSeconds?: number; + Policy?: string; + ProviderId?: string; + } + + export interface CredentialsFromParams { + /** + * Data retrieved from a call to AWS.STS.getFederatedToken, getSessionToken(), assumeRole(), or assumeRoleWithWebIdentity(). + */ + Data: any; + /** + * An optional credentials object to fill instead of creating a new object. Useful when modifying an existing credentials object from a refresh call. + */ + Credentials?: Credentials + } + + export interface DecodeAuthorizationMessageParams { + EncodedMessage: string; + } + + export interface GetFederationTokenParams { + Name: string; + DurationSeconds?: number, + Policy?: string + } + + export interface GetSessionTokenParams { + DurationSeconds: number, + SerialNumber: string; + TokenCode: string; + } + } } diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index b9749002c9..afd6014598 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -7,10 +7,11 @@ declare namespace Microsoft.WindowsAzure { // MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx interface MobileServiceClient { - new (applicationUrl: string, applicationKey: string): MobileServiceClient; + new (applicationUrl: string, applicationKey?: string): MobileServiceClient; applicationUrl: string; applicationKey: string; currentUser: User; + push: Push; //for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google' login(provider: string, token: string, callback: (error: any, user: User) => void ): void; login(provider: string, token: string): asyncPromise; @@ -18,8 +19,40 @@ declare namespace Microsoft.WindowsAzure { login(provider: string): asyncPromise; logout(): void; getTable(tableName: string): MobileServiceTable; - withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient; - invokeApi(apiName: string, options?:InvokeApiOptions): asyncPromise; + withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient; + /** + * Invokes the specified custom api and returns a response object. + * + * @param apiName The custom api to invoke. + * @param options Contains additional parameter information, valid values are: + * body: The body of the HTTP request. + * method: The HTTP method to use in the request, with the default being POST, + * parameters: Any additional query string parameters, + * headers: HTTP request headers, specified as an object. + * @param callback Optional callback accepting (error, results) parameters. + */ + invokeApi(apiName: string, options?: InvokeApiOptions, callback?: (error: any, results: any) => void): asyncPromise; + } + + interface Push + { + /** + * Register a push channel with the Mobile Apps backend to start receiving notifications. + * + * @param platform The device platform being used - wns, gcm or apns. + * @param pushChannel The push channel identifier or URI. + * @param templates An object containing template definitions. Template objects should contain body, headers and tags properties. + * @param secondaryTiles An object containing template definitions to be used with secondary tiles when using WNS. + * @param callback Optional callback accepting (error, results) parameters. + */ + register(platform: string, pushChannel: string, templates?: any, secondaryTiles?: any, callback?: (error: any, results: any) => void): void; + /** + * Invokes the specified custom api and returns a response object. + * + * @param pushChannel The push channel identifier or URI. + * @param callback Optional callback accepting (error, results) parameters. + */ + unregister(pushChannel: string, callback?: (error: any, results: any) => void): void; } interface InvokeApiOptions @@ -36,6 +69,7 @@ declare namespace Microsoft.WindowsAzure { accessTokens: any; // { [providerName: string]: string; } level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated' userId: string; + mobileServiceAuthenticationToken: string; } diff --git a/babelify/babelify-tests.ts b/babelify/babelify-tests.ts new file mode 100644 index 0000000000..6ace8462a9 --- /dev/null +++ b/babelify/babelify-tests.ts @@ -0,0 +1,23 @@ +/// + +import babelify = require("babelify"); + +module BabelifyTest { + + export function whatDidTheEs6Say(srcPath: string, opts?: babelify.BabelifyOptions) { + opts.extensions = opts.extensions || undefined; + opts.sourceMapsAbsolute = opts.sourceMapsAbsolute || false; + var dst: NodeJS.ReadWriteStream; + + babelify(""); // 'opts' are optional + + babelify(srcPath, opts).on("error", function (err: any) { + console.error("babelify error: ", err); + }); + + babelify.configure(opts)(srcPath).pipe(dst); + } + +} + +export = BabelifyTest; \ No newline at end of file diff --git a/babelify/babelify.d.ts b/babelify/babelify.d.ts new file mode 100644 index 0000000000..2637814a64 --- /dev/null +++ b/babelify/babelify.d.ts @@ -0,0 +1,46 @@ +// Type definitions for babelify v7.3.0 +// Project: https://github.com/babel/babelify +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +/** Browserify transform for Babel + */ +declare module 'babelify' { + import stream = require("stream"); + import babel = require("babel-core"); + + + function Babelify(filename: string, opts?: Babelify.BabelifyOptions): Babelify.BabelifyObject; + + module Babelify { + + export interface BabelifyConstructor { + (filename: string, opts: Babelify.BabelifyOptions): Babelify.BabelifyObject; + } + + /** In addition to the various purposes documented here, all of the babelify options are passed to babel which passes them on to babel.transform() when each file is transformed */ + export interface BabelifyOptions extends babel.TransformOptions { + /** These are passed to babel.util.canCompile() for each filename + * default: null + */ + extensions?: string | string[]; + + /** if true, a 'sourceFileName' property with a value equal to the current file being transformed is included with the options passed to babel.transform() + * default: false + */ + sourceMapsAbsolute?: boolean; + } + + export class BabelifyObject extends stream.Transform { + _transform(buf: string | Buffer, encoding: string, callback: () => void): void; + _flush(callback: () => void): void; + } + + export function configure(opts: Babelify.BabelifyOptions): (filename: string) => Babelify.BabelifyObject; + } + + export = Babelify; +} diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index ef0a10f006..9cf1cb49b8 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -147,7 +147,6 @@ declare namespace Backbone { /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; - change(): any; changedAttributes(attributes?: any): any[]; clear(options?: Silenceable): any; clone(): Model; @@ -173,8 +172,12 @@ declare namespace Backbone { invert(): any; pick(keys: string[]): any; pick(...keys: string[]): any; + pick(fn: (value: any, key: any, object: any) => any): any; omit(keys: string[]): any; omit(...keys: string[]): any; + omit(fn: (value: any, key: any, object: any) => any): any; + chain(): any; + isEmpty(): boolean; } class Collection extends ModelBase { @@ -223,58 +226,72 @@ declare namespace Backbone { private _removeReference(model: TModel): void; private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; + /** + * Return a shallow copy of this collection's models, using the same options as native Array#slice. + */ + slice(min: number, max?: number): TModel[]; + // mixins from underscore - all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; + all(iterator?: _.ListIterator, context?: any): boolean; + any(iterator?: _.ListIterator, context?: any): boolean; chain(): any; - contains(value: any): boolean; - countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; - countBy(attribute: string): _.Dictionary; - detect(iterator: (item: any) => boolean, context?: any): any; // ??? - drop(): TModel; - drop(n: number): TModel[]; - each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; - every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; - find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; + collect(iterator: _.ListIterator, context?: any): TResult[]; + contains(value: TModel): boolean; + countBy(iterator?: _.ListIterator): _.Dictionary; + countBy(iterator: string): _.Dictionary; + detect(iterator: _.ListIterator, context?: any): TModel; + difference(others: TModel[]): TModel[]; + drop(n?: number): TModel[]; + each(iterator: _.ListIterator, context?: any): TModel[]; + every(iterator: _.ListIterator, context?: any): boolean; + filter(iterator: _.ListIterator, context?: any): TModel[]; + find(iterator: _.ListIterator, context?: any): TModel; + findIndex(predicate: _.ListIterator, context?: any): number; + findLastIndex(predicate: _.ListIterator, context?: any): number; first(): TModel; first(n: number): TModel[]; - foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; - groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; - groupBy(attribute: string, context?: any): _.Dictionary; - include(value: any): boolean; - indexOf(element: TModel, isSorted?: boolean): number; + foldl(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + foldr(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + forEach(iterator: _.ListIterator, context?: any): TModel[]; + groupBy(iterator: _.ListIterator, context?: any): _.Dictionary; + groupBy(iterator: string, context?: any): _.Dictionary; + head(): TModel; + head(n: number): TModel[]; + include(value: TModel): boolean; + includes(value: TModel): boolean; + indexBy(iterator: _.ListIterator, context?: any): _.Dictionary; + indexBy(iterator: string, context?: any): _.Dictionary; + indexOf(value: TModel, isSorted?: boolean): number; initial(): TModel; initial(n: number): TModel[]; - inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - isEmpty(object: any): boolean; - invoke(methodName: string, args?: any[]): any; + inject(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + invoke(methodName: string, ...args: any[]): any; + isEmpty(): boolean; last(): TModel; last(n: number): TModel[]; - lastIndexOf(element: TModel, fromIndex?: number): number; - map(iterator: (element: TModel, index: number, context?: any) => any, context?: any): any[]; - max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - select(iterator: any, context?: any): any[]; + lastIndexOf(value: TModel, from?: number): number; + map(iterator: _.ListIterator, context?: any): TResult[]; + max(iterator?: _.ListIterator, context?: any): TModel; + min(iterator?: _.ListIterator, context?: any): TModel; + partition(iterator: _.ListIterator): TModel[][]; + reduce(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + reduceRight(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + reject(iterator: _.ListIterator, context?: any): TModel[]; + rest(n?: number): TModel[]; + sample(): TModel; + sample(n: number): TModel[]; + select(iterator: _.ListIterator, context?: any): TModel[]; + shuffle(): TModel[]; size(): number; - shuffle(): any[]; - slice(min: number, max?: number): TModel[]; - some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; - sortBy(attribute: string, context?: any): TModel[]; - sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; - reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; - reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; - rest(): TModel; - rest(n: number): TModel[]; - tail(): TModel; - tail(n: number): TModel[]; - toArray(): any[]; - without(...values: any[]): TModel[]; + some(iterator?: _.ListIterator, context?: any): boolean; + sortBy(iterator?: _.ListIterator, context?: any): TModel[]; + sortBy(iterator: string, context?: any): TModel[]; + tail(n?: number): TModel[]; + take(): TModel; + take(n: number): TModel[]; + toArray(): TModel[]; + without(...values: TModel[]): TModel[]; } class Router extends Events { @@ -370,7 +387,6 @@ declare namespace Backbone { $(selector: any): JQuery; render(): View; remove(): View; - make(tagName: any, attributes?: any, content?: any): any; delegateEvents(events?: EventsHash): any; delegate(eventName: string, selector: string, listener: Function): View; undelegateEvents(): any; diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 50632712a6..bd961c1c89 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -90,6 +90,25 @@ function test_models() { note.set({ title: "March 20", content: "In his eyes she eclipses..." }); note.set("title", "A Scandal in Bohemia"); + + let strings: string[] + let value: any; + let values: any[]; + let bool: boolean; + + // underscore methods + strings = note.keys(); + values = note.values(); + values = note.pairs(); + values = note.invert(); + value = note.pick("foo"); + value = note.pick("foo", "bar"); + value = note.pick((value: any, key: any, object: any) => true); + value = note.omit("foo"); + value = note.omit("foo", "bar"); + value = note.omit((value: any, key: any, object: any) => true); + value = note.chain().pick().omit().value(); + bool = note.isEmpty(); } class Employee extends Backbone.Model { @@ -161,6 +180,78 @@ function test_collection() { book.get("published") === true); var alphabetical = books.sortBy((book: Book): number => null); + + let one: Book; + let models: Book[]; + let bool: boolean; + let numDict: _.Dictionary; + let modelDict: _.Dictionary; + let modelsDict: _.Dictionary; + let num: number; + + models = books.slice(1); + models = books.slice(1, 3); + + // underscore methods + bool = books.all((value: Book, index: number, list: Book[]) => true); + bool = books.any((value: Book, index: number, list: Book[]) => true); + bool = books.chain().any((value: Book, index: number, list: Book[]) => true).value(); + models = books.collect((value: Book, index: number, list: Book[]) => value); + bool = books.contains(book1); + numDict = books.countBy((value: Book, index: number, list: Book[]) => true); + numDict = books.countBy("foo"); + one = books.detect((value: Book, index: number, list: Book[]) => true); + models = books.difference([book1]); + models = books.drop(); + models = books.each((value: Book, index: number, list: Book[]) => true); + bool = books.every((value: Book, index: number, list: Book[]) => true); + models = books.filter((value: Book, index: number, list: Book[]) => true); + one = books.find((value: Book, index: number, list: Book[]) => true); + num = books.findIndex((value: Book, index: number, list: Book[]) => true); + num = books.findLastIndex((value: Book, index: number, list: Book[]) => true); + one = books.first(); + models = books.first(3); + models = books.foldl((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.foldr((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.forEach((value: Book, index: number, list: Book[]) => true); + modelsDict = books.groupBy((value: Book, index: number, list: Book[]) => true); + modelsDict = books.groupBy("foo"); + one = books.head(); + models = books.head(3); + bool = books.include(book1); + bool = books.includes(book1); + modelDict = books.indexBy((value: Book, index: number, list: Book[]) => true); + modelDict = books.indexBy("foo"); + num = books.indexOf(book1, true); + one = books.initial(); + models = books.initial(3); + models = books.inject((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + one = books.invoke("at", 3); + bool = books.isEmpty(); + one = books.last(); + models = books.last(3); + num = books.lastIndexOf(book1, 3); + models = books.map((value: Book, index: number, list: Book[]) => value); + one = books.max((value: Book, index: number, list: Book[]) => value); + one = books.min((value: Book, index: number, list: Book[]) => value); + [models] = books.partition((value: Book, index: number, list: Book[]) => true); + models = books.reduce((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.reduceRight((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.reject((value: Book, index: number, list: Book[]) => true); + models = books.rest(3); + one = books.sample(); + models = books.sample(3); + models = books.select((value: Book, index: number, list: Book[]) => true); + models = books.shuffle(); + num = books.size(); + bool = books.some((value: Book, index: number, list: Book[]) => true); + models = books.sortBy((value: Book, index: number, list: Book[]) => value); + models = books.sortBy("foo"); + models = books.tail(3); + one = books.take(); + models = books.take(3); + models = books.toArray(); + models = books.without(book1, book1); } ////////// diff --git a/backbone/backbone-with-lodash-tests.ts b/backbone/backbone-with-lodash-tests.ts index e0b04880bf..0ac4efe375 100644 --- a/backbone/backbone-with-lodash-tests.ts +++ b/backbone/backbone-with-lodash-tests.ts @@ -91,6 +91,25 @@ function test_models() { note.set({ title: "March 20", content: "In his eyes she eclipses..." }); note.set("title", "A Scandal in Bohemia"); + + let strings: string[] + let value: any; + let values: any[]; + let bool: boolean; + + // underscore methods + strings = note.keys(); + values = note.values(); + values = note.pairs(); + values = note.invert(); + value = note.pick("foo"); + value = note.pick("foo", "bar"); + value = note.pick((value: any, key: any, object: any) => true); + value = note.omit("foo"); + value = note.omit("foo", "bar"); + value = note.omit((value: any, key: any, object: any) => true); + value = note.chain().pick().omit().value(); + bool = note.isEmpty(); } class Employee extends Backbone.Model { @@ -152,6 +171,78 @@ function test_collection() { book.get("published") === true); var alphabetical = books.sortBy((book: Book): number => null); + + let one: Book; + let models: Book[]; + let bool: boolean; + let numDict: _.Dictionary; + let modelDict: _.Dictionary; + let modelsDict: _.Dictionary; + let num: number; + + models = books.slice(1); + models = books.slice(1, 3); + + // underscore methods + bool = books.all((value: Book, index: number, list: Book[]) => true); + bool = books.any((value: Book, index: number, list: Book[]) => true); + bool = books.chain().any((value: Book, index: number, list: Book[]) => true).value(); + models = books.collect((value: Book, index: number, list: Book[]) => value); + bool = books.contains(book1); + numDict = books.countBy((value: Book, index: number, list: Book[]) => true); + numDict = books.countBy("foo"); + one = books.detect((value: Book, index: number, list: Book[]) => true); + models = books.difference([book1]); + models = books.drop(); + models = books.each((value: Book, index: number, list: Book[]) => true); + bool = books.every((value: Book, index: number, list: Book[]) => true); + models = books.filter((value: Book, index: number, list: Book[]) => true); + one = books.find((value: Book, index: number, list: Book[]) => true); + num = books.findIndex((value: Book, index: number, list: Book[]) => true); + num = books.findLastIndex((value: Book, index: number, list: Book[]) => true); + one = books.first(); + models = books.first(3); + models = books.foldl((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.foldr((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.forEach((value: Book, index: number, list: Book[]) => true); + modelsDict = books.groupBy((value: Book, index: number, list: Book[]) => true); + modelsDict = books.groupBy("foo"); + one = books.head(); + models = books.head(3); + bool = books.include(book1); + bool = books.includes(book1); + modelDict = books.indexBy((value: Book, index: number, list: Book[]) => true); + modelDict = books.indexBy("foo"); + num = books.indexOf(book1, true); + one = books.initial(); + models = books.initial(3); + models = books.inject((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + one = books.invoke("at", 3); + bool = books.isEmpty(); + one = books.last(); + models = books.last(3); + num = books.lastIndexOf(book1, 3); + models = books.map((value: Book, index: number, list: Book[]) => value); + one = books.max((value: Book, index: number, list: Book[]) => value); + one = books.min((value: Book, index: number, list: Book[]) => value); + [models] = books.partition((value: Book, index: number, list: Book[]) => true); + models = books.reduce((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.reduceRight((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []); + models = books.reject((value: Book, index: number, list: Book[]) => true); + models = books.rest(3); + one = books.sample(); + models = books.sample(3); + models = books.select((value: Book, index: number, list: Book[]) => true); + models = books.shuffle(); + num = books.size(); + bool = books.some((value: Book, index: number, list: Book[]) => true); + models = books.sortBy((value: Book, index: number, list: Book[]) => value); + models = books.sortBy("foo"); + models = books.tail(3); + one = books.take(); + models = books.take(3); + models = books.toArray(); + models = books.without(book1, book1); } ////////// diff --git a/base64-js/base64-js-tests.ts b/base64-js/base64-js-tests.ts new file mode 100644 index 0000000000..6852ddb626 --- /dev/null +++ b/base64-js/base64-js-tests.ts @@ -0,0 +1,6 @@ +/// + +import * as base64js from 'base64-js'; + +const bytes: Uint8Array = base64js.toByteArray('shemp'); +const decoded: string = base64js.fromByteArray(new Uint8Array(0)); diff --git a/base64-js/base64-js.d.ts b/base64-js/base64-js.d.ts new file mode 100644 index 0000000000..cc7d2165c8 --- /dev/null +++ b/base64-js/base64-js.d.ts @@ -0,0 +1,10 @@ +// Type definitions for base64-js v1.1.2 +// Project: https://github.com/beatgammit/base64-js +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'base64-js' { + + export function toByteArray(encoded: string): Uint8Array; + export function fromByteArray(bytes: Uint8Array): string; +} diff --git a/bingmaps/Microsoft.Maps.d.ts b/bingmaps/Microsoft.Maps.d.ts index 95e39a043e..1e7e464930 100644 --- a/bingmaps/Microsoft.Maps.d.ts +++ b/bingmaps/Microsoft.Maps.d.ts @@ -174,6 +174,7 @@ declare namespace Microsoft.Maps { fixedMapPosition?: boolean; height?: number; inertiaIntensity?: number; + navigationBarMode?: number; showBreadcrumb?: boolean; showCopyright?: boolean; showDashboard?: boolean; @@ -216,6 +217,12 @@ declare namespace Microsoft.Maps { getY(): number; } + export enum NavigationBarMode { + default, + compact, + minified + } + export enum PixelReference { control, page, @@ -307,6 +314,7 @@ declare namespace Microsoft.Maps { getZIndex(): number; setHtmlContent(content: string): void; setLocation(location: Location): void; + setMap(map: Map): void; setOptions(options: InfoboxOptions): void; toString(): string; } diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 16f639dfaf..f7e691a365 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -33,7 +33,7 @@ declare module "body-parser" { /** * passed to JSON.parse(). */ - receiver?: (key: string, value: any) => any; + reviver?: (key: string, value: any) => any; /** * parse extended syntax with the qs module. (default: true) */ @@ -65,7 +65,7 @@ declare module "body-parser" { /** * passed to JSON.parse(). */ - receiver?: (key: string, value: any) => any; + reviver?: (key: string, value: any) => any; }): express.RequestHandler; export function raw(options?: { diff --git a/bootstrap-fileinput/bootstrap-fileinput.d.ts b/bootstrap-fileinput/bootstrap-fileinput.d.ts new file mode 100644 index 0000000000..fadfadd612 --- /dev/null +++ b/bootstrap-fileinput/bootstrap-fileinput.d.ts @@ -0,0 +1,1039 @@ +// Type definitions for bootstrap-fileinput +// Project: https://github.com/kartik-v/bootstrap-fileinput +// Definitions by: Ché Coxshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; +} + + +declare module BootstrapFileInput { + interface FileInputOptions { + /** + Language configuration for the plugin to enable the plugin to display messages for your locale (you must set the ISO code for the language). + You can have multiple language widgets on the same page. + The locale JS file for the language code must be defined as mentioned in the translations section: http://plugins.krajee.com/file-input#translations + */ + language?: string; + /** + Whether to display the file caption. + Defaults to true. + */ + showCaption?: boolean; + /** + Whether to display the file preview. + Defaults to true. + */ + showPreview?: boolean; + /** + Whether to display the file remove/clear button. + Defaults to true. + */ + showRemove?: boolean; + /** + Whether to display the file upload button. + Defaults to true. + This will default to a form submit button, unless the uploadUrl is specified. + */ + showUpload?: boolean; + /** + Whether to display the file upload cancel button. + Defaults to true. + This will be only enabled and displayed when an AJAX upload is in process. + */ + showCancel?: boolean; + /** + Whether to display the close icon in the preview. + Defaults to true. + This will be only parsed when showPreview is true or when you are using the {close} tag in your preview templates. + */ + showClose?: boolean; + /** + Whether to persist display of the uploaded file thumbnails in the preview window (for ajax uploads) until the remove/clear button is pressed. + Defaults to true. + When set to false, a next batch of files selected for upload will clear these thumbnails from preview. + */ + showUploadedThumbs?: boolean; + /** + Whether to automatically replace the files in the preview after the maxFileCount limit is reached and a new set of file(s) is/are selected. + This will only work if a valid maxFileCount is set. + Defaults to false. + */ + autoReplace?: boolean; + /** + Any additional CSS class to append to the caption container. + */ + captionClass?: string; + /** + Any additional CSS class to append to the preview container. + */ + previewClass?: string; + /** + Any additional CSS class to append to the main plugin container. + */ + mainClass?: string; + /** + The initial preview content to be displayed. + You can pass the minimal HTML markup for displaying your image, text, or file. + If set as a string, this will display a single file in the initial preview if there is no delimiter. You can set a delimiter (as defined in initialDelimiter) to show multiple files in initial preview. + If set as an array, it will display all files in the array as an initial preview (useful for multiple file upload scenarios). + The following CSS classes will need to be added for displaying each file type as per the plugin style theme: + image files: Include CSS class file-preview-image + text files: Include CSS class file-preview-text + other files: Include CSS class file-preview-other + */ + initialPreview?: string | any[]; + /** + the count of initial preview items that will be added to the count of files selected in preview. This is applicable when displaying the right caption, when overwriteInitial is set to false. + */ + initialPreviewCount?: number; + /** + the delimiter to be used for splitting the initial preview content as individual file thumbnails (applicable only if initialPreview is passed as a string instead of array). Defaults to *$$*. + */ + initialPreviewDelimiter?: string; + /** + the configuration for setting up important properties for each initialPreview item (that is setup as part of initialPreview). + */ + initialPreviewConfig?: PreviewConfig[]; + /** + whether the delete button will be displayed for each thumbnail that has been created with initialPreview. + */ + initialPreviewShowDelete?: boolean; + /** + whether the file thumbnail should be removed from preview on error. Defaults to false. + */ + removeFromPreviewOnError?: boolean; + /** + this will be a list of tags used in thumbnail templates that will be replaced dynamically within the thumbnail markup, when the thumbnail is rendered. + */ + previewThumbTags?: { [key: string]: string; } + /** + this is an extension of previewThumbTags specifically for initial preview content - but will be configured as an array of objects corresponding to each initial preview thumbnail. The initial preview thumbnails set via initialPreview will read this configuration for replacing tags. + */ + initialPreviewThumbTags?: { [key: string]: string; } + /** + the extra data that will be passed as data to the initial preview delete url/AJAX server call via POST. + This will be overridden by the initialPreviewConfig['extra'] property. + This property is only applicable for ajax deletions in initial preview and when you have set a value for initialPreviewConfig['url'] or deleteUrl. + This can be setup either as an object (associative array of keys and values) or as a function callback. + Note + The ajax delete action will send the following data to server via POST: + key: the key setting as setup in initialPreviewConfig['key'] + any other extra data passed as key: value pairs either via initialPreviewConfig['extra'] OR deleteExtraData if former is not set. + */ + deleteExtraData?: {} | { (): {} }; + /** + the URL for deleting the image/content in the initial preview via AJAX post response. This will be overridden by the initialPreviewConfig['url'] property. + Note + The ajax delete action will send the following data to server via POST: + key: the key setting as setup in initialPreviewConfig['key'] + any other extra data passed as key: value pairs either via initialPreviewConfig['extra'] OR deleteExtraData if former is not set. + */ + deleteUrl?: string; + /** + the initial preview caption text to be displayed. + If you do not set a value here and initialPreview is set to true this will default to "{preview-file-count} files selected", where {preview-file-count} is the count of the files passed in initialPreview. + */ + initialCaption?: string; + /** + whether you wish to overwrite the initial preview content and caption setup. + This defaults to true, whereby, any initialPreview content set will be overwritten, when new file is uploaded or when files are cleared. + Setting it to false will help displaying a saved image or file from database always - useful especially when using the multiple file upload feature. + */ + overwriteInitial?: boolean; + /** + the templates configuration for rendering each part of the layout. + */ + layoutTemplates?: LayoutTemplates; + /** + the templates configuration for rendering each preview file type. + */ + previewTemplates?: PreviewTemplates; + /** + the list of allowed file types for upload. + This by default is set to null which means the plugin supports all file types for upload. + If an invalid file type is found, then a validation error message as set in msgInvalidFileType will be raised. + Note: + You need to be careful in case you are setting both allowedFileTypes and allowedFileExtensions. In this case, the allowedFileTypes property is validated first and generally precedes the allowedFileExtensions setting (and the latter validation maybe skipped). + */ + allowedFileTypes?: ("image" | "html" | "text" | "video" | "audio" | "flash" | "object")[]; + /** + the list of allowed file extensions for upload. + This by default is set to null which means the plugin supports all file extensions for upload. + If an invalid file extension is found, then a validation error message as set in msgInvalidFileExtension will be raised. + Note: + You need to be careful in case you are setting both allowedFileTypes and allowedFileExtensions. In this case, the allowedFileTypes property is validated first and generally precedes the allowedFileExtensions setting (and the latter validation maybe skipped). + */ + allowedFileExtensions?: string[]; + /** + the list of allowed preview types for your widget. + This by default supports all file types for preview. + The plugin by default treats each file as an object if it does not match any of the previous types. + To disable this behavior, you can remove object from the list of allowedPreviewTypes OR fine tune it through allowedPreviewMimeTypes. + To disable content preview for all file-types and show the previewIcon instead as a thumbnail, set this to null, empty, or false. + */ + allowedPreviewTypes?: ("image" | "html" | "text" | "video" | "audio" | "flash" | "object")[]; + /** + the list of allowed mime types for preview. + This is set to null by default which means all possible mime types are allowed. + This setting works in combination with allowedPreviewTypes to filter only the needed file types allowed for preview. + */ + allowedPreviewMimeTypes?: string[]; + /** + the default content / markup to show by default in the preview window whenever the files are cleared or the input is cleared. + This can be useful for use cases like showing the default user profile picture or profile image before upload to overwrite. + This is a bit different from initialPreview in the sense, that the initialPreview content will always be displayed unless it is deleted or overwritten based on overwriteInitial. + The defaultPreviewContent on the other hand will only be shown ONLY on initialization OR whenever you clear the preview. + At other times when files have been selected this will be overwritten temporarily until file(s) selected is/are cleared. + This property can be useful to display for example a default user profile picture (or saved picture) in the preview window unless the user selects a picture. + */ + defaultPreviewContent?: string; + /** + the list of additional custom tags that will be replaced in the layout templates. + */ + customLayoutTags?: {}; + /** + the list of additional custom tags that will be replaced in the preview templates. + */ + customPreviewTags?: {}; + /** + the format settings (width and height) for rendering each preview file type. + */ + previewSettings?: PreviewSettings; + /** + the settings to validate and identify each file type when a file is selected for upload. + This is a list of callbacks, which accepts the file mime type and file name as a parameter. + */ + fileTypeSettings?: FileTypeSettings; + /** + the icon to be shown in each preview file thumbnail when an unreadable file type for preview is detected. Defaults to  . + */ + previewFileIcon?: string; + /** + the CSS class to be applied to the preview file icon container. Defaults to file-icon-4x. + */ + previewFileIconClass?: string; + /** + the preview icon markup settings for each file extension (type). + You need to set this as key: value pairs, where the key corresponds to a file extension (e.g. doc, docx, xls etc.), and the value corresponds to the markup of the icon to be rendered. + If this is not set OR a file extension is not set here, the preview will default to previewFileIcon. + Note that displaying the icons instead of file content is controlled via allowedPreviewTypes and allowedPreviewMimeTypes + */ + previewFileIconSettings?: PreviewFileIconSettings; + /** + the extensions to be auto derived for each file extension (type). + This is useful if you want to set the same icon for multiple file extension types. + You need to set this as `key: value` pairs, where the key corresponds to a file extension as set in previewFileIconSettings (e.g. doc, docx, xls etc.). + The value will be a function callback that accepts the following parameter: + ext: string, the file extension (without the . [dot]) of the file currently selected in the preview. + You can configure the callback to match the set of file extensions (via regex or similar) for each `key` and return a boolean output if the file extension matches. + */ + previewFileExtSettings?: PreviewFileExtSettings; + /** + the CSS class for the each of the button labels for browse, remove, upload, and cancel. + Defaults to hidden-xs, which automatically hides the button labels for small screen devices and renders as smaller iconic buttons to fit to the screen. + */ + buttonLabelClass?: string; + /** + the label to display for the file picker/browse button. Defaults to Browse …. + */ + browseLabel?: string; + /** + the icon to display before the label for the file picker/browse button. Defaults to  . + */ + browseIcon?: string; + /** + the CSS class for the file picker/browse button. Defaults to btn btn-primary. + */ + browseClass?: string; + /** + the label to display for the file remove button. Defaults to Remove. + */ + removeLabel?: string; + /** + the icon to display before the label for the file picker/remove button. Defaults to  . + */ + removeIcon?: string; + /** + the CSS class for the file remove button. Defaults to btn btn-default. + */ + removeClass?: string; + /** + the title to display on hover for the file remove button. Defaults to Clear selected files. + */ + removeTitle?: string; + /** + the label to display for the file upload button. Defaults to Upload. + */ + uploadLabel?: string; + /** + the icon to display before the label for the file upload button. Defaults to  . + */ + uploadIcon?: string; + /** + the CSS class for the file upload button. Defaults to btn btn-default. + */ + uploadClass?: string; + /** + the title to display on hover for the file remove button. + Defaults to Upload selected files. + */ + uploadTitle?: string; + /** + the URL for the upload processing action (typically for ajax based processing). + Defaults to null. + If this is not set or null, then the upload button action will default to form submission. + NOTE: + This is MANDATORY if you want to use advanced features like drag & drop, append/remove files, selectively upload files via ajax etc. + The plugin automatically send $_FILES data to the server with the input `name` attribute as the key if provided. + If input name is not set, the key defaults to file-data. + */ + uploadUrl?: string; + /** + whether the batch upload of multiple files will be asynchronous/in parallel. + Defaults to true. + */ + uploadAsync?: boolean; + /** + the extra data that will be passed as data to the url/AJAX server call via POST. + This property is only applicable for ajax uploads and when you have set a value for uploadUrl. + This can be setup either as an object (associative array of keys and values) or as a function callback. + As an object, it can be set for example as: + { id: 100, value: '100 Details' } + Note that for uploading individual file via thumbnail, the function callback can also receive the thumbnail previewId and index as parameters. These are described below: + previewId: the identifier for the preview file container (only available when uploading each thumbnail file) + index: the zero-based sequential index of the loaded file in the preview list (only available when uploading each thumbnail file) + */ + uploadExtraData?: {} | ((previewId?: string, index?: number) => {}); + /** + the minimum allowed image height in px if you are uploading image files. + Defaults to null which means no limit on image height. + */ + minImageHeight?: number; + /** + the maximum allowed image width in px if you are uploading image files. + Defaults to null which means no limit on image width. + Note that if you set resizeImage property to true, then the entire image will be resized within this width (depending on resizePreference). + */ + maxImageWidth?: number; + /** + the maximum allowed image height in px if you are uploading image files. + Defaults to null which means no limit on image height. + Note that if you set resizeImage property to true, then the entire image will be resized within this height (depending on resizePreference). + */ + maxImageHeight?: number; + /** + whether to add ability to resize uploaded images. Defaults to false. + Note that resizing images requires HTML5 canvas support which is supported on most modern browsers. + In addition, you must include the JavaScript-Canvas-to-Blob plugin by blueimp by including canvas-to-blob.js in your application. + This JS file must be loaded before fileinput.js on the page. + The JavaScript-Canvas-to-Blob source files are available in js/plugins folder of bootstrap-fileinput project page. + The canvas-to-blob.js plugin is a polyfill for canvas.toBlob method and is needed for allowing the resized image files via HTML5 canvas to be returned as a blob + */ + resizeImage?: boolean; + /** + preference to resize the image based on width or height. + Defaults to width. + This property is parsed only when resizeImage is true. + If set to width, the maxImageWidth property is first tested and if image size is greater than this, then the image is resized to maxImageWidth. + The image height is resized and adjusted in the same ratio as width. + In case, the image width is already less than maxImageWidth then the maxImageHeight property is used to resize and width is adjusted in same ratio. + This will behave conversely, when resizePreference is set to height - the maxImageHeight will be first tested against image height and then the rest of steps will be similarly parsed with preference given to height instead of width as before. + */ + resizePreference?: "width" | "height"; + /** + the quality of the resized image. This must be a decimal number between 0.00 to 1.00. + Defaults to 0.92. + */ + resizeImageQuality?: number; + /** + the default image mime type of the converted image after resize. + Defaults to image/jpeg. + */ + resizeDefaultImageType?: string; + /** + the maximum file size for upload in KB. + If set to 0, it means size allowed is unlimited. + Defaults to 0. + */ + maxFileSize?: number; + /** + the minimum number of files allowed for each multiple upload. + If set to 0, it means number of files are optional. + Defaults to 0. + */ + minFileCount?: number; + /** + the maximum number of files allowed for each multiple upload. + If set to 0, it means number of files allowed is unlimited. + Defaults to 0. + */ + maxFileCount?: number; + /** + whether to include initial preview file count (server uploaded files) in validating minFileCount and maxFileCount. + Defaults to false. + */ + validateInitialCount?: boolean; + /** + the message that will be displayed when ZERO files are found. + Defaults to No. + */ + msgNo?: string; + /** + the message that will be displayed within the progress bar when file upload is aborted or cancelled. + Defaults to Cancelled. + */ + msgCancelled?: string; + /** + the title displayed (before the file name) on hover of the zoom button for zooming the file content in a modal window. + This is currently applicable only for text file previews. + Defaults to View details. + */ + msgZoomTitle?: string; + /** + the heading of the modal dialog that displays the zoomed file content. + This is currently applicable only for text file previews. + Defaults to Detailed Preview. + */ + msgZoomModalHeading?: string; + /** + the message to be displayed when the file size exceeds maximum size. + Defaults to: + File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB. Please retry your upload! + where: + {name}: will be replaced by the file name being uploaded + {size}: will be replaced by the uploaded file size + {maxSize}: will be replaced by the maxFileSize parameter. + */ + msgSizeTooLarge?: string; + /** + message to be displayed when the file count is less than the minimum count as set in minFileCount. + Defaults to: + You must select at least {n} {files} to upload. Please retry your upload! + where: + {n}: will be replaced by the allowed minimum files as set in minFileCount. + {files}: will be replaced with fileSingle or filePlural properties in locale file depending on the minFileCount. + */ + msgFilesTooLess?: string; + /** + the message to be displayed when the file count exceeds maximum count as set in maxFileCount. + Defaults to: + Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}. Please retry your upload! + where: + {n}: will be replaced by number of files selected for upload + {m}: will be replaced by the allowed maximum files as set in maxFileCount + */ + msgFilesTooMany?: string; + /** + the exception message to be displayed when the file selected is not found by the FileReader. + Defaults to: + File "{name}" not found! + where: + {name}: will be replaced by the file name being uploaded + */ + msgFileNotFound?: string; + /** + the exception message to be displayed when the file selected is not allowed to be accessed due to a security exception. + Defaults to: + Security restrictions prevent reading the file "{name}". + where: + {name}: will be replaced by the file name being uploaded + */ + msgFileSecured?: string; + /** + the exception message to be displayed when the file selected is not readable by the FileReader API. + Defaults to: + File "{name}" is not readable. + where: + {name}: will be replaced by the file name being uploaded + */ + msgFileNotReadable?: string; + /** + the exception message to be displayed when the file preview upload is aborted. + Defaults to: + File preview aborted for "{name}". + where: + {name}: will be replaced by the file name being uploaded + */ + msgFilePreviewAborted?: string; + /** + the exception message to be displayed for any other error when previewing the file. + Defaults to: + An error occurred while reading the file "{name}". + where: + {name}: will be replaced by the file name being uploaded + */ + msgFilePreviewError?: string; + /** + the message to be displayed when the file type is not in one of the file types set in allowedFileTypes. + Defaults to: + Invalid type for file "{name}". Only "{types}" files are supported. + where: + {name}: will be replaced by the file name being uploaded + {types}: will be replaced by the comma separated list of types defined in allowedFileTypes. + */ + msgInvalidFileType?: string; + /** + the message to be displayed when the file type is not in one of the file extensions set in allowedFileExtensions. + Defaults to: + Invalid extension for file "{name}". Only "{extensions}" files are supported. + where: + {name}: will be replaced by the file name being uploaded + {extensions}: will be replaced by the comma separated list of extensions defined in allowedFileExtensions. + */ + msgInvalidFileExtension?: string; + /** + the message to be displayed when an ongoing ajax file upload is aborted by pressing the Cancel button. + Defaults to The file upload was aborted. + If this is set to null or empty, the internal ajax error message will be displayed - Defaults to File Upload Error. + */ + msgUploadAborted?: string; + /** + the exception message to be displayed within the caption container (instead of msgFilesSelected), when a validation error is encountered. + Defaults to File Upload Error. + */ + msgValidationError?: string; + /** + the css class for the validation error message displayed in the caption container. + Defaults to text-danger. + */ + msgValidationErrorClass?: string; + /** + the icon to be displayed before the validation error in the caption container. + Defaults to + */ + msgValidationErrorIcon?: string; + /** + the css class for the error message to be displayed in the preview window when the file size exceeds maxSize. + Defaults to file-error-message. + */ + msgErrorClass?: string; + /** + the message displayed when the files are getting read and loaded for preview. + Defaults to + Loading file {index} of {files} … + The following special variables will be replaced: + {index}: the sequence number of the current file being loaded. + {files}: the total number of files selected for upload. + */ + msgLoading?: string; + /** + the progress message displayed as each file is loaded for preview. + Defaults to: + Loading file {index} of {files} - {name} - {percent}% completed. + The following variables will be replaced: + {index}: the sequence number of the current file being loaded. + {files}: the total number of files selected for upload. + {percent}: the percentage of file read and loaded. + {name}: the name of the current file being loaded. + */ + msgProgress?: string; + /** + the progress message displayed in caption window when multiple (more than one) files are selected. + Defaults to: + {n} files selected. + The following variables will be replaced: + {n}: the number of files selected. + */ + msgSelected?: string; + /** + the message displayed when a folder has been dragged to the drop zone. + Defaults to: + Drag & drop files only! {n} folder(s) dropped were skipped. + The following variables will be replaced: + {n}: the number of folders dropped. + */ + msgFoldersNotAllowed?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its width is less than the minImageWidth setting. + Defaults to: + Width of image file "{name}" must be at least {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the minImageWidth setting. + */ + msgImageWidthSmall?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its height is less than the minImageHeight setting. + Defaults to: + Height of image file "{name}" must be at least {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the minImageHeight setting. + */ + msgImageHeightSmall?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its width exceeds the maxImageWidth setting. + Defaults to: + Width of image file "{name}" cannot exceed {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the maxImageWidth setting. + */ + msgImageWidthLarge?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its height exceeds the maxImageHeight setting. + Defaults to: + Height of image file "{name}" cannot exceed {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the maxImageHeight setting. + */ + msgImageHeightLarge?: string; + /** + the upload progress bar CSS class to be applied when AJAX upload is in process (applicable only for ajax uploads). + Defaults to progress-bar progress-bar-success progress-bar-striped active. + */ + progressClass?: string; + /** + the upload progress bar CSS class to be applied when AJAX upload is in process (applicable only for ajax uploads). + Defaults to progress-bar progress-bar-success progress-bar-striped active. + */ + progressCompleteClass?: string; + /** + the upload progress bar CSS class to be applied when AJAX upload is cancelled or aborted. + Defaults to progress-bar progress-bar-danger. + */ + progressErrorClass?: string; + /** + the type of files that are to be displayed in the preview window. + Defaults to image. + Can be one of the following: + image: Only image type files will be shown in preview. + text: Only text type files will be shown in preview. + any: Both image and text files content will be shown in preview. + Files other than image or text will be displayed as a thumbnail with the filename in the preview window. + */ + previewFileType?: "image" | "text" | "any"; + /** + the icon for zooming the file content in a new modal dialog. + This is currently applicable only for text file previews. + Defaults to + */ + zoomIndicator?: string; + /** + the identifier for the container element displaying the error (e.g. '#id'). + If not set, will default to the container with CSS class kv-fileinput-error inside the preview container (identified by elPreviewContainer). + The msgErrorClass will be automatically appended to this container before displaying the error. + */ + elErrorContainer?: string; + /** + the identifier for the container element containing the caption (e.g. '#id'). + If not set, will default to the container with CSS class file-caption inside the main plugin container. + */ + elCaptionContainer?: string; + /** + the identifier for the container element containing the caption text (e.g. '#id'). + If not set, will default to the container with CSS class file-caption-name inside the main plugin container. + */ + elCaptionText?: string; + /** + the identifier for the container element containing the preview (e.g. '#id'). + If not set, will default to the container with CSS class file-preview inside the main plugin container. + */ + elPreviewContainer?: string; + /** + the identifier for the element containing the preview image thumbnails (e.g. '#id'). + If not set, will default to the container with CSS class file-preview-thumbnails inside the main plugin container. + */ + elPreviewImage?: string; + /** + the identifier for the element containing the preview progress status (e.g. '#id'). + If not set, will default to the container with CSS class file-preview-status inside the main plugin container. + */ + elPreviewStatus?: string; + /** + a callback to convert the filename as a slug string eliminating special characters. + If not set, it will use the plugin's own internal slugDefault method. + This callback function includes the filename as parameter and must return a converted filename string. + */ + slugCallback?: (filename: string) => string; + /** + whether to enable a drag and drop zone for dragging and dropping files to. + This is available only for ajax based uploads. + Defaults to true. + */ + dropZoneEnabled?: boolean; + /** + title to be displayed in the drag and drop zone. + This is available only for ajax based uploads. + Defaults to: + Drag & drop files here …. + */ + dropZoneTitle?: string; + /** + CSS class for the drag & drop zone title. + Defaults to file-drop-zone-title. + */ + dropZoneTitleClass?: string; + /** + configuration for setting up file actions for newly selected file thumbnails in the preview window. + */ + fileActionsettings?: FileActionSettings; + /** + markup for additional action buttons to display within the initial preview thumbnails (for example displaying an image edit button). + The following tag can be used in the markup and will be automatically replaced: + {dataKey}: Will be replaced with the key set within initialPreviewConfig. + */ + otherActionButtons?: string; + /** + the encoding to be used while reading a text file. + Applicable only for previewing text files. + Defaults to UTF-8. + */ + textEncoding?: string; + /** + additional ajax settings to pass to the plugin before submitting the ajax request for upload. + Applicable only for ajax uploads. + This can be useful to pass additional tokens to headers or one can use it for setting other ajax options for advanced cases. + Refer the jQuery ajax documentation for the various settings you can configure. + */ + ajaxSettings?: JQueryAjaxSettings; + /** + additional ajax settings to pass to the plugin before submitting the delete ajax request in each initial preview thumbnail. + Applicable only for ajax uploads. + This can be useful to pass additional tokens to headers or one can use it for setting other ajax options for advanced cases. + Refer the jQuery ajax documentation for the various settings you can configure. + */ + ajaxDeleteSettings?: JQueryAjaxSettings; + /** + whether to show details of the error stack from the server log when an error is encountered via ajax response. + Defaults to true. + */ + showAjaxErrorDetails?: boolean; + } + + interface PreviewConfig { + /** + the caption or filename to display for each initial preview item content. + */ + caption: string; + /** + the CSS width of the image/ content displayed. + */ + width: string; + /** + the URL for deleting the image/ content in the initial preview via AJAX post response.This will default to deleteUrl if not set. + */ + url: string; + /** + the key that will be passed as data to the url via AJAX POST. + */ + key: string | {}; + /** + the additional frame css class to set for the file's thumbnail frame. + */ + frameClass: string; + /** + the HTML attribute settings (set as key:value pairs) for the thumbnail frame. + */ + frameAttr: {}; + /** + the extra data that will be passed as data to the initial preview delete url / AJAX server call via POST.This will default to deleteExtraData if not set. + */ + extra: {} | Function; + } + + interface LayoutTemplates { + /** + the template for rendering the widget with caption. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the mainClass property. + {close}: will be replaced with the close (cross) icon (by default on top right of the preview window). The layout template to control this markup is layoutTemplates.close. + {preview}: the content parsed by the previewTemplate and will be displayed only if showPreview is true. + {caption}: the content parsed by the captionTemplate and will be displayed only if showCaption is true. + {remove}: the file remove/clear button and will be displayed only if showRemove is true. + {upload}: the file upload button and will be displayed only if showUpload is true. + {cancel}: the file upload cancel button that will be displayed when AJAX upload is in process to abort the AJAX upload. + {browse}: the main file browse button to select your files for input. + */ + main1?: string; + /** + the template for rendering the widget without caption. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the mainClass property. + {close}: will be replaced with the close (cross) icon (by default on top right of the preview window). The layout template to control this markup is layoutTemplates.close. + {preview}: the content parsed by the previewTemplate and will be displayed only if showPreview is true. + {caption}: the content parsed by the captionTemplate and will be displayed only if showCaption is true. + {remove}: the file remove/clear button and will be displayed only if showRemove is true. + {upload}: the file upload button and will be displayed only if showUpload is true. + {cancel}: the file upload cancel button that will be displayed when AJAX upload is in process to abort the AJAX upload. + {browse}: the main file browse button to select your files for input. + */ + main2?: string; + /** + the template for rendering the preview. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the previewClass property. + */ + preview?: string; + /** + the icon to render before the caption text. + */ + icon?: string; + /** + the template for rendering the caption. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the captionClass property. + */ + caption?: string; + /** + the template for rendering the modal (for text file preview zooming). + */ + modal?: string; + /** + the template for the progress bar when upload is in progress (for batch/mass uploads and within each preview thumbnail for async/single uploads). + The upload progress bar when displayed within each thumbnail will be wrapped inside a container having a CSS class of `file-thumb-progress`. + The following tags will be parsed and replaced automatically: + {percent}: will be replaced with the upload progress percentage. + */ + progress?: string; + /** + the template for the footer section of each file preview thumbnail. + The following tags will be parsed and replaced automatically: + {actions}: will be replaced with the output of the actions template. + {class}: the CSS class as set in the progressClass or progressCompleteClass property (depending on the progress percentage). + */ + footer?: string; + /** + the template for the file action buttons to be displayed within the thumbnail footer. + The following tags will be parsed and replaced automatically: + {upload}: will be replaced with the output of the actionUpload template. + {delete}: will be replaced with the output of the actionDelete template. + */ + actions?: string; + /** + the template for the file delete action button within the thumbnail footer. + The following tags will be parsed and replaced automatically: + {removeClass}: the css class for the remove button. Will be replaced with the removeClass set within fileActionSettings. + {removeIcon}: the icon for the remove button. Will be replaced with the removeIcon set within fileActionSettings. + {removeTitle}: the title to display on hover for the remove button. Will be replaced with the removeTitle set within fileActionSettings. + {dataUrl}: the URL for deleting the file thumbnail for initialPreview content only. Will be replaced with the url set within initialPreviewConfig. + {dataKey}: the key (additional data) that will be passed to the URL above via POST to the AJAX call. Will be replaced with the key set within initialPreviewConfig. + */ + actionDelete?: string; + /** + the template for the file upload action button within the thumbnail footer. + The following tags will be parsed and replaced automatically: + {uploadClass}: the css class for the upload button. Will be replaced with the uploadClass set within fileActionSettings. + {uploadIcon}: the icon for the upload button. Will be replaced with the uploadIcon set within fileActionSettings. + {uploadTitle}: the title to display on hover for the upload button. Will be replaced with the uploadTitle set within fileActionSettings. + */ + actionUpload?: string; + /** + The template for upload, remove, and cancel buttons. + The following tags will be parsed and replaced automatically: + {type}: the HTML button type, defaults to button for most buttons and submit for form based uploads. + {title}: the title to display on button hover. + {css}: the CSS class for the button. This is derived from settings for uploadClass or removeClass or cancelClass. + {status}: the disabled status for the button if available (else will be blank). + {icon}: the button icon as identified by uploadIcon or removeIcon or cancelIcon. + {label}: the button label as identified by uploadLabel or removeLabel or cancelLabel. + */ + btnDefault?: string; + /** + The template for upload button when used with ajax (i.e. when uploadUrl is set). + The following tags will be parsed and replaced automatically: + {type}: the HTML button type, defaults to button for most buttons and submit for form based uploads. + {title}: the title to display on button hover. + {css}: the CSS class for the button. This is derived from settings for uploadClass. + {status}: the disabled status for the button if available (else will be blank). + {icon}: the button icon as identified by uploadIcon. + {label}: the button label as identified by uploadLabel. + {href}: applicable only for Upload button for ajax uploads and will be replaced with the uploadUrl property. + */ + btnLink?: string; + /** + The template for the browse button. + {type}: the HTML button type, defaults to button for most buttons and submit for form based uploads. + {title}: the title to display on button hover. + {css}: the CSS class for the button. This is derived from settings for browseClass. + {status}: the disabled status for the button if available (else will be blank). + {icon}: the button icon as identified by browseIcon. + {label}: the button label as identified by browseLabel. + */ + btnBrowse?: string; + } + + interface PreviewTemplates { + /** + the preview template for image files. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + image?: string; + /** + the preview template for text files. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + {dialog}: Will be replaced with the JS code to launch the modal dialog. + {zoomTitle}: This will be replaced with the msgZoomTitle property. This is the title that is displayed on hover of the zoom button (which on clicking will display the text file). + {zoomInd}: This will be replaced with the zoomIndicator property. This is the title that is displayed on hover of the zoom button (which on clicking will display the text file). + {heading}: This represents the modal dialog heading title. This will be replaced with the msgZoomModalHeading property. + */ + text?: string; + /** + the preview template for html files. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + html?: string; + /** + the preview template for video files (supported by HTML 5 video tag). + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + video?: string; + /** + the preview template for audio files (supported by HTML 5 audio tag). + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + audio?: string; + /** + the preview template for flash files (supported currently on webkit browsers). + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + flash?: string; + /** + the preview template for all other files - by default treated as object. To disable this behavior, configure the allowedPreviewTypes property. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + object?: string; + /** + this template is used ONLY for rendering the initialPreview markup content passed directly as a raw format. + The following tags will be parsed and replaced automatically: + {content}: will be replaced with the raw HTML markup as set in initialPreview.. + */ + generic?: string; + } + + interface PreviewSettings { + image?: { width?: string; height?: string; }; + html?: { width?: string; height?: string; }; + text?: { width?: string; height?: string; }; + video?: { width?: string; height?: string; }; + audio?: { width?: string; height?: string; }; + flash?: { width?: string; height?: string; }; + object?: { width?: string; height?: string; }; + other?: { width?: string; height?: string; }; + } + + interface FileTypeSettings { + image: (vType: string, vName: string) => boolean; + html: (vType: string, vName: string) => boolean; + text: (vType: string, vName: string) => boolean; + video: (vType: string, vName: string) => boolean; + audio: (vType: string, vName: string) => boolean; + flash: (vType: string, vName: string) => boolean; + object: (vType: string, vName: string) => boolean; + other: (vType: string, vName: string) => boolean; + } + + interface PreviewFileIconSettings { + [key: string]: string; + } + + interface PreviewFileExtSettings { + [key: string]: (ext: string) => boolean; + } + + interface FileActionSettings { + /** + icon for remove button to be displayed in each file thumbnail. + */ + removeIcon: string; + /** + CSS class for the remove button in each file thumbnail. + */ + removeClass: string; + /** + title for remove button in each file thumbnail. + */ + removeTitle: string; + /** + icon for upload button to be displayed in each file thumbnail. + */ + uploadIcon: string; + /** + CSS class for the remove button in each file thumbnail. + */ + uploadClass: string; + /** + title for remove button in each file thumbnail. + */ + uploadTitle: string; + /** + an indicator (HTML markup) for new pending upload displayed in each file thumbnail. + */ + indicatorNew: string; + /** + an indicator (HTML markup) for successful upload displayed in each file thumbnail. + */ + indicatorSuccess: string; + /** + an indicator (HTML markup) for error in upload displayed in each file thumbnail. + */ + indicatorError: string; + /** + an indicator (HTML markup) for ongoing upload displayed in each file thumbnail. + */ + indicatorLoading: string; + /** + title to display on hover of indicator for new pending upload in each file thumbnail. + */ + indicatorNewTitle: string; + /** + title to display on hover of indicator for successful in each file thumbnail. + */ + indicatorSuccessTitle: string; + /** + title to display on hover of indicator for error in upload in each file thumbnail. + */ + indicatorErrorTitle: string; + /** + title to display on hover of indicator for ongoing upload in each file thumbnail. + */ + indicatorLoadingTitle: string; + } +} \ No newline at end of file diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 686cc6b423..f60a0ffed6 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -15,7 +15,7 @@ * http://bootstrap-datepicker.readthedocs.org/en/release/options.html */ interface DatepickerOptions { - format?: string; + format?: string | DatepickerCustomFormatOptions; weekStart?: number; startDate?: any; endDate?: any; @@ -38,6 +38,11 @@ interface DatepickerOptions { assumeNearbyYear?: any; } +interface DatepickerCustomFormatOptions { + toDisplay?(date: string, format: any, language: any): string; + toValue?(date: string, format: any, language: any): Date; +} + interface DatepickerEventObject extends JQueryEventObject { date: Date; format(format?: string): string; diff --git a/bootstrap/bootstrap-tests.ts b/bootstrap/bootstrap-tests.ts index c497e0abcd..f7cfdeab43 100644 --- a/bootstrap/bootstrap-tests.ts +++ b/bootstrap/bootstrap-tests.ts @@ -44,3 +44,8 @@ $('.typeahead').typeahead({ }); $('#navbar').affix(); + +$('.item').emulateTransitionEnd(2000); + +$.support.transition = false; +console.log(($.support.transition as TransitionEventNames).end === "transitionend"); diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index b0e8fbf858..ae84454332 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -53,7 +53,7 @@ interface PopoverOptions { } interface CollapseOptions { - parent?: any; + parent?: any; toggle?: boolean; } @@ -79,6 +79,10 @@ interface AffixOptions { target?: any; } +interface TransitionEventNames { + end: string; +} + interface JQuery { modal(options?: ModalOptions): JQuery; modal(options?: ModalOptionsBackdropString): JQuery; @@ -114,6 +118,12 @@ interface JQuery { typeahead(options?: TypeaheadOptions): JQuery; affix(options?: AffixOptions): JQuery; + + emulateTransitionEnd(duration: number): JQuery; +} + +interface JQuerySupport { + transition: boolean | TransitionEventNames; } declare module "bootstrap" { diff --git a/browser-pack/browser-pack-tests.ts b/browser-pack/browser-pack-tests.ts new file mode 100644 index 0000000000..4cf20249e8 --- /dev/null +++ b/browser-pack/browser-pack-tests.ts @@ -0,0 +1,33 @@ +/// + +import browserPack = require("browser-pack"); + +module BrowserPackTest { + + export function packIt(opts?: BrowserPack.Options) { + var packOpts: BrowserPack.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts.externalRequireName || "require", + hasExports: opts.hasExports || false, + prelude: opts.prelude || undefined, + preludePath: opts.preludePath || undefined, + raw: opts.raw || false, + sourceMapPrefix: opts.sourceMapPrefix || '//#', + standalone: opts.standalone || undefined, + standaloneModule: opts.standaloneModule || undefined, + }; + + var res = browserPack(); // 'opts' are optional + var res2 = browserPack(packOpts); + + // ensure return value is a stream + var res3 = res.pipe(res2); + + res.on("error", function (err: any) { + console.error("browser-pack error: ", err); + }); + } + +} + +export = BrowserPackTest; \ No newline at end of file diff --git a/browser-pack/browser-pack.d.ts b/browser-pack/browser-pack.d.ts new file mode 100644 index 0000000000..52b96ce134 --- /dev/null +++ b/browser-pack/browser-pack.d.ts @@ -0,0 +1,61 @@ +// Type definitions for browser-pack v6.0.1 +// Project: https://github.com/substack/browser-pack +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** pack node-style source files from a json stream into a browser bundle + */ +declare module BrowserPack { + + export interface Options { + /** Whether the bundle should include require= (or the opts.externalRequireName) so that + * require() is available outside the bundle + */ + hasExports?: boolean; + + /** A string to use in place of 'require' if opts.hasExports is specified, default is 'require' + */ + externalRequireName?: string; + + /** Specify a custom prelude, but know what you're doing first. See the prelude.js file in + * this repo for the default prelude. If you specify a custom prelude, you must also specify + * a valid opts.preludePath to the prelude source file for sourcemaps to work + */ + prelude?: string; + + /** prelude.js path if a custom opts.prelude is specified + */ + preludePath?: string; + + /** Used if opts.preludePath is undefined, this is used to resolve the prelude.js file location, default: 'process.cwd()' + */ + basedir?: string; + + /** if given, the writable end of the stream will expect objects to be written to + * it instead of expecting a stream of json text it will need to parse, default false + */ + raw?: boolean; + + /** External string name to use for UMD, if not provided, UMD declaration is not wrapped around output + */ + standalone?: string; + + /** Sets the internal module name to export for standalone + */ + standaloneModule?: string; + + /** If given and source maps are computed, the opts.sourceMapPrefix string will be used instead of default: '//#' + */ + sourceMapPrefix?: string; + } + +} + +declare module "browser-pack" { + /** pack node-style source files from a json stream into a browser bundle + */ + function browserPack(opts?: BrowserPack.Options): NodeJS.ReadWriteStream; + export = browserPack; +} \ No newline at end of file diff --git a/browser-resolve/browser-resolve-tests.ts b/browser-resolve/browser-resolve-tests.ts new file mode 100644 index 0000000000..071b17a1d2 --- /dev/null +++ b/browser-resolve/browser-resolve-tests.ts @@ -0,0 +1,39 @@ +/// + +import * as browserResolve from 'browser-resolve'; + +function basic_test_async(callback: (err?: Error, resolved?: string) => void) { + browserResolve('typescript', function(error, resolved) { + if (error) { + return callback(error); + } + callback(null, resolved); + }); +} + +function basic_test_sync() { + var resolved = browserResolve.sync('typescript'); +} + +function options_test_async() { + browserResolve('typescript', { + browser: 'jsnext:main', + filename: './browser-resolve/browser-resolve.js', + modules: { + fs: './fs-shim.js' + } + }, function(error, resolved) { + if (error) { + console.error(error); + return; + } + console.log(resolved); + }); +} + +function options_test_sync() { + var resolved = browserResolve.sync('typescript', { + filename: './browser-resolve/browser-resolve.js', + modules: {} + }); +} diff --git a/browser-resolve/browser-resolve.d.ts b/browser-resolve/browser-resolve.d.ts new file mode 100644 index 0000000000..8c1456c8f0 --- /dev/null +++ b/browser-resolve/browser-resolve.d.ts @@ -0,0 +1,61 @@ +// Type definitions for browser-resolve +// Project: https://github.com/defunctzombie/node-browser-resolve +// Definitions by: Mario Nebl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'browser-resolve' { + import * as resolve from 'resolve'; + + /** + * Callback invoked when resolving asynchronously + * + * @param error + * @param resolved Absolute path to resolved identifier + */ + type resolveCallback = (err?: Error, resolved?: string) => void; + + /** + * Resolve a module path and call cb(err, path [, pkg]) + * + * @param id Identifier to resolve + * @param callback + */ + function browserResolve(id: string, cb: resolveCallback): void; + + /** + * Resolve a module path and call cb(err, path [, pkg]) + * + * @param id Identifier to resolve + * @param options Options to use for resolving, optional. + * @param callback + */ + function browserResolve(id: string, opts: browserResolve.AsyncOpts, cb: resolveCallback): void; + + /** + * Returns a module path + * + * @param id Identifier to resolve + * @param options Options to use for resolving, optional. + */ + function browserResolveSync(id: string, opts?: browserResolve.SyncOpts): string; + + namespace browserResolve { + interface Opts { + // the 'browser' property to use from package.json (defaults to 'browser') + browser?: string; + // the calling filename where the require() call originated (in the source) + filename?: string; + // modules object with id to path mappings to consult before doing manual resolution (use to provide core modules) + modules?: any; + } + + export interface AsyncOpts extends resolve.AsyncOpts, Opts {} + export interface SyncOpts extends resolve.SyncOpts, Opts {} + + export var sync: typeof browserResolveSync; + } + + export = browserResolve +} diff --git a/cassandra-driver/cassandra-driver.d.ts b/cassandra-driver/cassandra-driver.d.ts new file mode 100644 index 0000000000..0da40f2081 --- /dev/null +++ b/cassandra-driver/cassandra-driver.d.ts @@ -0,0 +1,761 @@ +// Type definitions for nodejs-driver v0.8.2 +// Project: https://github.com/datastax/nodejs-driver +// Definitions by: Marc Fisher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "cassandra-driver" { + type Callback = Function; + type ResultCallback = (err: Error, result: types.ResultSet) => void; + + import * as events from "events"; + import * as stream from "stream"; + import _Long = require("long"); + + namespace policies { + namespace addressResolution { + var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; + + interface AddressTranslator { + translate(address: string, port: number, callback: Callback): void; + } + + interface EC2MultiRegionTranslatorStatic { + new(): EC2MultiRegionTranslator; + } + + interface EC2MultiRegionTranslator extends AddressTranslator { + logError(address: string, err: Error): void; + } + } + + namespace loadBalancing { + var DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; + var RoundRobinPolicy: RoundRobinPolicyStatic; + var TokenAwarePolicy: TokenAwarePolicyStatic; + var WhiteListPolicy: WhiteListPolicyStatic; + + interface LoadBalancingPolicy { + init(client: Client, hosts: HostMap, callback: Callback): void; + getDistance(host: Host): types.distance; + newQueryPlan(keyspace: string, queryOptions: any, callback: Callback): void; + } + + interface DCAwareRoundRobinPolicyStatic { + new(localDc?: string, usedHostsPerRemoteDc?: number): DCAwareRoundRobinPolicy; + } + + interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + localHostsArray: Array; + remoteHostsArray: Array; + } + + interface RoundRobinPolicyStatic { + new(): RoundRobinPolicy; + } + + interface RoundRobinPolicy extends LoadBalancingPolicy {} + + interface TokenAwarePolicyStatic { + new(childPolicy: LoadBalancingPolicy): TokenAwarePolicy; + } + + interface TokenAwarePolicy extends LoadBalancingPolicy {} + + interface WhiteListPolicyStatic { + new(childPolicy: LoadBalancingPolicy, whiteList: Array): WhiteListPolicy; + } + + interface WhiteListPolicy extends LoadBalancingPolicy {} + } + + namespace reconnection { + var ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; + var ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; + + interface ReconnectionPolicy { + newSchedule(): {next: Function}; + } + + interface ConstantReconnectionPolicyStatic { + new(delay: number): ConstantReconnectionPolicy; + } + + interface ConstantReconnectionPolicy extends ReconnectionPolicy {} + + interface ExponentialReconnectionPolicyStatic { + new(baseDelay: number, maxDelay: number, startWithNoDelay: boolean): ExponentialReconnectionPolicy; + } + + interface ExponentialReconnectionPolicy extends ReconnectionPolicy {} + } + + namespace retry { + var RetryPolicy: RetryPolicyStatic; + + interface DecisionInfo { + decision: number; + consistency: number; + } + + interface RequestInfo { + request: any, + nbRetry: number + } + + enum retryDecision { + rethrow = 0, + retry, + ignore + } + + interface RetryPolicyStatic { + new (): RetryPolicy; + + retryDecision: any; + } + + interface RetryPolicy { + onReadTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, isDataPresent: boolean): DecisionInfo; + onUnavailable(requestInfo: RequestInfo, consistency: types.consistencies, required: number, alive: number): DecisionInfo; + onWriteTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, writeType: string): DecisionInfo; + rethrowResult(): { decision: retryDecision }; + retryResult(): { decision: retryDecision, consistency: types.consistencies, useCurrentHost: boolean }; + } + } + } + + namespace types { + var BigDecimal: BigDecimalStatic; + var InetAddress: InetAddressStatic; + var Integer: IntegerStatic; + var LocalDate: LocalDateStatic; + var LocalTime: LocalTimeStatic; + var Long: _Long; + var ResultSet: ResultSetStatic; + var ResultStream: ResultStreamStatic; + var Row: RowStatic; + var TimeUuid: TimeUuidStatic; + var Tuple: TupleStatic; + var Uuid: UuidStatic; + + enum consistencies { + any = 0, + one, + two, + three, + quorum, + all, + localQuorm, + eachQuorum, + serial, + localSerial, + localOne + } + + enum dataTypes { + custom = 0, + ascii, + bigint, + blob, + boolean, + counter, + decimal, + double, + float, + int, + text, + timestamp, + uuid, + varchar, + varint, + timeuuid, + inet, + date, + time, + smallint, + tinyint, + list, + map, + set, + udt, + tuple + } + + enum distance { + local = 0, + remote, + ignored + } + + interface responseErrorCodes { [key:string]:number; } + interface unset { unset: boolean; } + + function generateTimestamp(date?: Date, microseconds?: number): _Long; + function timeuuid(options?: {msecs: number | Date, node: Buffer, clockseq: number, nsecs: number}, buffer?: Buffer, offset?: number): string; + + interface BigDecimalStatic { + new (unscaledValue: number, scale: number): BigDecimal; + + fromBuffer(buf: Buffer): BigDecimal; + toBuffer(value: BigDecimal): Buffer; + fromString(value: string): BigDecimal; + fromNumber(value: number): BigDecimal; + } + + interface BigDecimal { + equals(other: BigDecimal): boolean; + inspect(): string; + notEquals(other: BigDecimal): boolean; + compare(other: BigDecimal): number; + subtract(other: BigDecimal): BigDecimal; + add(other: BigDecimal): BigDecimal; + greaterThan(other: BigDecimal): boolean; + isNegative(): boolean; + isZero(): boolean; + toString(): string; + toNumber(): number; + toJSON(): string; + } + + interface InetAddressStatic { + new(buffer: Buffer): InetAddress; + + fromString(value: string): InetAddress; + } + + interface InetAddress { + equals(other: InetAddress): boolean; + getBuffer(): Buffer; + inspect(): string; + toString(): string; + toJSON(): string; + + length: number; + version: number; + } + + interface IntegerStatic { + new(bits: Array, sign: number): Integer; + + fromInt(value: number): Integer; + fromNumber(value: number): Integer; + fromBits(bits: Array): Integer; + fromString(str: string, opt_radix?: number): Integer; + fromBuffer(bits: Buffer): Integer; + toBuffer(value: Integer): Buffer; + + ZERO: Integer; + ONE: Integer; + } + + interface Integer { + toInt(): number; + toNumber(): number; + toString(opt_radix?: number): string; + getBits(index: number): number; + getBitsUnsigned(index: number): number; + getSign(): number; + isZero(): boolean; + isNegative(): boolean; + isOdd(): boolean; + equals(other: Integer): boolean; + notEquals(other: Integer): boolean; + greaterThan(other: Integer): boolean; + greaterThanOrEqual(other: Integer): boolean; + lessThan(other: Integer): boolean; + lessThanOrEqual(other: Integer): boolean; + compare(other: Integer): number; + shorten(numBits: number): Integer; + negate(): Integer; + add(other: Integer): Integer; + subtract(other: Integer): Integer; + multiply(other: Integer): Integer; + divide(other: Integer): Integer; + modulo(other: Integer): Integer; + not(): Integer; + and(other: Integer): Integer; + or(other: Integer): Integer; + xor(other: Integer): Integer; + shiftLeft(numBits: number): Integer; + shiftRight(numBits: number): Integer; + inspect(): string; + abs(): Integer; + toJSON(): string; + } + + interface LocalDateStatic { + new(year: number, month: number, day: number): LocalDate; + + now(): LocalDate; + utcNow(): LocalDate; + fromDate(date: Date): LocalDate; + fromString(value: string): LocalDate; + fromBuffer(buffer: Buffer): LocalDate; + } + + interface LocalDate { + _value: number; + year: number; + month: number; + day: number; + + equals(other: LocalDate): boolean; + inspect(): string; + toBuffer(): Buffer; + toString(): string; + toJSON(): string; + } + + interface LocalTimeStatic { + new (totalNanoseconds: _Long): LocalTime; + + fromString(value: string): LocalTime; + now(nanoseconds?: number): LocalTime; + fromDate(date: Date, nanoseconds: number): LocalTime; + fromMilliseconds(milliseconds: number, nanoseconds?: number): LocalTime; + fromBuffer(value: Buffer): LocalTime; + } + + interface LocalTime { + hour: number; + minute: number; + second: number; + nanosecond: number; + + compare(other: LocalTime): boolean; + equals(other: LocalTime): boolean; + getTotalNanoseconds(): _Long; + inspect(): string; + toBuffer(): Buffer; + toString(): string; + toJSON(): string; + } + + interface ResultSetStatic { + new(response: any, host: string, triedHost: { [key:string]: any }, consistency: consistencies): ResultSet; + } + + interface ResultSet { + info: { + queriedHost: Host, + triedHosts: { [key:string]:string; }, + achievedConsistency: consistencies, + traceId: Uuid, + warnings: Array, + customPayload: any + }; + rows: Array; + rowLength: number; + columns: Array<{ [key:string]:string; }>; + pageState: string; + nextPage: any; // function + + first(): Row; + getPageState(): string; + getColumns(): Array<{ [key:string]:string; }>; + } + + interface ResultStreamStatic { + new (opt: any): ResultSet; + } + + interface ResultStream extends stream.Readable { + buffer: Buffer; + paused: boolean; + + _read(): void; + _valve(readNext: Function): void; + add(chunk: Buffer): void; + } + + interface RowStatic { + new(columns: Array<{ [key:string]:string; }>): Row; + } + + interface Row { + get(columnName: string|number): { [key:string]:any; }; + values(): Array<{ [key:string]:any; }>; + keys(): Array; + forEach(callback: Callback): void; + } + + interface TimeUuidStatic { + new (value?: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; + + fromDate(date: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; + fromString(value: string): TimeUuid; + min(date: Date, ticks?: number): TimeUuid; + max(date: Date, ticks?: number): TimeUuid; + now(nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; + } + + interface TimeUuid extends Uuid { + getDatePrecision(): { date: Date, ticks: number }; + getDate(): Date; + getNodeId(): Buffer; + getNodeIdString(): string; + } + + interface TupleStatic { + new (...arguments: Array): Tuple; + + fromArray(elements: Array): Tuple; + } + + interface Tuple { + elements: Array; + length: number; + + get(index: number): any; + toString(): string; + toJSON(): string; + values(): Array; + } + + interface UuidStatic { + new (buffer: Buffer): Uuid; + + fromString(value: string): Uuid; + random(): Uuid; + } + + interface Uuid { + buffer: Buffer; + + getBuffer(): Buffer; + equals(other: types.Uuid): boolean; + toString(): string; + inspect(): string; + toJSON(): string; + } + } + + var Client: ClientStatic; + var Host: HostStatic; + var HostMap: HostMapStatic; + var Encoder: EncoderStatic; + + interface ClientOptions { + contactPoints: Array, + keyspace: string, + policies?: { + addressResolution?: policies.addressResolution.AddressTranslator, + loadBalancing?: policies.loadBalancing.LoadBalancingPolicy, + reconnection?: policies.reconnection.ReconnectionPolicy, + retry?: policies.retry.RetryPolicy + }, + queryOptions?: QueryOptions, + pooling?: { + heartBeatInterval: number, + coreConnectionsPerHost: { [key:number]:number; }, + warmup: boolean; + }, + protocolOptions?: { + port: number, + maxSchemaAgreementWaitSeconds: number, + maxVersion: number + }, + socketOptions?: { + connectTimeout: number, + defunctReadTimeoutThreshold: number, + keepAlive: boolean, + keepAliveDelay: number, + readTimeout: number, + tcpNoDelay: boolean, + coalescingThreshold: number + }, + authProvider?: auth.AuthProvider, + sslOptions?: any, + encoding?: { + map: Function, + set: Function, + copyBuffer: boolean, + useUndefinedAsUnset: boolean + } + } + + interface QueryOptions { + autoPage?: boolean; + captureStackTrace?: boolean; + consistency: number; + customPayload?: any; + fetchSize?: number; + hints: Array | Array>; + logged?: boolean; + pageState?: Buffer|string; + prepare?: boolean; + readTimeout?: number; + retry?: policies.retry.RetryPolicy; + retryOnTimeout?: boolean; + routingIndexes?: Array; + routingKey?: Buffer | Array; + routingNames?: Array; + serialConsistency?: number; + timestamp?: number | _Long; + traceQuery?: boolean; + } + + interface ClientStatic { + new(options?: ClientOptions): Client; + } + + interface Client extends events.EventEmitter { + hosts: HostMap; + keyspace: string; + metadata: metadata.Metadata; + + batch(queries: Array|Array<{query: string, params?: any}>, options: QueryOptions, callback: ResultCallback): void; + connect(callback: Callback): void; + eachRow(query: string, params?: any, options?: QueryOptions, rowCallback?: Callback, callback?: Callback): void; + execute(query: string, params?: any, options?: QueryOptions, callback?: ResultCallback): void; + getReplicas(keyspace: string, token: Buffer): Array; // TODO: Should this be a more explicit return? + shutdown(callback?: Callback): void; + stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): void; + } + + interface HostStatic { + new(address: string, protocolVersion: number, options: ClientOptions): Host; + } + + interface Host extends events.EventEmitter { + address: string; + cassandraVersion: string; + dataCenter: string; + rack: string; + tokens: Array; + + canBeConsideredAsUp(): boolean; + getCassandraVersion(): Array; + isUp(): boolean; + } + + interface HostMapStatic { + new (): HostMap; + } + + interface HostMap extends events.EventEmitter { + length: number; + + forEach(callback: Callback): void; + get(key: string): Host; + keys(): Array; + remove(key: string): void; + removeMultiple(keys: Array): void; + set(key: string, value: Host): void; + values(): Array; + } + + interface EncoderStatic { + new(protocolVersion: number, options: ClientOptions) : Encoder; + } + + interface Encoder { + decode(buffer: Buffer, type: {code: number, info?: any}): void; + encode(value: any, typeInfo?: string|number|{code: number, info?: any}): Buffer; + } + + namespace auth { + var Authenticator: AuthenticatorStatic; + var PlainTextAuthProvider: PlainTextAuthProviderStatic; + + interface AuthenticatorStatic { + new (): Authenticator; + } + + interface Authenticator { + evaluateChallenge(challenge: Buffer, callback: Callback): void; + initialResponse(callback: Callback): void; + onAuthenticationSuccess(token?: Buffer): void; + } + + interface AuthProvider { + newAuthenticator(endpoint: string, name: string): void; + } + + interface PlainTextAuthProviderStatic { + new (username: string, password: string): PlainTextAuthProvider; + } + + interface PlainTextAuthProvider extends AuthProvider { + newAuthenticator(endpoint: string, name: string): void; + } + } + + namespace errors { + abstract class DriverError { + constructor(message: string, constructor?: any); + } + + class ArgumentError extends DriverError { + constructor(message: string); + } + + class AuthenticationError extends DriverError { + constructor(message: string); + } + + class DriverInternalError extends DriverError { + constructor(message: string); + } + + class NoHostAvailableError extends DriverError { + constructor(innerErrors: any, message?: string); + } + + class NotSupportedError extends DriverError { + constructor(message: string); + } + + class OperationTimedOutError extends DriverError {} + + class ResponseError extends DriverError { + constructor(code: number, message: string); + } + } + + namespace metadata { + var Aggregate: AggregateStatic; + var Index: IndexStatic; + var MaterializedView: MaterializedViewStatic; + var Metadata: MetadataStatic; + var SchemaFunction: SchemaFunctionStatic; + var TableMetadata: TableMetadataStatic; + + type caching = "all" | "keys_only" | "rows_only" | "none"; + + interface AggregateStatic { + new (): Aggregate; + } + + interface Aggregate { + argumentTypes: Array<{ code: number, info: any}>; + finalFunction: string; + initCondition: string; + keyspaceName: string, + returnType: string; + signature: Array; + stateFunction: string; + stateType: string; + } + + interface DataTypeInfo { + code: number, + info: string | DataTypeInfo | Array, + options: { + frozen: boolean, + reversed: boolean + } + } + + interface ColumnInfo { + name: string, + type: DataTypeInfo + } + + interface DataCollection { + bloomFilterFalsePositiveChance: number; + caching: caching; + clusterKeys: Array<{ c: ColumnInfo, index: number, order: string }>; + clusteringOrder: Array; + columns: Array; + columnsByName: { [key: string]: ColumnInfo }; + comment: string; + compactionClass: string; + compactionOptions: any; + compression: any; + crcCheckChange?: number; + defaultTtl: number; + extensions: any; + gcGraceSeconds: number; + localReadRepairChance: number; + maxIndexInterval?: number; + minIndexInterval?: number; + name: string; + partitionKeys: Array<{ c: ColumnInfo, index: number }> + populateCacheOnFlush: boolean; + readRepairChance: number; + speculateRetry: string; + } + + enum IndexType { + custom = 0, + keys, + composites + } + + interface IndexStatic { + new (name: string, target: string, kind: IndexType, options: Object): Index; + + fromRows(indexRows: Array): Array; + fromColumnRows(columnRows: Array, columnsByName: { [key:string]: ColumnInfo }): Array; + } + + interface Index { + kind: IndexType; + name: string; + options: Object; + target: string; + + isCompositesKind(): boolean; + isCustomKind(): boolean; + isKeysKind(): boolean; + } + + interface MaterializedViewStatic { + new (name: string): MaterializedView; + } + + interface MaterializedView extends DataCollection {} + + interface MetadataStatic { + new (options: ClientOptions, controlConnection: any): Metadata; + } + + interface Metadata { + clearPrepared(): void; + + getAggregate(keyspaceName: string, name: string, signature: Array | Array<{ code: number, info: any }>, callback: Callback): void; + getAggregates(keyspaceName: string, name: string, callback: Callback): void; + getFunction(keyspaceName: string, name: string, signature: Array | Array<{ code: number, info: any }>, callback: Callback): void; + getFunctions(keyspaceName: string, name: string, callback: Callback): void; + getMaterializedView(keyspaceName: string, name: string, callback: Callback): void; + getReplicas(keyspaceName: string, tokenBuffer: Buffer): Array; + getTable(keyspaceName: string, name: string, callback: Callback): void; + getTrace(traceId: types.Uuid, callback: Callback): void; + getUdt(keyspaceName: string, name: string, callback: Callback): void; + refreshKeyspace(name: string, callback?: Callback): void; + refreshKeyspaces(callback?: Callback): void; + } + + interface SchemaFunctionStatic { + new (): SchemaFunction; + } + + interface SchemaFunction { + argumentNames: Array; + argumentTypes: Array<{ code: number, info: any}>; + body: string; + calledOnNullInput: boolean; + keyspaceName: string, + language: string; + name: string; + returnType: string; + signature: Array; + } + + interface TableMetadataStatic { + new (name: string): TableMetadata; + } + + interface TableMetadata extends DataCollection { + indexes: Array; + indexInterval?: number; + isCompact: boolean; + memtableFlushPeriod: number; + replicateOnWrite: boolean; + } + } +} \ No newline at end of file diff --git a/cassandra-driver/cassandra-driver.tests.ts b/cassandra-driver/cassandra-driver.tests.ts new file mode 100644 index 0000000000..3eebf93018 --- /dev/null +++ b/cassandra-driver/cassandra-driver.tests.ts @@ -0,0 +1,11 @@ +/// + +import * as cassandra from 'cassandra-driver'; +import * as util from 'util'; + +var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'}); + +var query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; +client.execute(query, ['guy'], function(err, result) { + console.log('got user profile with email ' + result.rows[0].email); +}); \ No newline at end of file diff --git a/chai/chai-3.2.0-tests.ts b/chai/chai-3.2.0-tests.ts index 9b646b1529..cb1b74b8f1 100644 --- a/chai/chai-3.2.0-tests.ts +++ b/chai/chai-3.2.0-tests.ts @@ -1930,6 +1930,24 @@ suite('assert', () => { }, 'expected 5 to be below 5'); }); + test('isAtLeast', () => { + assert.isAtLeast(5, 3); + assert.isAtLeast(5, 5); + + err(() => { + assert.isAtLeast(3, 5); + }, 'expected 3 to be greater than or equal to 5'); + }); + + test('isAtMost', () => { + assert.isAtMost(3, 5); + assert.isAtMost(5, 5); + + err(() => { + assert.isAtMost(5, 3); + }, 'expected 5 to be less than or equal to 3'); + }); + test('extensible', () => { assert.extensible({}); }); test('isExtensible', () => { assert.isExtensible({}); }); test('notExtensible', () => { assert.notExtensible(Object.preventExtensions({})); }); diff --git a/chai/chai-3.2.0.d.ts b/chai/chai-3.2.0.d.ts index 87b0c08e6f..6dc653b72f 100644 --- a/chai/chai-3.2.0.d.ts +++ b/chai/chai-3.2.0.d.ts @@ -271,6 +271,9 @@ declare namespace Chai { isAbove(val: number, abv: number, msg?: string): void; isBelow(val: number, blw: number, msg?: string): void; + isAtMost(val: number, atmst: number, msg?: string): void; + isAtLeast(val: number, atlst: number, msg?: string): void; + isFunction(val: any, msg?: string): void; isNotFunction(val: any, msg?: string): void; diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 0ebc855022..8eb0995947 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -378,7 +378,20 @@ declare namespace Chai { } export interface Config { + /** + * Default: false + */ includeStack: boolean; + + /** + * Default: true + */ + showDiff: boolean; + + /** + * Default: 40 + */ + truncateThreshold: number; } export class AssertionError { diff --git a/chartist/chartist.d.ts b/chartist/chartist.d.ts index 6c679dc1d8..0e92364812 100644 --- a/chartist/chartist.d.ts +++ b/chartist/chartist.d.ts @@ -105,7 +105,7 @@ declare namespace Chartist { plugins?: Array; // all of these plugins seem to be functions with options, but keeping type any for now update(data: Object, options?: T, override?: boolean): void; - detatch(): void; + detach(): void; /** * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index bba377090f..9d8728338f 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -641,7 +641,7 @@ declare namespace CKEDITOR { filebrowserImageBrowseLinkUrl?: string; filebrowserImageBrowseUrl?: string; filebrowserImageUploadUrl?: string; - filebrowserUploadUr?: string; + filebrowserUploadUrl?: string; filebrowserWindowFeatures?: string; filebrowserWindowHeight?: number | string; filebrowserWindowWidth?: number | string; diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index f513057216..b1bf33e2d2 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -220,14 +220,7 @@ declare namespace CodeMirror { /** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area, and the size of the visible area(minus scrollbars). */ - getScrollInfo(): { - left: any; - top: any; - width: any; - height: any; - clientWidth: any; - clientHeight: any; - } + getScrollInfo(): CodeMirror.ScrollInfo; /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ @@ -609,6 +602,15 @@ declare namespace CodeMirror { text: string; } + interface ScrollInfo { + left: any; + top: any; + width: any; + height: any; + clientWidth: any; + clientHeight: any; + } + interface TextMarker { /** Remove the mark. */ clear(): void; diff --git a/common-tags/common-tags-tests.ts b/common-tags/common-tags-tests.ts new file mode 100644 index 0000000000..9114f4414c --- /dev/null +++ b/common-tags/common-tags-tests.ts @@ -0,0 +1,156 @@ +/// + +import * as commonTags from 'common-tags'; + +/* Test Built-in Tags */ + +commonTags.commaLists ` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.commaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.commaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +let fruits = ['apple', 'orange', 'watermelon']; + +commonTags.html` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.codeBlock` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.source` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.oneLine` + foo + bar + baz +`; + +commonTags.oneLineTrim` + https://news.com/article + ?utm_source=designernews.co +`; + +commonTags.oneLineCommaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineCommaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineCommaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.inlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineInlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +let verb = 'notice'; + +commonTags.stripIndent` + This is a multi-line string. + You'll ${verb} that it is indented. + We don't want to output this indentation. + But we do want to keep this line indented. +`; + +commonTags.stripIndents` + This is a multi-line string. + You'll ${verb} that it is indented. + We don't want to output this indentation. + We don't want to keep this line indented either. +`; + +/* Test Tag Constructor */ + +new commonTags.TemplateTag(); + +const substitutionReplacer = (oldValue : string, newValue : string) => ({ + onSubstitution(substitution : string, resultSoFar : string) { + if (substitution === oldValue) { + return newValue; + } + return substitution; + } +}); + +new commonTags.TemplateTag(substitutionReplacer('fizz', 'buzz')); + +new commonTags.TemplateTag( + substitutionReplacer('fizz', 'buzz'), + substitutionReplacer('foo', 'bar') +); + +new commonTags.TemplateTag([ + substitutionReplacer('fizz', 'buzz'), + substitutionReplacer('foo', 'bar') +]); + +new commonTags.TemplateTag({}); + +new commonTags.TemplateTag({ + onEndResult: endResult => `${endResult}!` +}); + +new commonTags.TemplateTag({ + onSubstitution: substitution => `${substitution}!`, + onEndResult: endResult => `${endResult}!` +}); + +/* Tests Built-in Transformers */ + +new commonTags.TemplateTag(commonTags.trimResultTransformer()); +new commonTags.TemplateTag(commonTags.trimResultTransformer('left')); +new commonTags.TemplateTag(commonTags.trimResultTransformer('right')); + +new commonTags.TemplateTag(commonTags.stripIndentTransformer()); +new commonTags.TemplateTag(commonTags.stripIndentTransformer('initial')); +new commonTags.TemplateTag(commonTags.stripIndentTransformer('all')); + +new commonTags.TemplateTag(commonTags.replaceResultTransformer('foo', 'bar')); + +new commonTags.TemplateTag(commonTags.inlineArrayTransformer()); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({})); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({separator: 'foo'})); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({conjunction: 'bar'})); + +new commonTags.TemplateTag(commonTags.splitStringTransformer('foo')); diff --git a/common-tags/common-tags.d.ts b/common-tags/common-tags.d.ts new file mode 100644 index 0000000000..aa443ac33d --- /dev/null +++ b/common-tags/common-tags.d.ts @@ -0,0 +1,62 @@ +// Type definitions for common-tags v1.2.1 +// Project: https://github.com/declandewet/common-tags +// Definitions by: Viktor Zozuliak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'common-tags' { + type TemplateTag = (literals: string[], ...placeholders: any[]) => string; + + type TemplateTransformer = { + onSubstitution?: (substitution: string, resultSoFar: string) => string; + onEndResult?: (endResult : string) => string; + } + + /* Built-in Tags */ + export var commaLists: TemplateTag; + + export var commaListsAnd: TemplateTag; + + export var commaListsOr: TemplateTag; + + export var html: TemplateTag; + + export var codeBlock: TemplateTag; + + export var source: TemplateTag; + + export var oneLine: TemplateTag; + + export var oneLineTrim: TemplateTag; + + export var oneLineCommaLists: TemplateTag; + + export var oneLineCommaListsOr: TemplateTag; + + export var oneLineCommaListsAnd: TemplateTag; + + export var inlineLists: TemplateTag; + + export var oneLineInlineLists: TemplateTag; + + export var stripIndent: TemplateTag; + + export var stripIndents: TemplateTag; + + /* New Tag Constructor */ + export var TemplateTag: { + new(): TemplateTag; + new(...transformers: TemplateTransformer[]): TemplateTag; + new(transformers: TemplateTransformer[]): TemplateTag; + }; + + /* Built-in Transformers */ + export var trimResultTransformer: (side?: 'left'|'right') => TemplateTransformer; + + export var stripIndentTransformer: (type?: 'initial'|'all') => TemplateTransformer; + + export var replaceResultTransformer: (replaceWhat: string, replaceWith: string) => TemplateTransformer; + + export var inlineArrayTransformer: (opts?: {separator?: string, conjunction?: string}) => TemplateTransformer; + + export var splitStringTransformer: (splitBy: string) => TemplateTransformer; +} diff --git a/component-emitter/component-emitter-tests.ts b/component-emitter/component-emitter-tests.ts new file mode 100644 index 0000000000..e6c6a5b1ab --- /dev/null +++ b/component-emitter/component-emitter-tests.ts @@ -0,0 +1,52 @@ +/// // only for require +/// +// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016 + + +// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016 + +var Emitter = require('component-emitter'); +var emitter = new Emitter; +emitter.emit('something'); + + + + +var user = { name: 'tobi' }; +Emitter(user); + +(user).emit('im a user'); + + + +// this example modified from the one on https://www.npmjs.com/package/component-emitter +var User = Object.create({ + someUserFunction: () => {console.log('someUserFunction called!')} +}) +var another_user = Emitter(User); +another_user.someUserFunction() +another_user.on('hi', () => {console.log('Hi called')}) +another_user.emit('hi') + + +// Additional sample code for this test +function handleSomeRecurringEvent(event_data: any) { + console.log('handle some-recurring-event') +} +emitter.on('some-recurring-event', handleSomeRecurringEvent) + + +emitter.once('some-single-shot-event', (event_data: any) => {console.log('handle some-single-shot-event')}) + + +emitter.off() +emitter.off('some-recurring-event') +emitter.off('some-recurring-event', handleSomeRecurringEvent) + +var event_data = {some: 'data'} +emitter.emit('some-recurring-event') +emitter.emit('some-recurring-event', event_data) + +emitter.listeners('some-recurring-event') + +emitter.hasListeners('some-recurring-event') diff --git a/component-emitter/component-emitter.d.ts b/component-emitter/component-emitter.d.ts new file mode 100644 index 0000000000..28ce4f4bc9 --- /dev/null +++ b/component-emitter/component-emitter.d.ts @@ -0,0 +1,19 @@ +// Type definitions for component-emitter v1.2.1 +// Project: https://www.npmjs.com/package/component-emitter +// Definitions by: Peter Snider +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/emitter-component + + +interface Emitter { + (obj?: Object): Emitter; + on(event: string, listener: Function): Emitter; + once(event: string, listener: Function): Emitter; + off(event?: string, listener?: Function): Emitter; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; +} + +declare module 'component-emitter' { + var Emitter: Emitter; +} diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts index d0e742d9c2..6c4273e4e0 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -29,8 +29,20 @@ declare namespace cucumber { } interface HookScenario{ - attach(text: string, mimeType?: string, callback?: (err?:any) => void): void; - isFailed() : boolean; + getKeyword():string; + getName():string; + getDescription():string; + getUri():string; + getLine():number; + getTags():string[]; + getException():Error; + getAttachments():any[]; + attach(data:any, mimeType?:string, callback?:(err?:any) => void):void; + isSuccessful():boolean; + isFailed():boolean; + isPending():boolean; + isUndefined():boolean; + isSkipped():boolean; } interface HookCode { diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 683fb8532c..b35d898522 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -292,17 +292,17 @@ declare namespace d3 { */ datum(): Datum; - /** - * Set the data item for each node in the selection. - * @param value the constant element to use for each node - */ - datum(value: NewDatum): Update; - /** * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. * @param value the function to compute data for each node */ datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; + + /** + * Set the data item for each node in the selection. + * @param value the constant element to use for each node + */ + datum(value: NewDatum): Update; /** * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. @@ -1111,8 +1111,7 @@ declare namespace d3 { export function deviation(array: number[]): number; export function deviation(array: T[], accessor: (datum: T, index: number) => number): number; - export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; - export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; + export function bisectLeft(array: T[], x: T, lo?: number, hi?: number): number; export var bisect: typeof bisectRight; @@ -3064,6 +3063,8 @@ declare namespace d3 { } export interface Partition { + (root: T): T[]; + nodes(root: T): T[]; links(nodes: T[]): partition.Link[]; diff --git a/d3kit/d3kit-tests.ts b/d3kit/d3kit-tests.ts new file mode 100644 index 0000000000..1b8d2a24f9 --- /dev/null +++ b/d3kit/d3kit-tests.ts @@ -0,0 +1,1112 @@ +/// +/// +/// +/// + +/* jshint expr: true */ + +var expect = chai.expect; +describe('Skeleton', function(){ + var element: Element, $element: d3.Selection, $svg: d3.Selection, skeleton: d3kit.Skeleton; + + beforeEach(function(done){ + element = document.body.appendChild(document.createElement('div')) as Element; + skeleton = new d3kit.Skeleton(element, null, ['custom1', 'custom2']); + $element = d3.select(element); + $svg = $element.select('svg'); + done(); + }); + + describe('new Skeleton()', function(){ + it('should create inside the element', function(){ + expect($element.select('svg').size()).to.be.equal(1); + }); + it('should create inside inside the element', function(){ + expect($element.select('svg').select('g').size()).to.be.equal(1); + }); + }); + + describe('#getCustomEventNames()', function(){ + it('should return custom event names', function(){ + expect(skeleton.getCustomEventNames()).to.deep.equal(['custom1', 'custom2']); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return event dispatcher', function(){ + expect(skeleton.getDispatcher()).to.be.an('Object'); + expect(skeleton.getDispatcher().data).to.be.a('Function'); + }); + }); + + describe('#getInnerWidth()', function(){ + it('should return width of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(100); + expect(skeleton.getInnerWidth()).to.equal(80); + }); + }); + + describe('#getInnerHeight()', function(){ + it('should return height of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(100); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + }); + + describe('#getLayerOrganizer()', function(){ + it('should return the LayerOrganizer', function(){ + expect(skeleton.getLayerOrganizer()).to.be.an('Object'); + }); + }); + + describe('#getRootG()', function(){ + it('should return d3 selection of the root ', function(){ + var g = skeleton.getRootG(); + expect(g.size()).to.equal(1); + expect((g[0][0] as Element).tagName).to.equal('g'); + }); + }); + + describe('#getSvg()', function(){ + it('should return d3 selection of the ', function(){ + var svg = skeleton.getSvg(); + expect(svg.size()).to.equal(1); + expect((svg[0][0] as Element).tagName).to.equal('svg'); + }); + }); + + describe('#data(data, doNotDispatch)', function(){ + it('should return data when called without argument', function(){ + skeleton.data({a: 1}); + expect(skeleton.data()).to.deep.equal({a: 1}); + }); + it('should set data when called with at least one argument', function(){ + skeleton.data('test'); + expect(skeleton.data()).to.equal('test'); + }); + it('after setting, should dispatch "data" event', function(done){ + skeleton.on('data.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.data({a: 1}); + }); + it('after setting, should not dispatch "data" event if doNotDispatch is true', function(done){ + skeleton.on('data.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.data({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#options(options, doNotDispatch)', function(){ + it('should return options when called without argument', function(){ + skeleton.options({a: 2}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(2); + }); + it('should set options when called with at least one argument', function(){ + skeleton.options({a: 1}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(1); + }); + it('should not overwrite but extend existing options when setting', function(){ + skeleton.options({a: 1}); + skeleton.options({b: 2}); + expect(skeleton.options()).to.include.keys(['a', 'b']); + expect(skeleton.options().a).to.equal(1); + expect(skeleton.options().b).to.equal(2); + }); + it('after setting, should dispatch "options" event', function(done){ + skeleton.on('options.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.options({a: 1}); + }); + it('after setting, should not dispatch "options" event if doNotDispatch is true', function(done){ + skeleton.on('options.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.options({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#margin(margin, doNotDispatch)', function(){ + it('should return margin when called without argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + expect(skeleton.margin()).to.deep.equal(margin); + }); + it('should set margin when called with at least one argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + + skeleton.margin({left: 20}); + expect(skeleton.margin().left).to.equal(20); + expect(skeleton.margin().right).to.equal(10); + skeleton.margin({right: 20}); + expect(skeleton.margin().right).to.equal(20); + skeleton.margin({top: 20}); + expect(skeleton.margin().top).to.equal(20); + skeleton.margin({bottom: 20}); + expect(skeleton.margin().bottom).to.equal(20); + }); + it('should update innerWidth after setting margin', function(){ + skeleton.width(100); + skeleton.margin({left: 10, right:10}); + expect(skeleton.getInnerWidth()).to.equal(80); + skeleton.margin({left: 15, right:15}); + expect(skeleton.getInnerWidth()).to.equal(70); + }); + it('should update innerHeight after setting margin', function(){ + skeleton.height(100); + skeleton.margin({top: 10, bottom:10}); + expect(skeleton.getInnerHeight()).to.equal(80); + skeleton.margin({top: 15, bottom:15}); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + it('should update the root transform/translate', function(){ + skeleton.margin({left: 30, top: 30}); + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(10.5,10.5)'); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.margin({left: 33}); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.margin({left: 33}, true); + setTimeout(done, 100); + }); + }); + + describe('#offset(offset)', function(){ + it('should return offset when called without argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + expect(skeleton.offset()).to.deep.equal(offset); + }); + it('should set offset when called with at least one argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + skeleton.offset([2,3]); + expect(skeleton.offset()).to.deep.equal([2,3]); + }); + it('should update the root transform/translate', function(){ + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + skeleton.offset([2,3]); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(12,13)'); + }); + }); + + describe('#width(width, doNotDispatch)', function(){ + it('should return width when called without argument', function(){ + var w = $svg.attr('width'); + expect(skeleton.width()).to.equal(+w); + }); + it('should set width when called with Number as the first argument', function(){ + skeleton.width(300); + expect(+$svg.attr('width')).to.equal(300); + }); + it('should set width when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.width('299px'); + expect(+$svg.attr('width')).to.equal(299); + }); + it('should set width to container\'s width when called with "auto" as the first argument', function(){ + var w = element.clientWidth; + skeleton.width('auto'); + expect(+$svg.attr('width')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.width(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.width(200, true); + setTimeout(done, 100); + }); + }); + + describe('#height(height, doNotDispatch)', function(){ + it('should return height when called without argument', function(){ + var w = $svg.attr('height'); + expect(skeleton.height()).to.equal(+w); + }); + it('should set height when called with Number as the first argument', function(){ + skeleton.height(300); + expect(+$svg.attr('height')).to.equal(300); + }); + it('should set height when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.height('299px'); + expect(+$svg.attr('height')).to.equal(299); + }); + it('should set height to container\'s height when called with "auto" as the first argument', function(){ + var w = element.clientHeight; + skeleton.height('auto'); + expect(+$svg.attr('height')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.height(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.height(200, true); + setTimeout(done, 100); + }); + }); + + describe('#dimension(dimension, doNotDispatch)', function(){ + it('should return an array [width, height] when called without argument', function(){ + var dim = [+$svg.attr('width'), +$svg.attr('height')]; + expect(skeleton.dimension()).to.deep.equal(dim); + }); + it('should set width and height of the when called with an array [width, height] as the first argument', function(){ + skeleton.dimension([118, 118]); + expect([+$svg.attr('width'), +$svg.attr('height')]).to.deep.equal([118, 118]); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.dimension([150, 150]); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.dimension([150, 150], true); + setTimeout(done, 100); + }); + }); + + describe('#hasData()', function(){ + it('should return true when data are not null nor undefined', function(){ + skeleton.data({}); + expect(skeleton.hasData()).to.be.true; + skeleton.data({test: 1}); + expect(skeleton.hasData()).to.be.true; + skeleton.data([]); + expect(skeleton.hasData()).to.be.true; + skeleton.data(['test']); + expect(skeleton.hasData()).to.be.true; + }); + it('should return false when data are null or undefined', function(){ + skeleton.data(null); + expect(skeleton.hasData()).to.be.false; + skeleton.data(undefined); + expect(skeleton.hasData()).to.be.false; + }); + }); + + describe('#hasNonZeroArea()', function(){ + it('should return true if \'s width & height excluding margin is more than zero', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(80); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(50); + expect(skeleton.hasNonZeroArea()).to.be.true; + }); + it('should return false otherwise', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(20); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(30); + expect(skeleton.hasNonZeroArea()).to.be.false; + }); + }); + + describe('#mixin({})', function(){ + it('should extend this skeleton with new fields/functions', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + expect(skeleton).to.include.keys(['a', 'b']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(2); + }); + it('should overwrite existing fields', function(){ + skeleton.mixin({ + b: 2 + }); + skeleton.mixin({ + b: 3 + }); + expect(skeleton).to.include.keys(['b']); + expect((skeleton).b).to.equal(3); + }); + it('should keep original fields if not overwritten', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + skeleton.mixin({ + c: 20, + b: 3 + }); + expect(skeleton).to.include.keys(['a', 'b', 'c']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(3); + expect((skeleton).c).to.equal(20); + }); + }); + + describe('#resizeToFitContainer(mode)', function(){ + it('when mode is "all" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('all'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "both" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('both'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "full" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('full'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "width" should resize width to fit container but keep original height', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight/2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('width'); + + expect(skeleton.width()).to.equal(Math.floor(w2)); + expect(skeleton.height()).to.equal(Math.floor(h1)); + expect(skeleton.width()).to.not.equal(w1); + expect(skeleton.height()).to.not.equal(h2); + }); + it('when mode is "height" should resize height to fit container but keep original width', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight*2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('height'); + + expect(skeleton.width()).to.equal(Math.floor(w1)); + expect(skeleton.height()).to.equal(Math.floor(h2)); + expect(skeleton.width()).to.not.equal(w2); + expect(skeleton.height()).to.not.equal(h1); + }); + }); + + describe('#resizeToAspectRatio(ratio)', function(){ + // todo + }); + + describe('#autoResize(mode)', function(){ + it('should return current mode when called without argument', function(){ + skeleton.autoResize(false); + expect(skeleton.autoResize()).to.be.false; + skeleton.autoResize('width'); + expect(skeleton.autoResize()).to.equal('width'); + }); + it('should enable auto resize when set mode to "width/height/both/etc.", similar to parameters of resizeToFitContainer()', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + done(); + }, 500); + }); + it('should disable auto resize when set mode to false', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + // disable resize and + skeleton.autoResize(false); + skeleton.width(50); + setTimeout(function(){ + expect(skeleton.width()).to.not.equal(element.clientWidth); + done(); + }, 500); + }, 500); + }); + }); + + describe('#autoResizeDetection(detection)', function(){ + // todo + }); + + describe('#autoResizeToAspectRatio(ratio)', function(){ + // todo + }); + + +}); + +describe.only('LayerOrganizer', function(){ + + describe('new LayerOrganizer(container) will create layers as by default', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('svg').append('g'); + layers = new d3kit.LayerOrganizer(container); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('g.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('g.a-layer').size()).to.be.equal(1); + expect(container.select('g.b-layer').size()).to.be.equal(1); + expect(container.select('g.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('g.d-layer').size()).to.be.equal(1); + expect(container.select('g.d-layer g.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('g.f-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.g-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('g.i-layer').size()).to.be.equal(1); + expect(container.select('g.j-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('g.l-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.m-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer g.p-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + + describe('new LayerOrganizer(container, tag) will create layers with the given tag instead of ', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('div'); + layers = new d3kit.LayerOrganizer(container, 'div'); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('div.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('div.a-layer').size()).to.be.equal(1); + expect(container.select('div.b-layer').size()).to.be.equal(1); + expect(container.select('div.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('div.d-layer').size()).to.be.equal(1); + expect(container.select('div.d-layer div.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('div.f-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.g-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('div.i-layer').size()).to.be.equal(1); + expect(container.select('div.j-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('div.l-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.m-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer div.p-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + +}); + +describe('Chartlet', function(){ + interface ConfigureFunction { + (parent: d3kit.Chartlet, child: d3kit.Chartlet): void; + } + var enter: d3kit.ChartletEventFunction, update: d3kit.ChartletEventFunction, exit: d3kit.ChartletEventFunction, chartlet: d3kit.Chartlet; + var customEvents: Array = ['fooEvent']; + var ChildChartlet: () => d3kit.Chartlet; + var ParentChartlet: (configureFunction: ConfigureFunction) => d3kit.Chartlet; + + var callback = function(selection?: d3.Selection, done?: any) { return (sel: d3.Selection) => {done();};}; + beforeEach(function(done){ + ChildChartlet = function() { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + (chartlet).runTest = function (testFunction: any) { + testFunction(chartlet); + }; + return chartlet; + }; + + ParentChartlet = function(configureFunction: ConfigureFunction) { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + var child = ChildChartlet(); + configureFunction(chartlet, child); + (chartlet).runTest = (child).runTest; + return chartlet; + }; + + enter = callback; + update = callback; + exit = callback; + chartlet = new d3kit.Chartlet(enter, update, exit, customEvents); + done(); + }); + + describe('new Chartlet(enter, update, exit, customEvents)', function(){ + it('should create a chartlet', function(){ + expect(chartlet).to.be.an('Object'); + expect(chartlet).to.include.keys(['property', 'on']); + expect(chartlet.enter).to.be.a('Function'); + expect(chartlet.update).to.be.a('Function'); + expect(chartlet.exit).to.be.a('Function'); + expect(function(){ chartlet.enter(); }).to.not.throw(Error); + expect(function(){ chartlet.update(); }).to.not.throw(Error); + expect(function(){ chartlet.exit(); }).to.not.throw(Error); + expect(chartlet.getCustomEventNames()).to.deep.equal(customEvents); + }); + it('arguments "update", "exit" and "customEvents" are optional', function(){ + var comp = new d3kit.Chartlet(enter); + expect(comp).to.be.an('Object'); + expect(comp).to.include.keys(['property', 'on']); + expect(comp.enter).to.be.a('Function'); + expect(comp.update).to.be.a('Function'); + expect(comp.exit).to.be.a('Function'); + expect(function(){ comp.enter(); }).to.not.throw(Error); + expect(function(){ comp.update(); }).to.not.throw(Error); + expect(function(){ comp.exit(); }).to.not.throw(Error); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return a dispatcher', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.exist; + }); + it('returned dispatcher should handle enter/update/exit events', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.include.keys(['enterDone', 'updateDone', 'exitDone'].concat(customEvents)); + }); + }); + + describe('#getPropertyValue(name, d, i)', function(){ + it('should return computed value for specified property name, d and i', function(){ + var d = {a: 99}; + var i = 2; + + chartlet.property('foo', 1); + chartlet.property('bar', 'two'); + chartlet.property('baz', function(d:{a:number}, i: number) {return 3;}); + chartlet.property('qux', function(d:{a:number}, i: number) {return 'four';}); + chartlet.property('nux', function(d:{a:number}, i: number) {return d.a * i;}); + + expect(chartlet.getPropertyValue('foo', d, i)).to.equal(1); + expect(chartlet.getPropertyValue('bar', d, i)).to.equal('two'); + expect(chartlet.getPropertyValue('baz', d, i)).to.equal(3); + expect(chartlet.getPropertyValue('qux', d, i)).to.equal('four'); + expect(chartlet.getPropertyValue('nux', d, i)).to.equal(198); + }); + }); + + describe('#property(name, valueOrFn)', function(){ + describe('should act as a getter when called with one argument', function(){ + it('should always return a function', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + }); + it('should return a function that return undefined for unknown property name', function(){ + expect(chartlet.property('unknown name')).to.be.a('Function'); + expect(chartlet.property('unknown name')()).to.equal(undefined); + }); + }); + + describe('should act as a setter when called with two arguments', function(){ + it('should set specified property to a functor of given value', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + expect(chartlet.property('bar')()).to.equal(100); + }); + it('should overwrite previous value when set property with the same name', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('foo', 100); + expect(chartlet.property('foo')()).to.equal(100); + }); + }); + }); + + describe('#on(eventName, listener)', function(){ + it('event "enterDone" should be triggered after chartlet.enter() is completed.', function(done){ + chartlet.on('enterDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.enter(); + }); + it('event "updateDone" should be triggered after chartlet.update() is completed.', function(done){ + chartlet.on('updateDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.update(); + }); + it('event "exitDone" should be triggered after chartlet.exit() is completed.', function(done){ + chartlet.on('exitDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.exit(); + }); + }); + + describe('#inheritPropertyFrom(parentChartlet, parentPropertyName, childPropertyName)', function(){ + it('it should cause a child to inherit a parent property', function() { + var parent = ParentChartlet(function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo', 'bar'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('bar', 4, 0)).to.be.equal(8); + }); + }); + + it('it should default to the parent property name', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 4, 0)).to.be.equal(8); + }); + }); + }); + + describe('#inheritProperties(parentChartlet, parentPropertyNames, childPropertyNames)', function(){ + it('it should cause a child to inherit many parent properties', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz'], ['foo-x', 'bar-x', 'baz-x']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo-x', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar-x', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz-x', 1, 0)).to.be.equal(4); + }); + }); + + it('it should default to the parent property names', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz', 1, 0)).to.be.equal(4); + }); + }); + }); + + describe('#publishEventsTo(foreignDispatcher)', function(){ + it('should map events to a foreignDispatcher', function(done) { + + var parent = new d3kit.Chartlet(callback, callback, callback, ['foo']); + parent.getDispatcher().on('foo', function(value:number) { + expect(value).to.be.equal(99); + done(); + }); + + var child = new d3kit.Chartlet(callback, callback, callback, ['foo']) + .publishEventsTo(parent.getDispatcher()); + + (child.getDispatcher()).foo(99); + }); + }); +}); + +describe('#createChart', function(){ + var Chart = d3kit.factory.createChart({}, ['test'], function(skeleton: d3kit.Skeleton){ + return skeleton; + }); + + it('should return a function to create a chart', function(){ + expect(Chart).to.be.a('Function'); + }); + + // // Don't think it's possible to define these in a d.ts file; skipping + // it('results should have function getCustomEvents()', function(){ + // expect(Chart.getCustomEvents).to.exist; + // expect(Chart.getCustomEvents()).to.deep.equal(['test']); + // }); +}); + +describe('d3kit.helper', function(){ + + describe('#dasherize(str)', function(){ + it('should convert input to dash-case', function(){ + expect(d3kit.helper.dasherize('camelCase')).to.equal('camel-case'); + }); + }); + + describe('#deepExtend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { d: fn1, e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], j: [3,4,5], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#extend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should NOT perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#isFunction(function)', function(){ + it('should return true if the value is a function', function(){ + var fn1 = function(d:number){return d + 1;}; + function fn2(d:number){return d + 2;} + + expect(d3kit.helper.isFunction(fn1)).to.be.true; + expect(d3kit.helper.isFunction(fn2)).to.be.true; + }); + it('should return false if the value is not a function', function(){ + expect(d3kit.helper.isFunction(0)).to.be.false; + expect(d3kit.helper.isFunction(1)).to.be.false; + expect(d3kit.helper.isFunction(true)).to.be.false; + expect(d3kit.helper.isFunction('what')).to.be.false; + expect(d3kit.helper.isFunction(null)).to.be.false; + expect(d3kit.helper.isFunction(undefined)).to.be.false; + }); + }); + + describe('#isNumber(value)', function(){ + it('should return true for number', function(){ + expect(d3kit.helper.isNumber(1)).to.be.true; + expect(d3kit.helper.isNumber(0)).to.be.true; + expect(d3kit.helper.isNumber(-1)).to.be.true; + }); + it('should return false for string even if it is a number', function(){ + expect(d3kit.helper.isNumber('')).to.be.false; + expect(d3kit.helper.isNumber('1')).to.be.false; + expect(d3kit.helper.isNumber('0')).to.be.false; + expect(d3kit.helper.isNumber('what')).to.be.false; + }); + it('should return false for null and undefined', function(){ + expect(d3kit.helper.isNumber(null)).to.be.false; + expect(d3kit.helper.isNumber(undefined)).to.be.false; + }); + }); +}); + diff --git a/d3kit/d3kit.d.ts b/d3kit/d3kit.d.ts new file mode 100644 index 0000000000..4e53472b7b --- /dev/null +++ b/d3kit/d3kit.d.ts @@ -0,0 +1,155 @@ +// Type definitions for d3Kit v1.1.0 +// Project: https://www.npmjs.com/package/d3kit +// Definitions by: Morgan Benton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace d3kit { + + export interface ChartMargin { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + + export interface ChartOptions { + margin?: ChartMargin; + offset?: [number,number]; + initialWidth?: number; + initialHeight?: number; + [name: string]: any; + } + + export interface ChartMixin { + [name: string]: any; + } + + export class Skeleton { + + constructor(selector: string|Element, options?: ChartOptions, customEvents?: Array); + + // Getters + getCustomEventNames(): Array; + getDispatcher(): any; // should be d3.Dispatch but this throws error for user-created events + getInnerWidth(): number; + getInnerHeight(): number; + getLayerOrganizer(): LayerOrganizer; + getRootG(): d3.Selection; + getSvg(): d3.Selection; + + // Getter/Setters + data(): any; + data(data?: any, doNotDispatch?: boolean): Skeleton; + options(): any; // wish this could be ChartOptions + options(options: ChartOptions, doNotDispatch?: boolean): Skeleton; + margin(): ChartMargin; + margin(margin: ChartMargin, doNotDispatch?: boolean): Skeleton; + offset(): [number, number]; + offset(offset: Array, doNotDispatch?: boolean): Skeleton; + width(): number; + width(value: number|string, doNotDispatch?: boolean): Skeleton; + height(): number; + height(value: number|string, doNotDispatch?: boolean): Skeleton; + dimension(): [number, number]; + dimension(dimension: [number|string, number|string], doNotDispatch?: boolean): Skeleton; + autoResize(mode?: string|boolean): string|boolean|void; + autoResizeDetection(method?:string): string|void; + autoResizeToAspectRatio(ratio?: number|boolean): number|boolean|void; + + // Other functions + on(eventName: string, listener: (...args: Array) => void): void; + hasData(): boolean; + hasNonZeroArea(): boolean; + mixin(fn: ChartMixin): void; + resizeToFitContainer(mode: string|boolean, doNotDispatch?: boolean): void; + resizeToAspectRatio(ratio: number, doNotDispatch?: boolean): void; + } + + interface ChartletPropertyCallback { + (datum?: any, datum_index?: number): any; + } + + export interface ChartletEventFunction { + (sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + } + + export class Chartlet { + + constructor( + enterFunction?: ChartletEventFunction, + updateFunction?: ChartletEventFunction, + exitFunction?: ChartletEventFunction, + customEventName?: Array); + + // Getter functions + getDispatcher(): d3.Dispatch; + getCustomEventNames(): Array; + getPropertyValue(name: string, datum: any, datum_index: number): any; + + // Getter/Setter functions + property(name: string): ChartletPropertyCallback; + property(name: string, value: any): Chartlet; + + // Enter/Update/Exit functions + enter( sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + update(sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + exit( sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + + // Inheritance functions + inheritPropertyFrom(parent_chartlet: Chartlet, parent_property_name: string, child_property_name?: string): void; + inheritPropertiesFrom(parent_chartlet: Chartlet, parent_property_names: Array, child_property_names?: Array): void; + publishEventsTo(dispatcher: d3.Dispatch): Chartlet; + + // Events + on(eventName: string, handlerFunction: ChartletEventFunction): void; + } + + interface LayerConfig { + name?: string, + names?: Array, + sublayers?: LayerConfig + } + + export class LayerOrganizer { + + constructor(container: d3.Selection, tag?: string); + + create(config: string|Array|LayerConfig|Array): d3.Selection|Array>; + get(name: string): d3.Selection; + has(name: string): boolean; + } + + export namespace factory { + export function createChart( + defaultOptions: ChartOptions, + customEvents: Array, + constructor: (skeleton: Skeleton) => void + ): (selector: string|Element, options?: ChartOptions, customEvents?: Array) => Skeleton; + } + + export namespace helper { + export function debounce(fn: (...args: Array) => void, wait: number, immediate: boolean): (...args: Array) => void; + export function extend(target: Object, ...args: Object[]): Object; + export function deepExtend(target: Object, ...args: Object[]): Object; + export function bindMouseEventsToDispatcher(selection: d3.Selection, dispatch: d3.Dispatch, prefix: string): void; + export function removeAllChildren(selection: d3.Selection, noTransition: boolean): d3.Selection; + export function on(element: Element, type: string, listener: (...args: Array) => void): void; + export function off(element: Element, type: string, listener: (...args: Array) => void): void; + export function trim(str: string, characters: string): string; + export function dasherize(str: string): string; + export function $(s: Element|string): Element; + export function $$(s: Array|NodeList): Array; + export function isArray(value: any): boolean; + export function isNumber(value: any): boolean; + export function isObject(value: any): boolean; + export function isElement(o: any): boolean; + export function isFunction(functionToCheck: any): boolean; + } + +} + +declare module 'd3kit' { + export = d3kit; +} \ No newline at end of file diff --git a/d3pie/d3pie-tests.ts b/d3pie/d3pie-tests.ts new file mode 100644 index 0000000000..4d8a38280f --- /dev/null +++ b/d3pie/d3pie-tests.ts @@ -0,0 +1,146 @@ +/// + +let chart = new d3pie('test', + { + header: { + title: { + text: '', + color: '#333333', + fontSize: 18, + font: 'arial' + }, + subtitle: { + color: '#666666', + fontSize: 14, + font: 'arial' + }, + location: 'top-center', + titleSubtitlePadding: 8 + }, + footer: { + text: '', + color: '#666666', + fontSize: 14, + font: 'arial', + location: 'left' + }, + size: { + canvasHeight: 500, + canvasWidth: 500, + pieInnerRadius: 0, + pieOuterRadius: null + }, + data: { + sortOrder: 'none', + smallSegmentGrouping: { + enabled: false, + value: 1, + valueType: 'percentage', + label: 'Other', + color: '#cccccc' + }, + content: [] + }, + labels: { + outer: { + format: 'label', + hideWhenLessThanPercentage: null, + pieDistance: 30 + }, + inner: { + format: 'percentage', + hideWhenLessThanPercentage: null + }, + mainLabel: { + color: '#333333', + font: 'arial', + fontSize: 10 + }, + percentage: { + color: '#dddddd', + font: 'arial', + fontSize: 10, + decimalPlaces: 0 + }, + value: { + color: '#cccc44', + font: 'arial', + fontSize: 10 + }, + lines: { + enabled: true, + style: 'curved', + color: 'segment' // 'segment' or a hex color + } + }, + effects: { + load: { + effect: 'default', // none / default + speed: 1000 + }, + pullOutSegmentOnClick: { + effect: 'bounce', // none / linear / bounce / elastic / back + speed: 300, + size: 10 + }, + highlightSegmentOnMouseover: true, + highlightLuminosity: -0.2 + }, + tooltips: { + enabled: false, + type: 'placeholder', // caption|placeholder + string: '', + placeholderParser: null, + styles: { + fadeInSpeed: 250, + backgroundColor: '#000000', + backgroundOpacity: 0.5, + color: '#efefef', + borderRadius: 2, + font: 'arial', + fontSize: 10, + padding: 4 + } + }, + + misc: { + colors: { + background: null, // transparent + segments: [ + '#2484c1', '#65a620', '#7b6888', '#a05d56', '#961a1a', + '#d8d23a', '#e98125', '#d0743c', '#635222', '#6ada6a', + '#0c6197', '#7d9058', '#207f33', '#44b9b0', '#bca44a', + '#e4a14b', '#a3acb2', '#8cc3e9', '#69a6f9', '#5b388f', + '#546e91', '#8bde95', '#d2ab58', '#273c71', '#98bf6e', + '#4daa4b', '#98abc5', '#cc1010', '#31383b', '#006391', + '#c2643f', '#b0a474', '#a5a39c', '#a9c2bc', '#22af8c', + '#7fcecf', '#987ac6', '#3d3b87', '#b77b1c', '#c9c2b6', + '#807ece', '#8db27c', '#be66a2', '#9ed3c6', '#00644b', + '#005064', '#77979f', '#77e079', '#9c73ab', '#1f79a7' + ], + segmentStroke: '#ffffff' + }, + gradient: { + enabled: false, + percentage: 95, + color: '#000000' + }, + canvasPadding: { + top: 5, + right: 5, + bottom: 5, + left: 5 + }, + pieCenterOffset: { + x: 0, + y: 0 + }, + cssPrefix: null + }, + callbacks: { + onload: null, + onMouseoverSegment: null, + onMouseoutSegment: null, + onClickSegment: null + } + }) \ No newline at end of file diff --git a/d3pie/d3pie.d.ts b/d3pie/d3pie.d.ts new file mode 100644 index 0000000000..2bfe5d6525 --- /dev/null +++ b/d3pie/d3pie.d.ts @@ -0,0 +1,146 @@ +// Type definitions for d3pie 0.1.9 +// Project: https://github.com/benkeen/d3pie +// Definitions by: Petryshyn Sergii +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace d3pie { + interface ID3PieChart { + redraw(): void + openSegment(index: number): void + closeSegment(index: void): void + getOpenSegment(): any + updateProp(propKey: string, value: any): void + destroy(): void + } + + interface ID3PieStyleOptions { + color?: string + fontSize?: number + font?: string + } + + interface ID3PieTextOptions extends ID3PieStyleOptions { + text?: string + } + + interface ID3PieLabelsOptions { + format?: 'label' | 'value' | 'percentage' | 'label-value1' | 'label-value2' | 'label-percentage1' | 'label-percentage2' + hideWhenLessThanPercentage?: number + } + + interface ID3PieOptions { + header?: { + title?: ID3PieTextOptions + subtitle?: ID3PieTextOptions + location?: 'top-center' | 'top-left' | 'pie-center' + titleSubtitlePadding?: number + } + footer?: { location?: 'left' } & ID3PieTextOptions + size?: { + canvasHeight?: number + canvasWidth?: number + pieOuterRadius?: string | number + pieInnerRadius?: string | number + } + data: { + sortOrder?: 'none' | 'random' | 'value-asc' | 'value-desc' | 'label-asc' | 'label-desc' + smallSegmentGrouping?: { + enabled?: boolean + value?: number + valueType?: 'percentage' | 'value' + label?: string + color?: string + } + content: { + label: string + value: number + color?: string + }[] + } + labels?: { + outer?: { pieDistance?: number } & ID3PieLabelsOptions + inner?: ID3PieLabelsOptions + mainLabel?: ID3PieStyleOptions + percentage?: { decimalPlaces?: number } & ID3PieStyleOptions + value?: ID3PieStyleOptions + lines?: { + enabled?: boolean + style?: 'curved' | 'straight' + color?: string + } + truncation?: { + enabled?: boolean + truncateLength?: number + } + formatter?: (context: { + section: 'outer' | 'inner' + value: number + label: string + }) => string + } + effects?: { + load?: { + effect?: 'none' | 'default' + speed?: number + } + pullOutSegmentOnClick?: { + effect?: 'none' | 'linear' | 'bounce' | 'elastic' | 'back' + speed?: number + size?: number + } + highlightSegmentOnMouseover?: boolean + highlightLuminosity?: number + } + tooltips?: { + enabled?: boolean + type?: 'placeholder' | 'caption' + string?: string + placeholderParser?: (index: number, data: { label?: string, percentage?: number, value?: number }) => void + styles?: { + fadeInSpeed?: number + backgroundColor?: string + backgroundOpacity?: number + color?: string + borderRadius?: number + font?: string + fontSize?: number + padding?: number + } + } + misc?: { + colors?: { + background?: string + segments?: string[] + segmentStroke?: string + } + gradient?: { + enabled?: boolean + percentage?: number + color?: string + } + canvasPadding?: { + top?: number + right?: number + bottom?: number + left?: number + } + pieCenterOffset?: { + x?: number + y?: number + } + cssPrefix?: string + } + callbacks?: { + onload?: Function + onMouseoverSegment?: Function + onMouseoutSegment?: Function + onClickSegment?: Function + } + } + + interface ID3PieClass { + new (id: string | HTMLElement, options: ID3PieOptions): ID3PieChart + } +} + +declare const d3pie: d3pie.ID3PieClass \ No newline at end of file diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts index 836ae6f291..d5e712a66c 100644 --- a/dagre-d3/dagre-d3-tests.ts +++ b/dagre-d3/dagre-d3-tests.ts @@ -11,6 +11,9 @@ namespace DagreD3Tests { predecessors["a"] = graph.predecessors("a"); successors["a"] = graph.successors("a"); + graph.transition = (selection: d3.Selection) => { + return d3.transition(); + }; const render = new dagreD3.render(); const svg = d3.select("svg"); diff --git a/dagre-d3/dagre-d3.d.ts b/dagre-d3/dagre-d3.d.ts index cbf3bf458a..9248222e98 100644 --- a/dagre-d3/dagre-d3.d.ts +++ b/dagre-d3/dagre-d3.d.ts @@ -19,6 +19,8 @@ declare namespace Dagre { height: number; predecessors(id: string): string[]; successors(id: string): string[]; + // see source of http://cpettitt.github.io/project/dagre-d3/latest/demo/interactive-demo.html + transition?(selection: d3.Selection): d3.Transition; width: number; } diff --git a/DataStream.js/DataStream.js-tests.ts b/datastream.js/datastream.js-tests.ts similarity index 98% rename from DataStream.js/DataStream.js-tests.ts rename to datastream.js/datastream.js-tests.ts index 71bb08537e..94fb86f367 100644 --- a/DataStream.js/DataStream.js-tests.ts +++ b/datastream.js/datastream.js-tests.ts @@ -1,4 +1,4 @@ -/// +/// var buf = new ArrayBuffer(100); var ds = new DataStream(buf); diff --git a/DataStream.js/DataStream.js.d.ts b/datastream.js/datastream.js.d.ts similarity index 100% rename from DataStream.js/DataStream.js.d.ts rename to datastream.js/datastream.js.d.ts diff --git a/echarts/echarts.d.ts b/echarts/echarts.d.ts new file mode 100644 index 0000000000..f460a9eaca --- /dev/null +++ b/echarts/echarts.d.ts @@ -0,0 +1,133 @@ +// Type definitions for echarts +// Project: http://echarts.baidu.com/ +// Definitions by: Xie Jingyang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ECharts { + function init(dom:HTMLDivElement|HTMLCanvasElement, theme?:Object|string, opts?:{ + devicePixelRatio?: number + renderer?: string + }):ECharts; + + function connect(group:string|Array):void; + + function disConnect(group:string):void; + + function dispose(target:ECharts|HTMLDivElement|HTMLCanvasElement):void; + + function getInstanceByDom(target:HTMLDivElement|HTMLCanvasElement):void; + + function registerMap(mapName:string, geoJson:Object, specialAreas?:Object):void; + + function registerTheme(themeName:string, theme:Object):void; + + class ECharts { + group:string; + + setOption(option:EChartOption, notMerge?:boolean, notRefreshImmediately?:boolean):void + + getWidth():number + + getHeight():number + + getDom():HTMLCanvasElement|HTMLDivElement + + getOption():Object + + resize():void + + dispatchAction(payload:Object):void + + on(eventName:string, handler:Function, context?:Object):void + + off(eventName:string, handler?:Function):void + + showLoading(type?:string, opts?:Object):void + + hideLoading():void + + getDataURL(opts:{ + // 导出的格式,可选 png, jpeg + type?: string, + // 导出的图片分辨率比例,默认为 1。 + pixelRatio?: number, + // 导出的图片背景色,默认使用 option 里的 backgroundColor + backgroundColor?: string + }):string + + getConnectedDataURL(opts:{ + // 导出的格式,可选 png, jpeg + type: string, + // 导出的图片分辨率比例,默认为 1。 + pixelRatio: number, + // 导出的图片背景色,默认使用 option 里的 backgroundColor + backgroundColor: string + }):string + + clear():void + + isDisposed():boolean + + dispose():void + } + + interface EChartOption { + title?: EChartTitleOption + legend?: Object, + grid?: Object, + xAxis?: Object, + yAxis?: Object, + polar?: Object, + radiusAxis?: Object, + angleAxis?: Object, + radar?: Object, + dataZoom?: Array, + visualMap?: Array, + tooltip?: Object, + toolbox?: Object, + geo?: Object, + parallel?: Object, + parallelAxis?: Object, + timeline?: Object, + series?: Array, + color?: Array, + backgroundColor?: string, + textStyle?: Object, + animation?: boolean, + animationDuration?: number, + animationEasing?: string, + animationDurationUpdate?: number, + animationEasingUpdate?: string + } + + interface EChartTitleOption { + show?: boolean; + text?: string; + link?: string, + target?: string, + textStyle?: Object, + subtext?: string, + sublink?: string, + subtarget?: string, + subtextStyle?: Object, + padding?: number, + itemGap?: number, + zlevel?: number, + z?: number, + left?: string, + top?: string, + right?: string, + bottom?: string, + backgroundColor?: string, + borderColor?: string, + borderWidth?: number, + shadowBlur?: number, + shadowColor?: number, + shadowOffsetX?: number, + shadowOffsetY?: number, + } +} + +declare module "echarts" { + export = ECharts; +} diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index bd5f4009d2..30fe9512bf 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -71,6 +71,7 @@ declare namespace esprima { LabeledStatement: string, LogicalExpression: string, MemberExpression: string, + MetaProperty: string, MethodDefinition: string, NewExpression: string, ObjectExpression: string, diff --git a/exorcist/exorcist-tests.ts b/exorcist/exorcist-tests.ts new file mode 100644 index 0000000000..26a1be0e07 --- /dev/null +++ b/exorcist/exorcist-tests.ts @@ -0,0 +1,15 @@ +/// + +import exorcist = require("exorcist"); + +module ExorcistTest { + + function pullSourceMaps(srcPath: string, projRoot: string) { + exorcist(srcPath, undefined, projRoot); + exorcist(srcPath, null, projRoot, null, true); + exorcist(srcPath, null, projRoot, "./"); + } + +} + +export = ExorcistTest; \ No newline at end of file diff --git a/exorcist/exorcist.d.ts b/exorcist/exorcist.d.ts new file mode 100644 index 0000000000..a60908915b --- /dev/null +++ b/exorcist/exorcist.d.ts @@ -0,0 +1,21 @@ +// Type definitions for exorcist v0.4.0 +// Project: https://github.com/thlorenz/exorcist +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'exorcist' { + import through = require("through"); + + /** Externalizes the source map found inside a stream to an external .map file. + * Works with both JavaScript and CSS input streams + * @param file full path to the map file to which to write the extracted source map + * @param [url] full URL to the map file, set as sourceMappingURL in the streaming output (default: file) + * @param [root] root URL for loading relative source paths, set as sourceRoot in the source map (default: "") + * @param [base] base path for calculating relative source paths (default: use absolute paths) + * @param [errorOnMissing] when truthy, causes 'error' to be emitted instead of 'missing-map' if no map was found in the stream (default: falsey) + */ + function exorcist(file: string, url?: string, root?: string, base?: string, errorOnMissing?: boolean): through.ThroughStream; + export = exorcist; +} \ No newline at end of file diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 2662222d00..e15dbcb5b6 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -17,21 +17,23 @@ declare namespace Express { declare module "express-serve-static-core" { import * as http from "http"; + type RequestHandlerParams = RequestHandler | RequestHandler[]; + interface IRoute { path: string; stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - head(...handler: RequestHandler[]): IRoute; + all(...handler: RequestHandlerParams[]): IRoute; + get(...handler: RequestHandlerParams[]): IRoute; + post(...handler: RequestHandlerParams[]): IRoute; + put(...handler: RequestHandlerParams[]): IRoute; + delete(...handler: RequestHandlerParams[]): IRoute; + patch(...handler: RequestHandlerParams[]): IRoute; + options(...handler: RequestHandlerParams[]): IRoute; + head(...handler: RequestHandlerParams[]): IRoute; } interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandler[]): T; + (name: string | RegExp, ...handlers: RequestHandlerParams[]): T; } interface IRouter extends RequestHandler { @@ -88,13 +90,13 @@ declare module "express-serve-static-core" { route(path: string): IRoute; - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler | RequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandler): T; - use(path: string[], ...handler: RequestHandler[]): T; + use(...handler: RequestHandlerParams[]): T; + use(handler: ErrorRequestHandler | RequestHandlerParams): T; + use(path: string, ...handler: RequestHandlerParams[]): T; + use(path: string, handler: ErrorRequestHandler | RequestHandlerParams): T; + use(path: string[], ...handler: RequestHandlerParams[]): T; use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandler[]): T; + use(path: RegExp, ...handler: RequestHandlerParams[]): T; use(path: RegExp, handler: ErrorRequestHandler): T; use(path: string, router: Router): T; } @@ -860,7 +862,7 @@ declare module "express-serve-static-core" { set(setting: string, val: any): Application; get: { (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandler[]): Application; + (name: string | RegExp, ...handlers: RequestHandlerParams[]): Application; }; /** diff --git a/fbemitter/fbemitter.d.ts b/fbemitter/fbemitter.d.ts index b26b1a3162..0f5f6af528 100644 --- a/fbemitter/fbemitter.d.ts +++ b/fbemitter/fbemitter.d.ts @@ -3,7 +3,7 @@ // Definitions by: kmxz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'fbemitter' { +declare namespace FBEmitter { export class EventSubscription { @@ -64,4 +64,8 @@ declare module 'fbemitter' { } -} \ No newline at end of file +} + +declare module 'fbemitter' { + export = FBEmitter; +} diff --git a/fbsdk/fbsdk.d.ts b/fbsdk/fbsdk.d.ts index 6153de6579..79c710f8f7 100644 --- a/fbsdk/fbsdk.d.ts +++ b/fbsdk/fbsdk.d.ts @@ -150,6 +150,7 @@ interface FBSDKCanvas{ } interface FBResponseObject { + data: any; error: any; } diff --git a/flickity/flickity-tests.ts b/flickity/flickity-tests.ts index 8d06e4ee7f..4f155f3e17 100644 --- a/flickity/flickity-tests.ts +++ b/flickity/flickity-tests.ts @@ -30,7 +30,7 @@ percentPosition: false, prevNextButtons: false, selectedAttraction: 0.050, - useSetGallerySize: true, + setGallerySize: true, watchCSS: true, wrapAround: true, resize: true, @@ -64,7 +64,7 @@ percentPosition: false, prevNextButtons: false, selectedAttraction: 0.050, - useSetGallerySize: true, + setGallerySize: true, watchCSS: true, wrapAround: true, resize: true, diff --git a/flickity/flickity.d.ts b/flickity/flickity.d.ts index bf4541e5ff..febb09b525 100644 --- a/flickity/flickity.d.ts +++ b/flickity/flickity.d.ts @@ -269,7 +269,7 @@ interface FlickityOptions { * * default: true */ - useSetGallerySize?: boolean; + setGallerySize?: boolean; /** * Adjusts sizes and positions when window is resized. diff --git a/flux/flux-tests.ts b/flux/flux-tests.ts index 24369ef2dd..6bb4350dc6 100644 --- a/flux/flux-tests.ts +++ b/flux/flux-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import flux = require('flux') import FluxUtils = require('flux/utils') @@ -88,7 +88,7 @@ export = customDispatcher // Sample Reduce Store -class CounterStore extends FluxUtils.ReduceStore { +class CounterStore extends FluxUtils.ReduceStore { getInitialState(): number { return 0; } @@ -126,4 +126,4 @@ class CounterContainer extends Component { } } -const container = Container.create(CounterContainer); +const container = Container.create(CounterContainer); diff --git a/flux/flux.d.ts b/flux/flux.d.ts index 944d23b011..944aa54f3a 100644 --- a/flux/flux.d.ts +++ b/flux/flux.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// +/// declare namespace Flux { @@ -71,6 +73,29 @@ declare module "flux" { declare namespace FluxUtils { import React = __React; + import fbEmitter = FBEmitter; + import immutable = Immutable; + + /** + * Default options to create a Container with + * + * @interface RealOptions + */ + interface RealOptions { + /** + * Default value: true + * + * @type {boolean} + */ + pure?: boolean; + /** + * Default value: false + * + * @type {boolean} + */ + withProps?: boolean; + } + export class Container { constructor(); /** @@ -78,14 +103,13 @@ declare namespace FluxUtils { * that updates its state when relevant stores change. * The provided base class must have static methods getStores() and calculateState(). */ - static create(base: React.ComponentClass, options?: any): React.ComponentClass; + static create(base: React.ComponentClass, options?: RealOptions): React.ComponentClass; } /** * This class extends ReduceStore and defines the state as an immutable map. */ - // TODO: Change to > - export class MapStore extends ReduceStore { + export class MapStore extends ReduceStore, TPayload> { /** * Access the value at the given key. * Throws an error if the key does not exist in the cache. @@ -108,12 +132,10 @@ declare namespace FluxUtils { * it allows providing a previous result to update instead of generating a new map. * Providing a previous result allows the possibility of keeping the same reference if the keys did not change. */ - // TODO: Update with Immutable interface. - // getAll(keys: Immutable.IndexedIterable, prev?: Immutable.Map): Immutable.Map; - getAll(keys: any, prev?: any): any; + getAll(keys: immutable.Iterable.Indexed, prev?: immutable.Map): immutable.Map; } - export class ReduceStore extends Store { + export class ReduceStore extends Store { /** * Getter that exposes the entire state of this store. * If your state is not immutable you should override this and not expose state directly. @@ -131,7 +153,7 @@ declare namespace FluxUtils { * All subclasses must implement this method. * This method should be pure and have no side-effects. */ - reduce(state: T, action: any): T; + reduce(state: T, action: TPayload): T; /** * Checks if two versions of state are the same. @@ -141,24 +163,24 @@ declare namespace FluxUtils { } - export class Store { + export class Store { /** * Constructs and registers an instance of this store with the given dispatcher. */ - constructor(dispatcher: Flux.Dispatcher); + constructor(dispatcher: Flux.Dispatcher); /** * Adds a listener to the store, when the store changes the given callback will be called. * A token is returned that can be used to remove the listener. * Calling the remove() function on the returned token will remove the listener. */ - addListener(callback: Function): { remove: Function }; + addListener(callback: Function): fbEmitter.EventSubscription; /** * Returns the dispatcher this store is registered with. */ - getDispatcher(): Flux.Dispatcher; + getDispatcher(): Flux.Dispatcher; /** * Returns the dispatch token that the dispatcher recognizes this store by. @@ -185,7 +207,7 @@ declare namespace FluxUtils { * This is how the store receives actions from the dispatcher. * All state mutation logic must be done during this method. */ - __onDispatch(payload: any): void; + __onDispatch(payload: TPayload): void; } } diff --git a/fs-extra/fs-extra-tests.ts b/fs-extra/fs-extra-tests.ts index c1785f851d..a31df8cfd7 100644 --- a/fs-extra/fs-extra-tests.ts +++ b/fs-extra/fs-extra-tests.ts @@ -2,50 +2,16 @@ /// import fs = require('fs-extra'); -import stream = require('stream'); -var stats: fs.Stats; -var str: string; -var strArr: string[]; -var bool: boolean; -var num: number; var src: string; var dest: string; var file: string; -var filename: string; var dir: string; var path: string; var data: any; var object: Object; -var buffer: NodeBuffer; -var modeNum: number; -var modeStr: string; -var encoding: string; -var type: string; -var flags: string; -var srcpath: string; -var dstpath: string; -var oldPath: string; -var newPath: string; -var cache: string; -var offset: number; -var length: number; -var position: number; -var cacheBool: boolean; -var cacheStr: string; -var fd: number; -var len: number; -var uid: number; -var gid: number; -var atime: number; -var mtime: number; -var statsCallback: (err: Error, stats: fs.Stats) => void; var errorCallback: (err: Error) => void; var openOpts: fs.OpenOptions; -var watcher: fs.FSWatcher; -var readStreeam: stream.Readable; -var writeStream: stream.Writable; -var outputStream: stream.Writable; fs.copy(src, dest, errorCallback); fs.copy(src, dest, (src: string) => { @@ -125,130 +91,6 @@ fs.writeJSON(file, object, openOpts, errorCallback); fs.writeJsonSync(file, object, openOpts); fs.writeJSONSync(file, object, openOpts); -fs.rename(oldPath, newPath, errorCallback); -fs.renameSync(oldPath, newPath); -fs.truncate(fd, len, errorCallback); -fs.truncateSync(fd, len); -fs.chown(path, uid, gid, errorCallback); -fs.chownSync(path, uid, gid); -fs.fchown(fd, uid, gid, errorCallback); -fs.fchownSync(fd, uid, gid); -fs.lchown(path, uid, gid, errorCallback); -fs.lchownSync(path, uid, gid); -fs.chmod(path, modeNum, errorCallback); -fs.chmod(path, modeStr, errorCallback); -fs.chmodSync(path, modeNum); -fs.chmodSync(path, modeStr); -fs.fchmod(fd, modeNum, errorCallback); -fs.fchmod(fd, modeStr, errorCallback); -fs.fchmodSync(fd, modeNum); -fs.fchmodSync(fd, modeStr); -fs.lchmod(path, modeStr, errorCallback); -fs.lchmod(path, modeNum, errorCallback); -fs.lchmodSync(path, modeNum); -fs.lchmodSync(path, modeStr); -fs.stat(path, statsCallback); -fs.lstat(path, statsCallback); -fs.fstat(fd, statsCallback); -stats = fs.statSync(path); -stats = fs.lstatSync(path); -stats = fs.fstatSync(fd); -fs.link(srcpath, dstpath, errorCallback); -fs.linkSync(srcpath, dstpath); -fs.symlink(srcpath, dstpath, type, errorCallback); -fs.symlinkSync(srcpath, dstpath, type); -fs.readlink(path, (err: Error, linkString: string) => { - -}); -fs.realpath(path, (err: Error, resolvedPath: string) => { - -}); -fs.realpath(path, cache, (err: Error, resolvedPath: string) => { - -}); -str = fs.realpathSync(path, cacheBool); -fs.unlink(path, errorCallback); -fs.unlinkSync(path); -fs.rmdir(path, errorCallback); -fs.rmdirSync(path); -fs.mkdir(path, modeNum, errorCallback); -fs.mkdir(path, modeStr, errorCallback); -fs.mkdirSync(path, modeNum); -fs.mkdirSync(path, modeStr); -fs.readdir(path, (err: Error, files: string[]) => { - -}); -strArr = fs.readdirSync(path); -fs.close(fd, errorCallback); -fs.closeSync(fd); -fs.open(path, flags, modeStr, (err: Error, fd: number) => { - -}); -num = fs.openSync(path, flags, modeStr); -fs.utimes(path, atime, mtime, errorCallback); -fs.utimesSync(path, atime, mtime); -fs.futimes(fd, atime, mtime, errorCallback); -fs.futimesSync(fd, atime, mtime); -fs.fsync(fd, errorCallback); -fs.fsyncSync(fd); -fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { - -}); -num = fs.writeSync(fd, buffer, offset, length, position); -fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { - -}); -num = fs.readSync(fd, buffer, offset, length, position); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { - -}); -fs.readFile(filename, encoding, (err: Error, data: string) => { - -}); -fs.readFile(filename, openOpts, (err: Error, data: string) => { - -}); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { - -}); -buffer = fs.readFileSync(filename); -str = fs.readFileSync(filename, encoding); -str = fs.readFileSync(filename, openOpts); - -fs.writeFile(filename, data, errorCallback); -fs.writeFile(filename, data, encoding, errorCallback); -fs.writeFile(filename, data, openOpts, errorCallback); -fs.writeFileSync(filename, data); -fs.writeFileSync(filename, data, encoding); -fs.writeFileSync(filename, data, openOpts); - -fs.appendFile(filename, data, errorCallback); -fs.appendFile(filename, data, encoding, errorCallback); -fs.appendFile(filename, data, openOpts, errorCallback); -fs.appendFileSync(filename, data); -fs.appendFileSync(filename, data, encoding); -fs.appendFileSync(filename, data, openOpts); - -fs.watchFile(filename, { - curr: stats, - prev: stats -}); -fs.watchFile(filename, { - persistent: bool, - interval: num -}, { - curr: stats, - prev: stats -}); -fs.unwatchFile(filename); -watcher = fs.watch(filename, { persistent: bool }, (event: string, filename: string) => { - -}); -fs.exists(path, (exists: boolean) => { - -}); -bool = fs.existsSync(path); - fs.ensureDir(path, errorCallback); fs.ensureDirSync(path); fs.ensureFile(path, errorCallback); @@ -259,24 +101,3 @@ fs.ensureSymlink(path, errorCallback); fs.ensureSymlinkSync(path); fs.emptyDir(path, errorCallback); fs.emptyDirSync(path); - -readStreeam = fs.createReadStream(path); -readStreeam = fs.createReadStream(path, { - flags: str, - encoding: str, - fd: num, - mode: num, - bufferSize: num -}); -writeStream = fs.createWriteStream(path); -writeStream = fs.createWriteStream(path, { - flags: str, - encoding: str, - string: str -}); -outputStream = fs.createOutputStream(path); -outputStream = fs.createOutputStream(path, { - flags: str, - encoding: str, - string: str -}); diff --git a/fs-extra/fs-extra.d.ts b/fs-extra/fs-extra.d.ts index b133047dec..39656ce685 100644 --- a/fs-extra/fs-extra.d.ts +++ b/fs-extra/fs-extra.d.ts @@ -8,39 +8,8 @@ /// declare module "fs-extra" { - import stream = require("stream"); + export * from "fs"; - export interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - } - - export interface FSWatcher { - close(): void; - } - - export class ReadStream extends stream.Readable { } - export class WriteStream extends stream.Writable { } - - //extended methods export function copy(src: string, dest: string, callback?: (err: Error) => void): void; export function copy(src: string, dest: string, filter: CopyFilter, callback?: (err: Error) => void): void; export function copy(src: string, dest: string, options: CopyOptions, callback?: (err: Error) => void): void; @@ -77,8 +46,6 @@ declare module "fs-extra" { export function remove(dir: string, callback?: (err: Error) => void): void; export function removeSync(dir: string): void; - // export function delete(dir: string, callback?: (err: Error) => void): void; - // export function deleteSync(dir: string): void; export function writeJson(file: string, object: any, callback?: (err: Error) => void): void; export function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; @@ -88,98 +55,22 @@ declare module "fs-extra" { export function writeJsonSync(file: string, object: any, options?: OpenOptions): void; export function writeJSONSync(file: string, object: any, options?: OpenOptions): void; - export function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void; - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(fd: number, len: number, callback?: (err: Error) => void): void; - export function truncateSync(fd: number, len: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err: Error) => void): void; - export function chmod(path: string, mode: string, callback?: (err: Error) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err: Error) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err: Error) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: string, callback?: (err: Error) => void): void; - export function lchmod(path: string, mode: number, callback?: (err: Error) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; - export function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; - export function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: Error, linkString: string) => void): void; - export function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void; - export function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void; - export function realpathSync(path: string, cache?: boolean): string; - export function unlink(path: string, callback?: (err: Error) => void): void; - export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: (err: Error) => void): void; - export function rmdirSync(path: string): void; - export function mkdir(path: string, mode?: number, callback?: (err: Error) => void): void; - export function mkdir(path: string, mode?: string, callback?: (err: Error) => void): void; - export function mkdirSync(path: string, mode?: number): void; - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: Error, files: string[]) => void ): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err: Error) => void): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function fsync(fd: number, callback?: (err: Error) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void; - export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void ): void; - export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void ): void; - export function readFile(filename: string, options: OpenOptions, callback: (err: Error, data: string) => void ): void; - export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void ): void; - export function readFileSync(filename: string): NodeBuffer; - export function readFileSync(filename: string, encoding: string): string; - export function readFileSync(filename: string, options: OpenOptions): string; - export function writeFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void; - export function writeFile(filename: string, data: any, options?: OpenOptions, callback?: (err: Error) => void): void; - export function writeFileSync(filename: string, data: any, encoding?: string): void; - export function writeFileSync(filename: string, data: any, option?: OpenOptions): void; - export function appendFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void; - export function appendFile(filename: string, data: any,option?: OpenOptions, callback?: (err: Error) => void): void; - export function appendFileSync(filename: string, data: any, encoding?: string): void; - export function appendFileSync(filename: string, data: any, option?: OpenOptions): void; - export function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; - export function unwatchFile(filename: string, listener?: Stats): void; - export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void ): void; - export function existsSync(path: string): boolean; export function ensureDir(path: string, cb: (err: Error) => void): void; export function ensureDirSync(path: string): void; + export function ensureFile(path: string, cb: (err: Error) => void): void; export function ensureFileSync(path: string): void; + export function ensureLink(path: string, cb: (err: Error) => void): void; export function ensureLinkSync(path: string): void; + export function ensureSymlink(path: string, cb: (err: Error) => void): void; export function ensureSymlinkSync(path: string): void; + export function emptyDir(path: string, callback?: (err: Error) => void): void; export function emptyDirSync(path: string): boolean; - export interface CopyFilterFunction { + export interface CopyFilterFunction { (src: string): boolean } @@ -188,6 +79,7 @@ declare module "fs-extra" { export interface CopyOptions { clobber?: boolean preserveTimestamps?: boolean + dereference?: boolean filter?: CopyFilter } @@ -200,20 +92,4 @@ declare module "fs-extra" { fs?: any; mode?: number; } - - export interface ReadStreamOptions { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - bufferSize?: number; - } - export interface WriteStreamOptions { - flags?: string; - encoding?: string; - string?: string; - } - export function createReadStream(path: string, options?: ReadStreamOptions): ReadStream; - export function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream; - export function createOutputStream(path: string, options?: WriteStreamOptions): WriteStream; } diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index ce38b654b2..75cf6ffd54 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -72,6 +72,11 @@ var point: GeoJSON.Point = { coordinates: [100.0, 0.0] }; + +// This type is commonly used in the turf package +var pointCoordinates: number[] = point.coordinates + + var lineString: GeoJSON.LineString = { type: "LineString", coordinates: [ [100.0, 0.0], [101.0, 1.0] ] @@ -126,4 +131,4 @@ var geometryCollection: GeoJSON.GeometryCollection = { coordinates: [ [101.0, 0.0], [102.0, 1.0] ] } ] -} \ No newline at end of file +} diff --git a/geojson/geojson.d.ts b/geojson/geojson.d.ts index 4b4c2b56cf..38715a9a27 100644 --- a/geojson/geojson.d.ts +++ b/geojson/geojson.d.ts @@ -18,10 +18,7 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#positions */ - export interface Position - { - [index: number]: number; - } + export type Position = number[] /*** * http://geojson.org/geojson-spec.html#geometry-objects diff --git a/gijgo/gijgo-tests.ts b/gijgo/gijgo-tests.ts new file mode 100644 index 0000000000..4b981c172e --- /dev/null +++ b/gijgo/gijgo-tests.ts @@ -0,0 +1,23 @@ +/// +/// + +// Grid +$(() => { + this.grid = $('#grid').grid({ + primaryKey: 'ID', + columns: [ + { field: 'ID', width: 50, sortable: true }, + { field: 'Name', sortable: true }, + ], + pager: { limit: 5, sizes: [2, 5, 10, 20] } + }); +}); + +// Dialog +$(() => { + this.dialog = $('#playerModal').dialog({ + autoOpen: false, + title: 'Player', + width: 400 + }); +}); \ No newline at end of file diff --git a/gijgo/gijgo.d.ts b/gijgo/gijgo.d.ts new file mode 100644 index 0000000000..2f9604bbef --- /dev/null +++ b/gijgo/gijgo.d.ts @@ -0,0 +1,167 @@ +// Type definitions for Gijgo v0.6.2 +// Project: http://gijgo.com +// Definitions by: Atanas Atanasov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module Gijgo { + + //Grid + interface GridPager { + limit?: number; + sizes?: Array; + leftControls?: any; + rightControls?: any; + } + + interface GridColumn { + align?: string; + cssClass?: string; + decimalDigits?: number; + editor?: any; + events?: any; + field?: string; + format?: string; + headerCssClass?: string; + hidden?: boolean; + icon?: string; + minWidth?: number; + priority?: number; + sortable?: boolean; + stopPropagation?: boolean; + title?: string; + tmpl?: string; + tooltip?: string; + type?: string; + width?: number; + } + + interface GridDefaultParams { + direction?: string; + limit?: string; + page?: string; + sortBy?: string; + } + + interface GridMapping { + dataField?: string; + totalRecordsField?: string; + } + + interface GridSettings { + //Configuration options + autoGenerateColumns?: boolean; + autoLoad?: boolean; + columns?: Array; + dataSource?: any; + defaultColumnSettings?: GridColumn; + defaultParams?: GridDefaultParams; + detailTemplate?: string; + fontSize?: string; + mapping?: string; + minWidth?: number; + notFoundText?: string; + pager?: GridPager; + primaryKey?: string; + resizableColumns?: boolean; + resizeCheckInterval?: number; + responsive?: boolean; + selectionMethod?: string; + selectionType?: string; + showHiddenColumnsAsDetails?: boolean; + title?: string; + toolbarTemplate?: string; + uiLibrary?: string; + width?: number; + params?: any; + + //Events + beforeEmptyRowInsert?: (e: any, $row: JQuery) => any; + cellDataBound?: (e: any, $wrapper: JQuery, id: string, column: GridColumn, record: Entity) => any; + cellDataChanged?: (e: any, $cell: JQuery, column: GridColumn, record: Entity, oldValue: any, newValue: any) => any; + columnHide?: (e: any, column: GridColumn) => any; + columnShow?: (e: any, column: GridColumn) => any; + dataBinding?: (e: any, records: Array) => any; + dataBound?: (e: any, records: Array, totalRecords: number) => any; + destroying?: (e: any) => any; + detailCollapse?: (e: any, detailWrapper: JQuery, record: Entity) => any; + detailExpand?: (e: any, detailWrapper: JQuery, record: Entity) => any; + initialized?: (e: any) => any; + pageChanging?: (e: any, newPage: number) => any; + pageSizeChange?: (e: any, newPage: number) => any; + resize?: (e: any, newWidth: number, oldWidth: number) => any; + rowDataBound?: (e: any, $row: JQuery, id: string, record: Entity) => any; + rowRemoving?: (e: any, $row: JQuery, id: string, record: Entity) => any; + rowSelect?: (e: any, $row: JQuery, id: string, record: Entity) => any; + rowUnselect?: (e: any, $row: JQuery, id: string, record: Entity) => any; + } + + interface Grid extends JQuery { + addRow(record: Entity): Grid; + clear(showNotFoundText?: boolean): Grid; + count(): number; + destroy(keepTableTag?: boolean, keepWrapperTag?: boolean): void; + //get(position: number): Entity; //TODO: rename to getByPosition to avoid conflicts with jquery.get + getAll(): Array; + getById(id: string): Entity; + getChanges(): Array; + getSelected(): string; + getSelections(): Array; + hideColumn(field: string): Grid; + makeResponsive(): void; + reload(params?: Params): Grid; + removeRow(id: string): Grid; + render(response: any): Grid; + selectAll(): Grid; + setSelected(id: string | number): Grid; + showColumn(field: string): Grid; + title(text: any): any; + unSelectAll(): Grid; + updateRow(id: string, record: Entity): Grid; + } + + //Dialog + interface DialogSettings { + //Configuration options + autoOpen?: boolean; + closeOnEscape?: boolean; + draggable?: boolean; + height?: number | string; + maxHeight?: number; + maxWidth?: number; + minHeight?: number; + minWidth?: number; + modal?: boolean; + resizable?: boolean; + title?: string; + uiLibrary?: string; + width?: number; + + //Events + closed?: (e: any) => any; + closing?: (e: any) => any; + drag?: (e: any) => any; + dragStart?: (e: any) => any; + dragStop?: (e: any) => any; + initialized?: (e: any) => any; + opened?: (e: any) => any; + opening?: (e: any) => any; + resize?: (e: any) => any; + resizeStart?: (e: any) => any; + resizeStop?: (e: any) => any; + } + + interface Dialog extends JQuery { + close(): Dialog; + isOpen(): boolean; + open(): Dialog; + } +} + + +interface JQuery { + grid(settings: Gijgo.GridSettings): Gijgo.Grid; + grid(settings: Gijgo.GridSettings): Gijgo.Grid; + grid(settings: Gijgo.GridSettings): Gijgo.Grid; + + dialog(settings: Gijgo.DialogSettings): Gijgo.Dialog; +} diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index c1a1fbfaf0..9a75f9699e 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -322,6 +322,11 @@ app.on('login', function(event, webContents, request, authInfo, callback) { callback('username', 'secret'); }); +var win = new BrowserWindow({show: false}) +win.once('ready-to-show', () => { + win.show(); +}); + app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}); app.exit(0); @@ -354,6 +359,8 @@ win.show(); var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); win.setSheetOffset(toolbarRect.height); +var installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron'); + // content-tracing // https://github.com/atom/electron/blob/master/docs/api/content-tracing.md @@ -728,6 +735,8 @@ var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); +let image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); + // process // https://github.com/electron/electron/blob/master/docs/api/process.md @@ -828,15 +837,23 @@ session.defaultSession.on('will-download', (event, item, webContents) => { console.log(item.getFilename()); console.log(item.getTotalBytes()); - item.on('updated', function() { - console.log('Received bytes: ' + item.getReceivedBytes()); + item.on('updated', (event, state) => { + if (state === 'interrupted') { + console.log('Download is interrupted but can be resumed'); + } else if (state === 'progressing') { + if (item.isPaused()) { + console.log('Download is paused'); + } else { + console.log(`Received bytes: ${item.getReceivedBytes()}`); + } + } }); item.on('done', function(e, state) { if (state == "completed") { console.log("Download successfully"); } else { - console.log("Download is cancelled or interrupted that can't be resumed"); + console.log(`Download failed: ${state}`) } }); }); @@ -884,3 +901,15 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, details.requestHeaders['User-Agent'] = "MyAgent"; callback({cancel: false, requestHeaders: details.requestHeaders}); }); + +app.on('ready', function () { + const protocol = session.defaultSession.protocol + protocol.registerFileProtocol('atom', function (request, callback) { + var url = request.url.substr(7); + callback({path: path.normalize(__dirname + '/' + url)}); + }, function (error) { + if (error) { + console.error('Failed to register protocol'); + } + }) +}); diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 00730cb680..ce6efe3869 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.2.2 +// Type definitions for Electron v1.2.4 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -34,7 +34,7 @@ declare namespace Electron { /** * Emitted when the application has finished basic startup. * On Windows and Linux, the will-finish-launching event - * is the same as the ready event; on OS X, this event represents + * is the same as the ready event; on macOS, this event represents * the applicationWillFinishLaunching notification of NSApplication. * You would usually set up listeners for the open-file and open-url events here, * and start the crash reporter and auto updater. @@ -81,7 +81,7 @@ declare namespace Electron { * * You should call event.preventDefault() if you want to handle this event. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'open-file', listener: (event: Event, url: string) => void): this; /** @@ -90,12 +90,12 @@ declare namespace Electron { * * You should call event.preventDefault() if you want to handle this event. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'open-url', listener: (event: Event, url: string) => void): this; /** * Emitted when the application is activated, which usually happens when clicks on the applications’s dock icon. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'activate', listener: Function): this; /** @@ -115,6 +115,10 @@ declare namespace Electron { * Emitted when a new browserWindow is created. */ on(event: 'browser-window-created', listener: (event: Event, browserWindow: BrowserWindow) => void): this; + /** + * Emitted when a new webContents is created. + */ + on(event: 'web-contents-created', listener: (event: Event, webContents: WebContents) => void): this; /** * Emitted when failed to verify the certificate for url, to trust the certificate * you should prevent the default behavior with event.preventDefault() and call callback(true). @@ -193,18 +197,18 @@ declare namespace Electron { }): void; /** * On Linux, focuses on the first visible window. - * On OS X, makes the application the active app. + * On macOS, makes the application the active app. * On Windows, focuses on the application’s first window. */ focus(): void; /** * Hides all application windows without minimizing them. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ hide(): void; /** * Shows application windows after they were hidden. Does not automatically focus them. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ show(): void; /** @@ -253,36 +257,36 @@ declare namespace Electron { * Adds path to recent documents list. * * This list is managed by the system, on Windows you can visit the list from - * task bar, and on Mac you can visit it from dock menu. + * task bar, and on macOS you can visit it from dock menu. * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ addRecentDocument(path: string): void; /** * Clears the recent documents list. * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ clearRecentDocuments(): void; /** * Sets the current executable as the default handler for a protocol (aka URI scheme). - * Once registered, all links with your-protocol:// will be openend with the current executable. + * Once registered, all links with your-protocol:// will be opened with the current executable. * The whole link, including protocol, will be passed to your application as a parameter. * - * Note: This is only implemented on OS X and Windows. - * On OS X, you can only register protocols that have been added to your app's info.plist. + * Note: This is only implemented on macOS and Windows. + * On macOS, you can only register protocols that have been added to your app's info.plist. */ setAsDefaultProtocolClient(protocol: string): void; /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ removeAsDefaultProtocolClient(protocol: string): void; /** * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ isDefaultProtocolClient(protocol: string): boolean; /** @@ -311,13 +315,13 @@ declare namespace Electron { * @param webpageURL The webpage to load in a browser if no suitable app is * installed on the resuming device. The scheme must be http or https. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setUserActivity(type: string, userInfo: Object, webpageURL?: string): void; /** * @returns The type of the currently running activity. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ getCurrentActivityType(): string; /** @@ -339,12 +343,12 @@ declare namespace Electron { disableHardwareAcceleration(): void; commandLine: CommandLine; /** - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ dock: Dock; } - type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'; + type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'|'pepperFlashSystemPlugin'; interface ImportCertificateOptions { /** @@ -389,49 +393,49 @@ declare namespace Electron { /** * Cancel the bounce of id. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ cancelBounce(id: number): void; /** * Bounces the Downloads stack if the filePath is inside the Downloads folder. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ downloadFinished(filePath: string): void; /** * Sets the string to be displayed in the dock’s badging area. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setBadge(text: string): void; /** * Returns the badge string of the dock. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ getBadge(): string; /** * Hides the dock icon. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ hide(): void; /** * Shows the dock icon. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ show(): void; /** * Sets the application dock menu. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setMenu(menu: Menu): void; /** * Sets the image associated with this dock icon. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setIcon(icon: NativeImage | string): void; } @@ -498,9 +502,8 @@ declare namespace Electron { on(event: string, listener: Function): this; /** * Set the url and initialize the auto updater. - * The url cannot be changed once it is set. */ - setFeedURL(url: string): void; + setFeedURL(url: string, requestHeaders?: Headers): void; /** * Ask the server whether there is an update, you have to call setFeedURL * before using this API @@ -559,6 +562,10 @@ declare namespace Electron { * Emitted when the window is hidden. */ on(event: 'hide', listener: Function): this; + /** + * Emitted when the web page has been rendered and window can be displayed without visual flash. + */ + on(event: 'ready-to-show', listener: Function): this; /** * Emitted when window is maximized. */ @@ -608,17 +615,17 @@ declare namespace Electron { on(event: 'app-command', listener: (event: Event, command: string) => void): this; /** * Emitted when scroll wheel event phase has begun. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'scroll-touch-begin', listener: Function): this; /** * Emitted when scroll wheel event phase has ended. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'scroll-touch-end', listener: Function): this; /** * Emitted on 3-finger swipe. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'swipe', listener: (event: Event, direction: SwipeDirection) => void): this; on(event: string, listener: Function): this; @@ -643,13 +650,23 @@ declare namespace Electron { * Adds devtools extension located at path. The extension will be remembered * so you only need to call this API once, this API is not for programming use. * @returns The extension's name. + * + * Note: This API cannot be called before the ready event of the app module is emitted. */ static addDevToolsExtension(path: string): string; /** * Remove a devtools extension. * @param name The name of the devtools extension to remove. + * + * Note: This API cannot be called before the ready event of the app module is emitted. */ static removeDevToolsExtension(name: string): void; + /** + * @returns devtools extensions. + * + * Note: This API cannot be called before the ready event of the app module is emitted. + */ + static getDevToolsExtensions(): DevToolsExtensions; /** * The WebContents object this window owns, all web page related events and * operations would be done via it. @@ -702,6 +719,10 @@ declare namespace Electron { * @returns Whether the window is visible to the user. */ isVisible(): boolean; + /** + * @returns Whether the window is a modal window. + */ + isModal(): boolean; /** * Maximizes the window. */ @@ -741,7 +762,7 @@ declare namespace Electron { * not included within the aspect ratio calculations. * This API already takes into account the difference between a window’s size and its content size. * - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setAspectRatio(aspectRatio: number, extraSize?: Dimension): void; /** @@ -794,31 +815,31 @@ declare namespace Electron { isResizable(): boolean; /** * Sets whether the window can be moved by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setMovable(movable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be moved by user. On Linux always returns true. */ isMovable(): boolean; /** * Sets whether the window can be manually minimized by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setMinimizable(minimizable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be manually minimized by user. On Linux always returns true. */ isMinimizable(): boolean; /** * Sets whether the window can be manually maximized by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setMaximizable(maximizable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be manually maximized by user. On Linux always returns true. */ isMaximizable(): boolean; @@ -832,11 +853,11 @@ declare namespace Electron { isFullScreenable(): boolean; /** * Sets whether the window can be manually closed by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setClosable(closable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be manually closed by user. On Linux always returns true. */ isClosable(): boolean; @@ -872,8 +893,8 @@ declare namespace Electron { */ getTitle(): string; /** - * Changes the attachment point for sheets on Mac OS X. - * Note: This API is available only on OS X. + * Changes the attachment point for sheets on macOS. + * Note: This API is available only on macOS. */ setSheetOffset(offsetY: number, offsetX?: number): void; /** @@ -893,7 +914,7 @@ declare namespace Electron { */ isKiosk(): boolean; /** - * The native type of the handle is HWND on Windows, NSView* on OS X, + * The native type of the handle is HWND on Windows, NSView* on macOS, * and Window (unsigned long) on Linux. * @returns The platform-specific handle of the window as Buffer. */ @@ -918,22 +939,22 @@ declare namespace Electron { /** * Sets the pathname of the file the window represents, and the icon of the * file will show in window's title bar. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setRepresentedFilename(filename: string): void; /** - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. * @returns The pathname of the file the window represents. */ getRepresentedFilename(): string; /** * Specifies whether the window’s document has been edited, and the icon in * title bar will become grey when set to true. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setDocumentEdited(edited: boolean): void; /** - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. * @returns Whether the window's document has been edited. */ isDocumentEdited(): boolean; @@ -958,7 +979,7 @@ declare namespace Electron { reload(): void; /** * Sets the menu as the window top menu. - * Note: This API is not available on OS X. + * Note: This API is not available on macOS. */ setMenu(menu: Menu): void; /** @@ -981,11 +1002,11 @@ declare namespace Electron { setOverlayIcon(overlay: NativeImage, description: string): void; /** * Sets whether the window should have a shadow. On Windows and Linux does nothing. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setHasShadow(hasShadow: boolean): void; /** - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. * @returns whether the window has a shadow. On Windows and Linux always returns true. */ hasShadow(): boolean; @@ -996,13 +1017,13 @@ declare namespace Electron { */ setThumbarButtons(buttons: ThumbarButton[]): boolean; /** - * Shows pop-up dictionary that searches the selected word on the page. - * Note: This API is available only on OS X. + * Same as webContents.showDefinitionForSelection(). + * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; /** * Changes window icon. - * Note: This API is not available on OS X. + * Note: This API is not available on macOS. */ setIcon(icon: NativeImage): void; /** @@ -1042,6 +1063,25 @@ declare namespace Electron { * but if this window has focus, it will still receive keyboard events. */ setIgnoreMouseEvents(ignore: boolean): void; + /** + * Changes whether the window can be focused. + * Note: This API is available only on Windows. + */ + setFocusable(focusable: boolean): void; + /** + * Sets parent as current window's parent window, + * passing null will turn current window into a top-level window. + * Note: This API is not available on Windows. + */ + setParentWindow(parent: BrowserWindow): void; + /** + * @returns The parent window. + */ + getParentWindow(): BrowserWindow; + /** + * @returns All child windows. + */ + getChildWindows(): BrowserWindow[]; } type SwipeDirection = 'up' | 'right' | 'down' | 'left'; @@ -1055,6 +1095,13 @@ declare namespace Electron { flags?: ThumbarButtonFlags[]; } + interface DevToolsExtensions { + [name: string]: { + name: string; + value: string; + } + } + interface WebPreferences { /** * Whether node integration is enabled. @@ -1153,7 +1200,7 @@ declare namespace Electron { */ directWrite?: boolean; /** - * Enables scroll bounce (rubber banding) effect on OS X. + * Enables scroll bounce (rubber banding) effect on macOS. * Default: false. */ scrollBounce?: boolean; @@ -1290,6 +1337,14 @@ declare namespace Electron { * Default: true. */ closable?: boolean; + /** + * Whether the window can be focused. + * On Windows setting focusable: false also implies setting skipTaskbar: true. + * On Linux setting focusable: false makes the window stop interacting with wm, + * so the window will always stay on top in all workspaces. + * Default: true. + */ + focusable?: boolean; /** * Whether the window should always stay on top of other windows. * Default: false. @@ -1297,13 +1352,13 @@ declare namespace Electron { alwaysOnTop?: boolean; /** * Whether the window should show in fullscreen. - * When explicitly set to false the fullscreen button will be hidden or disabled on OS X. + * When explicitly set to false the fullscreen button will be hidden or disabled on macOS. * Default: false. */ fullscreen?: boolean; /** * Whether the window can be put into fullscreen mode. - * On OS X, also whether the maximize/zoom button should toggle full screen mode or maximize window. + * On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. * Default: true. */ fullscreenable?: boolean; @@ -1336,6 +1391,16 @@ declare namespace Electron { * Default: true. */ frame?: boolean; + /** + * Specify parent window. + * Default: null. + */ + parent?: BrowserWindow; + /** + * Whether this is a modal window. This only works when the window is a child window. + * Default: false. + */ + modal?: boolean; /** * Whether the web view accepts a single mouse-down event that simultaneously activates the window. * Default: false. @@ -1363,7 +1428,7 @@ declare namespace Electron { backgroundColor?: string; /** * Whether window should have a shadow. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. * Default: true. */ hasShadow?: boolean; @@ -1589,7 +1654,7 @@ declare namespace Electron { /** * You are required to call this method before using other crashReporter APIs. * - * Note: On OS X, Electron uses a new crashpad client, which is different from breakpad + * Note: On macOS, Electron uses a new crashpad client, which is different from breakpad * on Windows and Linux. To enable the crash collection feature, you are required to call * the crashReporter.start API to initialize crashpad in the main process and in each * renderer process from which you wish to collect crash reports. @@ -1812,7 +1877,7 @@ declare namespace Electron { /** * The value will be returned when user cancels the dialog instead of clicking the buttons of the dialog. * By default it is the index of the buttons that have "cancel" or "no" as label, - * or 0 if there is no such buttons. On OS X and Windows the index of "Cancel" button + * or 0 if there is no such buttons. On macOS and Windows the index of "Cancel" button * will always be used as cancelId, not matter whether it is already specified. */ cancelId?: number; @@ -1832,9 +1897,9 @@ declare namespace Electron { */ interface DownloadItem extends NodeJS.EventEmitter { /** - * Emits when the downloadItem gets updated. + * Emitted when the download has been updated and is not done. */ - on(event: 'updated', listener: Function): this; + on(event: 'updated', listener: (event: Event, state: 'progressing' | 'interrupted') => void): this; /** * Emits when the download is in a terminal state. This includes a completed download, * a cancelled download (via downloadItem.cancel()), and interrupted download that can’t be resumed. @@ -1852,10 +1917,18 @@ declare namespace Electron { * Pauses the download. */ pause(): void; + /** + * @returns Whether the download is paused. + */ + isPaused(): boolean; /** * Resumes the download that has been paused. */ resume(): void; + /** + * @returns Whether the download can resume. + */ + canResume(): boolean; /** * Cancels the download operation. */ @@ -1891,6 +1964,10 @@ declare namespace Electron { * @returns The Content-Disposition field from the response header. */ getContentDisposition(): string; + /** + * @returns The current state. + */ + getState(): 'progressing' | 'completed' | 'cancelled' | 'interrupted'; } // https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md @@ -2041,8 +2118,8 @@ declare namespace Electron { } type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; - type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close'; - type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'window' | 'help' | 'services'; + type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen'; + type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services'; interface MenuItemOptions { /** @@ -2065,13 +2142,13 @@ declare namespace Electron { * * Platform notice: * On Linux and Windows, the Command key would not have any effect, - * you can use CommandOrControl which represents Command on OS X and Control on + * you can use CommandOrControl which represents Command on macOS and Control on * Linux and Windows to define some accelerators. * - * Use Alt instead of Option. The Option key only exists on OS X, whereas + * Use Alt instead of Option. The Option key only exists on macOS, whereas * the Alt key is available on all platforms. * - * The Super key is mapped to the Windows key on Windows and Linux and Cmd on OS X. + * The Super key is mapped to the Windows key on Windows and Linux and Cmd on macOS. * * Available modifiers: * Command (or Cmd for short) @@ -2157,16 +2234,20 @@ declare namespace Electron { */ constructor(); /** - * Sets menu as the application menu on OS X. On Windows and Linux, the menu + * Sets menu as the application menu on macOS. On Windows and Linux, the menu * will be set as each window's top menu. */ static setApplicationMenu(menu: Menu): void; + /** + * @returns The application menu if set, or null if not set. + */ + static getApplicationMenu(): Menu; /** * Sends the action to the first responder of application. * This is used for emulating default Cocoa menu behaviors, * usually you would just use the role property of MenuItem. * - * Note: This method is OS X only. + * Note: This method is macOS only. */ static sendActionToFirstResponder(action: string): void; /** @@ -2176,7 +2257,7 @@ declare namespace Electron { */ static buildFromTemplate(template: MenuItemOptions[]): Menu; /** - * Popups this menu as a context menu in the browserWindow. You can optionally + * Pops up this menu as a context menu in the browserWindow. You can optionally * provide a (x,y) coordinate to place the menu at, otherwise it will be placed * at the current mouse cursor position. * @param x Horizontal coordinate where the menu will be placed. @@ -2233,8 +2314,8 @@ declare namespace Electron { */ toDataURL(): string; /** - * The native type of the handle is NSImage* on OS X. - * Note: This is only implemented on OS X. + * The native type of the handle is NSImage* on macOS. + * Note: This is only implemented on macOS. * @returns The platform-specific handle of the image as Buffer. */ getNativeHandle(): Buffer; @@ -2635,6 +2716,10 @@ declare namespace Electron { * The webRequest API set allows to intercept and modify contents of a request at various stages of its lifetime. */ webRequest: WebRequest; + /** + * @returns An instance of protocol module for this session. + */ + protocol: Protocol; } type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; @@ -3025,26 +3110,34 @@ declare namespace Electron { /** * @returns If the system is in Dark Mode. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ isDarkMode(): boolean; /** - * Subscribes to native notifications of OS X, callback will be called when the corresponding event happens. + * Subscribes to native notifications of macOS, callback will be called when the corresponding event happens. * The id of the subscriber is returned, which can be used to unsubscribe the event. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ subscribeNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; /** * Removes the subscriber with id. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ unsubscribeNotification(id: number): void; + /** + * Same as subscribeNotification, but uses NSNotificationCenter for local defaults. + */ + subscribeLocalNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; + /** + * Same as unsubscribeNotification, but removes the subscriber from NSNotificationCenter. + */ + unsubscribeLocalNotification(id: number): void; /** * Get the value of key in system preferences. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any; /** @@ -3065,17 +3158,17 @@ declare namespace Electron { interface Tray extends NodeJS.EventEmitter { /** * Emitted when the tray icon is clicked. - * Note: The bounds payload is only implemented on OS X and Windows. + * Note: The bounds payload is only implemented on macOS and Windows. */ on(event: 'click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; /** * Emitted when the tray icon is right clicked. - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; /** * Emitted when the tray icon is double clicked. - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; /** @@ -3095,27 +3188,27 @@ declare namespace Electron { on(event: 'balloon-closed', listener: Function): this; /** * Emitted when any dragged items are dropped on the tray icon. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'drop', listener: Function): this; /** * Emitted when dragged files are dropped in the tray icon. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drop-files', listener: (event: Event, files: string[]) => void): this; /** * Emitted when a drag operation enters the tray icon. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drag-enter', listener: Function): this; /** * Emitted when a drag operation exits the tray icon. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drag-leave', listener: Function): this; /** * Emitted when a drag operation ends on the tray or ends at another location. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drag-end', listener: Function): this; on(event: string, listener: Function): this; @@ -3141,12 +3234,12 @@ declare namespace Electron { setToolTip(toolTip: string): void; /** * Sets the title displayed aside of the tray icon in the status bar. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ setTitle(title: string): void; /** * Sets whether the tray icon is highlighted when it is clicked. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ setHighlightMode(highlight: boolean): void; /** @@ -3159,16 +3252,20 @@ declare namespace Electron { content?: string; }): void; /** - * Popups the context menu of tray icon. When menu is passed, + * Pops up the context menu of tray icon. When menu is passed, * the menu will showed instead of the tray's context menu. * The position is only available on Windows, and it is (0, 0) by default. - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ popUpContextMenu(menu?: Menu, position?: Point): void; /** * Sets the context menu for this icon. */ setContextMenu(menu: Menu): void; + /** + * @returns The bounds of this tray icon. + */ + getBounds(): Bounds; } interface Modifiers { @@ -3643,6 +3740,11 @@ declare namespace Electron { * @returns If the process of saving page has been initiated successfully. */ savePage(fullPath: string, saveType: 'HTMLOnly' | 'HTMLComplete' | 'MHTML', callback?: (eror: Error) => void): boolean; + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on macOS. + */ + showDefinitionForSelection(): void; /** * @returns The unique ID of this WebContents. */ @@ -3669,11 +3771,11 @@ declare namespace Electron { interface ContextMenuParams { /** - * x coodinate + * x coordinate */ x: number; /** - * y coodinate + * y coordinate */ y: number; /** @@ -4428,6 +4530,11 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on macOS. + */ + showDefinitionForSelection(): void; /** * @returns The WebContents associated with this webview. */ @@ -4816,7 +4923,7 @@ declare namespace NodeJS { * Sets the file descriptor soft limit to maxDescriptors or the OS hard limit, * whichever is lower for the current process. * - * Note: This API is only available on Mac and Linux. + * Note: This API is only available on macOS and Linux. */ setFdLimit(maxDescriptors: number): void; /** diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 8eeec964eb..d3bf7997d5 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -1,28 +1,330 @@ -// Type definitions for Globalize +// Type definitions for Globalize // Project: https://github.com/jquery/globalize -// Definitions by: Aram Taieb -// Definitions: https://github.com/afromogli/DefinitelyTyped +// Definitions by: Grégoire Castre , Aram Taieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Note: You'll need the cldr.js definition file to use the globalize (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cldr.js) -interface NumberFormatterOptions { - minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - round?: string; - useGrouping?: boolean; +/// + +interface DateFormatterOptions { + /** + * String value indicating a skeleton (see description above), eg. { skeleton: "GyMMMd" }. + * Skeleton provides a more flexible formatting mechanism than the predefined list full, long, medium, or short represented by date, time, or datetime. + * Instead, they are an open-ended list of patterns containing only date field information, and in a canonical order. + */ + skeleton?: string; + /** + * One of the following String values: full, long, medium, or short, eg. { date: "full" }. + */ + date?: "full" | "long" | "medium" | "short"; + /** + * One of the following String values: full, long, medium, or short, eg. { time: "full" }. + */ + time?: "full" | "long" | "medium" | "short"; + /** + * One of the following String values: full, long, medium, or short, eg. { datetime: "full" } + */ + datetime?: "full" | "long" | "medium" | "short"; + /** + * String value indicating a machine raw pattern (anything in the "Sym." column) eg. { raw: "dd/mm" }. + * Note this is NOT recommended for i18n in general. Use skeleton instead. + */ + raw?: string; } -interface Cldr { - /* TODO: add typings */ +interface CommonNumberFormatterOptions { + /** + * Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + */ + minimumIntegerDigits?: number; + /** + * Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. + * Numbers will be rounded or padded with trailing zeroes if necessary. + * Either one or both of these properties must be present. + * If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + */ + minimumFractionDigits?: number; + /** + * Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. + * Numbers will be rounded or padded with trailing zeroes if necessary. + * Either one or both of these properties must be present. + * If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + */ + maximumFractionDigits?: number; + /** + * Positive integer Number values indicating the minimum and maximum fraction digits to be shown. + * Either none or both of these properties are present + * If they are, they override minimum and maximum integer and fraction digits. + * The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + */ + minimumSignificantDigits?: number; + /** + * Positive integer Number values indicating the minimum and maximum fraction digits to be shown. + * Either none or both of these properties are present. + * If they are, they override minimum and maximum integer and fraction digits. + * The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + */ + maximumSignificantDigits?: number; + /** + * String with rounding method ceil, floor, round (default), or truncate. + */ + round?: "ceil" | "floor" | "round" | "truncate"; + /** + * Boolean (default is true) value indicating whether a grouping separator should be used. + */ + useGrouping?: boolean; +} + +interface NumberFormatterOptions extends CommonNumberFormatterOptions { + /** + * decimal (default), or percent + */ + style?: "decimal" | "percent"; +} + +interface CurrencyFormatterOptions extends CommonNumberFormatterOptions { + /** + * symbol (default), accounting, code or name. + */ + style?: "symbol" | "accounting" | "code" | "name"; +} + +interface NumberParserOptions { + /** + * decimal (default), or percent. + */ + style?: "decimal" | "percent"; +} + +interface PluralGeneratorOptions { + /** + * cardinal (default), or ordinal. + */ + type?: "cardinal" | "ordinal"; +} + +interface RelativeTimeFormatterOptions { + /** + * eg. "short" or "narrow". Or falsy for default long form + */ + form?: "short" | "narrow"; +} + +interface UnitFormatterOptions { + /** + * form: [String] eg. "long", "short" or "narrow". + */ + form?: "long" | "short" | "narrow"; + + /** + * numberFormatter: [Function] a number formatter function. Defaults to Globalize .numberFormatter() for the current locale using the default options. + */ + numberFormatter?: NumberFormatterOptions; } interface GlobalizeStatic { - load(jsonData: any): void; - locale(locale: string): Cldr; - numberFormatter(options?: NumberFormatterOptions): (value: number) => string; - formatNumber(value:number, options?: NumberFormatterOptions): string; + cldr: cldr.CldrStatic; + + /** + * Globalize.load( json, ... ) + * @param {Object} [JSON] + * Load resolved or unresolved cldr data. + * Somewhat equivalent to previous Globalize.addCultureInfo(...). + */ + load(json: Object): void; + + /** + * Globalize.locale() + * Return the default Cldr instance. + */ + locale(): cldr.CldrStatic; + + /** + * Globalize.locale( [locale] ) + * @param {string} locale + * Set default Cldr instance + * Return the default Cldr instance. + */ + + locale(locale: string): cldr.CldrStatic; + /** + * Globalize.locale( cldr ) + * @param {Cldr} cldr [Cldr instance] + * Set default Cldr instance + * Return the default Cldr instance. + */ + locale(cldr: cldr.CldrStatic): cldr.CldrStatic; + + /** + * .dateFormatter( options ) + * @param {DateFormatterOptions} options see date/expand_pattern for more info. + * @returns {Function} Return a function that formats a date according to the given `options` and the default/instance locale. + */ + dateFormatter(options?: DateFormatterOptions): (value: Date) => string; + + //Return a function that parses a string representing a date into a JavaScript Date object according to the given options. The default parsing assumes numeric year, month, and day (i.e., { skeleton: "yMd" }). + dateParser(options?: DateFormatterOptions): (value: string) => Date; + + //Alias for .dateFormatter( [options] )( value ). + formatDate(value: Date, options?: DateFormatterOptions): string; + /** + * Alias for .dateParser( [options] )( value ). + * @param {string} value The object whose module id you wish to determine. + * @param {DateFormatterOptions} options The object whose module id you wish to determine. + * @returns {Date} Return the value as a Date. + */ + parseDate(value: string, options?: DateFormatterOptions): Date; + + /** + * Load messages data. + * @param {Object} json JSON object of messages data. Keys can use any character, except /, { and }. Values (i.e., the message content itself) can contain any character. + * @returns {void} + */ + loadMessages(json: Object): void; + /** + * Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections. + * @param path String or Array containing the path of the message content, eg. "greetings/bye", or [ "greetings", "bye" ]. + * @returns {Function} Return A function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections. + */ + messageFormatter(path: string | string[]): (variables?: string | string[] | Object) => string; + + /** + * Formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string + * @param path String or Array containing the path of the message content, eg. "greetings/bye", or [ "greetings", "bye" ]. + * @param variables Variables can be Objects, where each property can be referenced by name inside a message; or Arrays, where each entry of the Array can be used inside a message, using numeric indices. When passing one or more arguments of other types, they're converted to an Array and used as such. + * @returns {string} Return a user-readable string. + */ + formatMessage(path: string | string[], variables?: string | string[] | Object): string + + /** + * Return a function that formats a number according to the given options or locale's defaults. + * @param {NumberFormatterOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + * round Optional String with rounding method ceil, floor, round (default), or truncate. + * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used. + * @returns {Function} Return a function that formats a number according to the given options. + */ + numberFormatter(options?: NumberFormatterOptions): (value: number) => string; + + /** + * Return a function that parses a string representing a number according to the given options or locale's defaults. + * @param {NumberParserOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * @returns {Function} Return a function that parses a String representing a number according to the given options. If value is invalid, NaN is returned. + */ + numberParser(options?: NumberParserOptions): (value: string) => number + + /** + * Return a number formatted according to the given options or locale's defaults. + * @param {number} value The number to format + * @param {NumberFormatterOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + * round Optional String with rounding method ceil, floor, round (default), or truncate. + * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used. + * @returns {string} Return the number formatted + */ + formatNumber(value: number, options?: NumberFormatterOptions): string; + + /** + * A function that parses a string representing a number according to the given options or locale's defaults. + * @param {string} value The number as string to parse + * @param {NumberParserOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * @returns {number} Return a number according to the given options. If value is invalid, NaN is returned. + */ + parseNumber(value: string, options?: NumberParserOptions): number; + + /** + * Return a function that formats a currency according to the given options or locale's defaults. + * The returned function is invoked with one argument: the Number value to be formatted. + * @param {string} currency 3-letter currency code as defined by ISO 4217, eg. USD. + * @param {CurrencyFormatterOptions} options A JSON object including none or any of the following options. + * @returns {Function} Return a function that formats a currency + */ + currencyFormatter(currency: string, options?: CurrencyFormatterOptions): (value: number) => string; + + /** + * Return a currency formatted according to the given options or locale's defaults. + * @param {number} value The value to format. + * @param {string} currency 3-letter currency code as defined by ISO 4217, eg. USD. + * @param {CurrencyFormatterOptions} options A JSON object including none or any of the following options. + * @returns {string} Return a string formatted in the currency according to the value and the options + */ + formatCurrency(value: number, currency: string, options?: CurrencyFormatterOptions): string; + + /** + * Return a function that returns the value's corresponding plural group: zero, one, two, few, many, or other. + * The returned function is invoked with one argument: the Number value for which to return the plural group. + * @param {PluralGeneratorOptions} options A JSON object including none or any of the following options. + * type Optional String cardinal (default), or ordinal. + * @returns {Function} Return a function that returns the value's corresponding plural group: zero, one, two, few, many, or other. + */ + pluralGenerator(options?: PluralGeneratorOptions): (value: number) => string; + + /** + * Returns the value's corresponding plural group: zero, one, two, few, many, or other. + * @param {number} value A Number for which to return the plural group. + * @param {PluralGeneratorOptions} options A JSON object including none or any of the following options. + * type Optional String cardinal (default), or ordinal. + * @returns {string} Returns the value's corresponding plural group: zero, one, two, few, many, or other. + */ + plural(value: number, options?: PluralGeneratorOptions): string; + + /** + * Returns a function that formats a relative time according to the given unit, options, and the default/instance locale. + * The returned function is invoked with one argument: the number value to be formatted. + * @param unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. + * @param options form: [String] eg. "short" or "narrow". Or falsy for default long form. + * @returns {Function} Returns a function that formats a relative time according to the given unit. + */ + relativeTimeFormatter(unit: string, options?: RelativeTimeFormatterOptions): (value: number) => string; + + /** + * Return a relative time according to the given unit + * @param {number} value The number to be formatted. + * @param {string} unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. + * @param options form: [String] eg. "short" or "narrow". Or falsy for default long form. + * @returns {string} Return a relative time according to the given unit. + */ + formatRelativeTime(value: number, unit: string, options?: RelativeTimeFormatterOptions): string; + + /** + * Returns a function that formats a unit according to the given unit, options, and the default/instance locale. + * The returned function is invoked with one argument: the number value to be formatted. + * @param unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour" + * @param options form: [String] eg. "long", "short" or "narrow". + * @returns {Function} Returns a function that formats a unit according to the given unit, options, and the default/instance locale. + */ + unitFormatter(unit: string, options?: UnitFormatterOptions): (value: number) => string; + + /** + * Alias for .unitFormatter( unit, options )( value ). + * @param {number} value The number to be formatted. + * @param {string} unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour" + * @param {UnitFormatterOptions} options form: [String] eg. "long", "short" or "narrow". + * @returns {string} Returns the unit formatted. + */ + formatUnit(value: number, unit: string, options?: UnitFormatterOptions): string + + /** + * Create a Globalize instance. + * @param {string} Locale string of the instance. + * @returns {Globalize} A Globalize instance + */ + new (locale: string): GlobalizeStatic; + /** + * Create a Globalize instance. + * @param cldr Cldr instance of the instance. + * @returns {Globalize} A Globalize instance + */ + new (cldr: cldr.CldrStatic): GlobalizeStatic; } declare var Globalize: GlobalizeStatic; diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 4d225779ce..f005582cb2 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1585,6 +1585,10 @@ declare namespace google.maps { setZoom(zoom: number): void; } + export interface FullscreenControlOptions { + position?: ControlPosition; + } + export interface StreetViewPanoramaOptions { addressControl?: boolean; addressControlOptions?: StreetViewAddressControlOptions; @@ -1592,8 +1596,11 @@ declare namespace google.maps { disableDefaultUi?: boolean; disableDoubleClickZoom?: boolean; enableCloseButton?: boolean; + fullscreenControl?: boolean; + fullscreenControlOptions?: FullscreenControlOptions; imageDateControl?: boolean; linksControl?: boolean; + mode?: "html4" | "html5" |"webgl"; panControl?: boolean; panControlOptions?: PanControlOptions; pano?: string; diff --git a/hammerjs/hammerjs.d.ts b/hammerjs/hammerjs.d.ts index 80487c134c..bfc6e7cb4f 100644 --- a/hammerjs/hammerjs.d.ts +++ b/hammerjs/hammerjs.d.ts @@ -39,7 +39,7 @@ interface HammerStatic DIRECTION_VERTICAL: number; DIRECTION_ALL: number; - Manager: HammerManager; + Manager: HammerManagerConstructor; Input: HammerInput; TouchAction: TouchAction; @@ -95,10 +95,12 @@ interface HammerOptions extends HammerDefaults } +interface HammerManagerConstructor { + new( element:HTMLElement, options?:any ):HammerManager; +} + interface HammerManager { - new( element:HTMLElement, options?:any ):HammerManager; - add( recogniser:Recognizer ):Recognizer; add( recogniser:Recognizer ):HammerManager; add( recogniser:Recognizer[] ):Recognizer; diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 3a0bd2ba08..7cd14fc214 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -77,8 +77,9 @@ interface HeatmapConfiguration { /* * The property name of the value/weight in a datapoint + * Default value: 'value' */ - valueField: string; + valueField?: string; } /* diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index c7584f4e0d..45f69a0bda 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -4954,7 +4954,7 @@ interface HighchartsDataPoint { * The inner radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. * @since 4.1.6 */ - innerRadius?: number; + innerRadius?: number|string; /** * When this property is true, the points acts as a summary column for the values added or substracted since the * last intermediate sum, or since the start of the series. The y value is ignored. @@ -5005,7 +5005,7 @@ interface HighchartsDataPoint { * The outer radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. * @since 4.1.6 */ - radius?: number; + radius?: number|string; /** * Whether the data point is selected initially. * @default false diff --git a/imagemapster/imagemapster-tests.ts b/imagemapster/imagemapster-tests.ts new file mode 100644 index 0000000000..7f9ec9d761 --- /dev/null +++ b/imagemapster/imagemapster-tests.ts @@ -0,0 +1,88 @@ +/// +/// + +const areaOptions: ImageMapster.AreaRenderingOptions = { + key: "foo", + includeKeys: "foo", + isMask: true, + toolTip: "tooltip", +}; + +const onClickData: ImageMapster.OnClickData = { + listTarget: $(), + key: "foo", + e: $.Event("click"), + selected: true, +} + +const onMouseData: ImageMapster.OnMouseData = { + key: "foo", + selected: true, + e: $.Event("click"), + options: areaOptions, +}; + +const onGetListData: ImageMapster.OnGetListData = { + key: "foo", + value: "foo", + area: [{}], + options: areaOptions, +}; + +const onStateChangeData: ImageMapster.OnStateChangeData = { + key: "foo", + state: "highlight", + selected: true, +}; + +const onShowToolTipData: ImageMapster.OnShowToolTipData = { + toolTip: $(), + key: "foo", + selected: true, + areaOptions, +}; + +const bool = true; + +const options: ImageMapster.Options = { + mapKey: "foo", + mapValue: "foo", + clickNavigate: true, + listKey: "foo", + listSelectedAttribute: "foo", + listSelectedClass: "foo", + wrapClass: "foo", + wrapCss: "foo", + mouseoutDelay: 123, + sortList: "asc", + configTimeout: 123, + scaleMap: true, + noHrefIsMask: true, + boundList: $(), + showToolTip: true, + toolTipContainer: $(), + toolTipClose: ["area-mouseout", "area-click", "tooltip-click", "image-mouseout"], + onClick: onClickData => {}, + onMouseover: onMouseData => {}, + onMouseout: onMouseData => {}, + onGetList: onGetListData => $(), + onConfigured: bool => {}, + onStateChange: onStateChangeData => {}, + onShowToolTip: onShowToolTipData => {}, +}; + +$("img").mapster(options) +$("img").mapster("select") +$("img").mapster("deselect") +$("img").mapster("set", true, options) +$("img").mapster("get", "foo") +$("img").mapster("highlight", true) +$("img").mapster("unbind", true) +$("img").mapster("snapshot") +$("img").mapster("rebind", options) +$("img").mapster("resize", 123, 123, 123) +$("img").mapster("keys", "foo", true) +$("img").mapster("keys", true) +$("img").mapster("set_options", options) +$("img").mapster("get_options", "foo", true) +$("img").mapster("tooltip", "foo"); diff --git a/imagemapster/imagemapster.d.ts b/imagemapster/imagemapster.d.ts new file mode 100644 index 0000000000..ad9eed3066 --- /dev/null +++ b/imagemapster/imagemapster.d.ts @@ -0,0 +1,996 @@ +// Type definitions for imagemapster 1.2.10 +// Project: http://www.outsharked.com/imagemapster/ +// Definitions by: delphinus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ImageMapster { + + type Select = "select"; + type Deselect = "deselect"; + type Set = "set"; + type Get = "get"; + type Highlight = "highlight"; + type Unbind = "unbind"; + type Resize = "resize"; + type Snapshot = "snapshot"; + type Rebind = "rebind"; + type Keys = "keys"; + type SetOptions = "set_options"; + type GetOptions = "get_options"; + type Tooltip = "tooltip"; + type ToolTipCloseEvent = "area-mouseout" | "area-click" | "tooltip-click" | "image-mouseout"; + type State = "highlight" | "select"; + + interface RenderingOptions { + + /** + * fade effect - can only be applied to "render_highlight". + * + * Use a fade effect when highlighting areas on mouseover. + */ + fade?: boolean; + + /** + * The duration of the fade-in effect, in milliseconds. + */ + fadeDuration?: number; + + /** + * highlight areas on mouseover. When null (default), the behavior is + * disabled for mobile browsers. You can explicitly enable or disable + * it by setting this option to a boolean value. + */ + highlight?: boolean; + + /** + * the map or an area on the map can be selected (or deselected). + * + * When true, the image map will function like a multiple-select menu. + * Users can click any area to select or deselect it. When applied to + * the entire map, it determines whether or not the click-selection + * functionality is enabled. When applied to an area, it determines + * whether that individual area (or group) can be selected. By default, + * the map and all areas are selectable. + */ + isSelectable?: boolean; + + /** + * the map or area on the map can be deselected. + * + * Normally true, this option can be used to prevent users from + * unselecting items once they have been selected. When combined with + * singleSelect, the effect is that one and only one option can be + * selected at any given time. Users cannot deselect the active option. + * This provides a menu-like functionality. It is possible for zero + * items to be selected if this is the default state (or the only + * selected item is deselected programatically). + */ + isDeselectable?: boolean; + + /** + * only one area can be selected at a time + * + * When true, only one or zero areas can be selected at any given time. + * If an area is selected and the user selects another area, the + * previously selected area will become deselected. Unlike + * "staticState", this property cannot be overridden by setting areas + * programatically, only one (or zero) areas can ever be selected when + * this option is true. + */ + singleSelect?: boolean; + + /** + * the map or area is permanently in a selected or deselected state. + * + * When true or false, the map or area to which this option applies + * will be permanently selected or deselected. Typically this is more + * useful applied to individual areas that you want to exclude from the + * interactive part of the map. + * + * staticState forces an area to be always selected or deselected. If + * set, this will supercede isSelectable. Something with a staticState + * will always be in that state and it cannot be changed by the user. + * Note that when setting states programatically, this option will not + * be honored; it only affects user interaction. + */ + staticState?: boolean; + + /** + * initial selection state of an area. + * + * The area in question is selected. To set default selections when + * creating a new mapster, use this option for a specific area (see + * above). + */ + selected?: boolean; + + /** + * Use an alternate image of the same size as the imagemap as the + * source for highlight or select effects. + * + * When specified, the mapster will highlight areas using the image + * data obtained from the same area in an alternate image, instead of + * using a fill effect to highlight or select the area. This feature is + * currently available in browsers with HTML5 canvas support. In + * practical terms, this means it will work in all commonly used + * browsers except IE 8 or lower. + * + * If this feature is enabled when an unsupported browser is used, it + * will fall back to the normal highlight method. + * + * The fill, stroke and opacity effects can be specified independently + * from those used for the normal higlight effect. This ensures that + * when your page is viewed with a non-supported browser, you can still + * control the rendering as would be appropriate for a normal + * fill/stroke effect, which may be different from when you're using an + * alternate image. + */ + altImage?: string; + altImageFill?: boolean; + altImageStroke?: boolean; + altImageOpacity?: number; + + /** + * Areas should be flood-filled when moused over or highlighted. + */ + fill?: boolean; + + /** + * The color used for flood fill. + */ + fillColor?: string; + fillColorMask?: string; + + /** + * The opacity of the fill. This is a number from 0 to 1. + */ + fillOpacity?: number; + + /** + * Areas should be outlined when moused over or highlighted. + */ + stroke?: boolean; + + /** + * The color of the outline. + */ + strokeColor?: string; + + /** + * The opacity of the outline. + */ + strokeOpacity?: number; + + /** + * The width of the outline. + */ + strokeWidth?: number; + + /** + * The options below control the way highlighted areas are rendered. + * Each can be applied globally to the map, or to each element, using + * the areas option to pass area-specific options. These options apply + * to either highlighted or selected areas. Highlighting occurs when + * the mouse enters an area on the image map. Selection occurs when an + * area is clicked, and selection is enabled. These options will be + * applied to both situations if present in the root of the options + * object. They can also be applied to one or the other situations + * specifically using the render_highlight and render_select options. + */ + render_highlight?: string | RenderingOptions; + render_select?: string | RenderingOptions; + } + + interface AreaRenderingOptions extends RenderingOptions { + + key: string; + + /** + * when rendering an area or area group, also render the areas in the + * other group (or groups) specified + * + * This is an area-specific option that allows you to create + * supergroups. A supergroup is a collection of groups that will all be + * highlighted simultaneously, but only when the area that defines the + * supergroup is moused over or activated through code. + * + * When the area for which this option has been set is activated, all + * the areas specified in the includeKeys list will also be rendered. + * This is a one-way relationship. Defining a supergroup in an area + * causes all the other groups to be highlighted, but not the other way + * around. + * + * A typical use of this is to define areas that you want to be + * highlighted when the mouse enters some specific area, but that you + * do not want to be highlighted on their own if the target area is + * moused over. This could be a hidden menu, for example: you want the + * menu to display when the hotspot is moused over, but when it's + * hidden, mousing over the menu area itself should have no effect. + */ + includeKeys?: string; + + /** + * the area is a mask rather than a highlighted area. + * + * Normally, every area in an imagemap is an active area, and would be + * highlighted when moused over (unless its behavior was otherwise + * specified with staticState). The isMask option allows you to + * identify an area as being a mask. When a mask is part of an area + * group, the masked area will be specifically excluded from the + * rendering of a highlight or selected state. + * + * This is usually used in conjunction, or instead of, the nohref + * attribute of the area tag. When nohref is specified on an area tag, + * that area is specifically excluded from the hotspot of any area that + * encompasses it. It will not respond to mouse events, and will not be + * highlighted. This can be used to create "holes" in hotspots. By + * default, ImageMapster will treat any area with nohref or no href tag + * as masks, the same as if this option had been applied. + * + * Sometimes you won't be able to use nohref to identify something as a + * mask, for example, if you intend to re-use an area has both a mask, + * and an independent hotspot. This would be typical if you wanted to a + * selectable area that was completely included within another + * selectable area, but functioned independently, such as concentric + * circles. In this case, you would need to identify the inner circle + * as both a mask, and a hotspot. The nohref attribute would make it + * not act as a hotspot, and only function as a mask. You couldn't also + * select the inner area. You can solve this problem by including the + * inner circle in two different groups - one group which is a mask for + * the main area, and another which is an independent selectable area. + * You can specify different options for each group, so even though + * it's just one area, it can function as two completely independent + * ones. + * + * There may also be situations where you do not want an area marked + * with nohref to be treated as a mask. For example, given "area1" and + * "area2," you may want to create a configuration where mousing over + * "area1" causes both "area1" and "area2" to be highlighted, but + * "area2" should not be highlighted on its own when it is moused over. + * In this situation, you'll need to use "nohref" to prevent the hover + * behavior for the area, but you still want it to be treated normally + * when it's rendered as a result of mousing over "area1." You can + * accomplish this using the noHrefIsMask global option, below. + * + * Generally, masked areas will appear as a window to the underlying + * image. If stroke is in effect, the stroke will be rendered for the + * mask as well as the areas, to create both inner and outer borders. + * You can always specifically enable or disable this, or any other + * effect, for any area as desired. + * + */ + isMask?: boolean; + + /** + * tool tip data for an area + * + * When this area-specific option is present and showToolTips = true, a + * toolTipContainer will be created this will be inserted into it, + * either as inner text (if only text as passed) or as HTML if a jQuery + * object is passed. In order to pass anything other than plain text + * using this option you must use a jQuery object. Any string will be + * treated as plain text (and special characters rendered correctly). + */ + toolTip?: string; + } + + interface OnClickData { + + /** + * $(item) from boundList + */ + listTarget?: JQuery; + + /** + * mapKey for this area + */ + key: string; + + e: JQueryEventObject; + selected: boolean; + } + + interface OnStateChangeData { + + /** + * map key + */ + key: string; + + state: "highlight" | "select"; + + /** + * indicating the current state (following the event) + */ + selected: boolean; + } + + interface OnMouseData { + + /** + * area key + */ + key: string; + + /** + * true if area is currently selected + */ + selected: boolean; + + e: JQueryEventObject; + options: AreaRenderingOptions; + } + + interface OnGetListData { + + /** + * primary mapKey for this area or area group + */ + key: string; + + /** + * mapValue for this area or group + */ + value: string; + + /** + * array of areas that make up this group + */ + area: any[]; + + options: AreaRenderingOptions; + } + + interface OnShowToolTipData { + + /** + * jQuery object of the tooltip container + */ + toolTip: JQuery; + + /** + * map key for this area + */ + key: string; + + /** + * current state of the area + */ + selected: boolean; + + areaOptions: AreaRenderingOptions; + } + + interface Options extends RenderingOptions { + + /** + * an attribute identifying each imagemap area. + * + * If specified, this refers to an attribute on the area tags that will + * be used to group them logically. Any areas containing the same + * mapKey will be considered part of a group, and rendered together + * when any of these areas is activated. If you don't want this + * functionality, ensure each key is unique. When mapKey is omitted, + * then each area is considered to be independent from the other and no + * grouping is applied. + * + * When mapKey is present, any area tags that are missing this + * attribute will be excluded from the image map e ntirely. This is + * functionally identical to setting staticState=false for these areas, + * except they will be inaccessible through the API. + * + * ImageMapster will work with any attribute you identify as a key. If + * you wish to maintain HTML compliance, it's recommeded that you use + * attribute names starting with "data-", for example, data-mapkey. Any + * such names are legal for the HTML5 document type. If you are using + * older document types, the class attribute is part of the HTML spec + * for area and will not cause any visual effects, so this is also a + * good choice. It is not recommended to use id, since the values of + * this attribute must be unique. title and alt also will cause + * possibly undesired side effects. + * + * You can specify more than one value in the mapKey attribute, + * separated by commas. This will cause an area to be a member of more + * than one group. The area may have different options in the context + * of each group. When the area is physically moused over, the first + * key listed will identify the group that's effective for that action. + */ + mapKey?: string; + + /** + * an attribute on each area tag containing additional descriptive + * information about an area. + * + * This option is applicable only when using onGetList. When set, the + * data provided to the callback function will include the value of + * this attribute for each group. This can be used to simplify building + * a list with associated information, without having to match against + * another resource. It also ties this information to the image map + * itself. It is not required to use this option when using onGetList. + * + * For example, you could set mapValue: 'data-statename' to an imagemap + * of the united states, and add an attribute to your areas that + * provided the full name of each state, e.g. data-statename="Alaska". + * This text would be included in the onGetList callback, and so you + * could use it to construct an external list of states. + * + * If there are grouped areas (areas with the same key), then the value + * from the first area found with data in this attribute will be used. + */ + mapValue?: string; + + /** + * Clicking on a link should cause the browser to navigate to the href + * whenever it's not a hash sign (#). Version 1.2.4.050 and later + * + * By default, ImageMapster will prevent the default browser behavior + * in image maps, and "select" areas when they are clicked. If you want + * to navigate to the url for an area, use this option. When enabled, + * all areas that have an href attribute, and its value is not empty or + * "#" (just a hashtag). + * + * When area grouping is used, if an href is present for any area in + * the primary group, this will be used as the navigation target. This + * way you don't need to copy the url for every area in groups, rather, + * you can include it on just one, and clicking any area will cause the + * appropraite navigation. + */ + clickNavigate?: boolean; + + /** + * an attribute on items in a boundList that corresponds to the value + * of the mapKey attributes. + * + * This is used to synchronize the actions on the imagemap with the + * actions on a boundList. Each value should match a value from the + * imageMap mapKey tag. Any item in the boundList with missing or + * mismatched data will be ignored. + */ + listKey?: string; + + /** + * attribute to set or remove when an area is selected or deselected + * + * If boundList is present, when a map area is selected, set or remove + * this attribute on the list element that matches that area based on + * their respective keys. + */ + listSelectedAttribute?: string; + + /** + * a class to add or remove when an area is selected or deselected + * + * If a boundList is present, when a map area is selected, this class + * is added or removed from the corresponding list element. This can be + * used to easily create any kind of associated action when areas on + * the map are changed. + */ + listSelectedClass?: string; + + /** + * + * define area-specific options; each object in the array must contain + * a "key" property identifying a valid mapKey, and additional + * rendering options specific to that area or group + */ + areas?: AreaRenderingOptions[], + + /** + * add "classname" class to the wrapper created around the image, or + * copy classes from the image if "true" + */ + wrapClass?: string | boolean; + + /** + * add CSS to the wrapper created around the image + */ + wrapCss?: string | boolean; + + /** + * delay removing highlight when mouse exits an area (1.2.5b36) + * + * Normally, when the user's mouse pointer exits an area, the highlight + * effect is removed immediately. This behavior can be changed with + * this option. Setting it to a positive number causes a delay of n + * milliseconds before the effect is removed. Setting to -1 causes the + * effect to remain active until another hotspot is entered (e.g., it + * will only be removed when superceded by a different area being + * highlighted). + * + * When using mouseoutDelay, the onMouseover event will still be fired + * at the time the user's mouse pointer leaves the area. However, the + * onStateChange event will be delayed until the highlight is actually + * removed. + * + * Whether or not you are using mouseoutDelay, only one area can be + * highlighted at a time. That is, whenever the mouse pointer moves + * onto a new active area, any previously highlighted area will become + * un-highlighted, regardless of any delay in effect. Hovering over a + * new area will always supercede any delay and cause the new area (and + * only the new area) to be highlighted at that time. So, for dense + * imagemaps where most areas adjoin one another, this option may not + * have much effect within the boundaries of the imagemap. Rather, it + * is intended to help keep the higlights active for imagemaps that are + * sparse, or have very small areas. + */ + mouseoutDelay?: number; + + /** + * sort the values before calling onGetList + * + * If a non-false value or "asc" is passed, the list will be sorted in + * ascending order by the area value from mapValue. If "desc" is + * passed, the list will be sorted in descending order. + */ + sortList?: boolean | "asc" | "desc"; + + /** + * time (in milliseconds) to wait for images to load before giving up + * + * When first bound, ImageMapster has to wait for the source image,and + * any altImage images to load before it can finish binding. This is + * necessary because otherwise it's not alwasy possible to know the + * native size of the images. After this period of time, ImageMapster + * will give up. If you have particularly large pages or images, you + * may want to increase this to account for long load times. + */ + configTimeout?: number; + + /** + * Automatically scale imagemaps to match the size of a + * dynamically-scaled image. + * + * When you render an image, you can optionally define a size through + * CSS or using the "height" and "width" attributes. If omitted, the + * image will be displayed in its native size. If included, browsers + * will automatically resize the image to display in the dimensions you + * have provided. + * + * Starting with 1.1.3, ImageMapster will automatically recalculate all + * area data to match the effective size of the image. This means that + * you can set the size of your image to anything you want and + * ImageMapster will work with no changes at all needed to the "area" + * data. + * + * If this behavior is not desired for some reason, this can be + * disabled by setting this option to false. + */ + scaleMap?: boolean; + + /** + * Treat areas containing the onhref attribute (or missing the href + * attribute) as masks. This is true by default. + * + * Set this to "false" to disable automatic masking of these areas. You + * can control them explicitly by creating independent groups for areas + * you wish to mask and assigning the isMask area-specific option when + * using this option. + * + * There are some things to be aware of when using nohref and masking: + * + * * You must put the area that include the nohref attribute before + * other areas that overlap it, or it will be ignored. + * + * * You should also explicitly omit the href tag when using nohref. + * + * * Due to limitations in rendering with VML (e.g. Internet Explorer + * 6-8), it is not possible to create a true mask, which would allow + * the underlying image to show through the masked area. Instead, the + * "masked" areas are rendered on top of the highlighted area in a + * different color. This can be specified for each area (see the + * fillColorMask option below) to create the best possible effect. + */ + noHrefIsMask?: boolean; + + /** + * a jQuery object whose elements are bound to the map. + * + * boundList can be any list of objects. To be bound to the map, they + * must contain an attribute whose name is identified by the option + * listKey, and whose value matches the value in an area tag's mapKey + * attribute. If more than one element in the list has the same value, + * the action will affect all matching elements. + */ + boundList?: JQuery; + + /** + * enable tooltips + * + * When showToolTip is true, mapster will look for a property called + * toolTip in the areas option for a an area. If present, a tool tip + * dialog will be shown on mouseover for that area. It will + * automatically be closed according to the behavior specified by + * toolTipClose. This option does not apply at the item level, but + * rather enables tooltips for the entire map. At the item level, only + * the presence of tooltip data is necessary for a tooltip to appear. + */ + showToolTip?: boolean; + + /** + * HTML describing the popup that will be created for tooltips. + * + * A div with some simple styling is included as the default tooltip + * container. This can be replaced with anything using this option. + * + * When tooltips are rendered, the code attempts to determine the best + * place for it. It will try to position it in near the top-left part + * of the area, and continue to try other corners in order to render it + * within the confines of the container where the image map resides. If + * it can't be placed within the image, it will be placed in the + * lower-right corner and extend outside the image. + */ + toolTipContainer?: string | JQuery; + + /** + * specify the behavior that causes a toolTip to close. + * + * This option should be passed an array of strings that define the + * events that cause active tooltips to close. The array can include + * one or more of the following stings: + * + * 'area-mouseout' - tooltips close when the mouse pointer leaves the + * area that activated it. This is the default. + * + * 'area-click' - tooltips close when another area (or the same one) is + * clicked + * + * 'tooltip-click' - tooltips close when the tooltip itself is clicked + * anywhere + * + * 'image-mouseout' - tooltips close when the mouse pointer leaves the + * image itself. + * + * Under any circumstances, active tooltip will disappear when a new + * one is created. You don't have to define an automatic closing + * behavior; setting this option to an empty array will result in + * tooltips never closing, leaving it to you to close them manually + * though the tooltip method. + */ + toolTipClose?: ToolTipCloseEvent[]; + + /** + * callback when a hotspot area is clicked. Return false to cancel + * default select action, or true to navigate to the 'href' + */ + + /** + * a callback when an area is clicked.:silent doautocmd FocusLost % + * + * This event occurs when the usual click event happens, but includes + * data from the mapster about the area: + * + * This can be used to perform additional actions on a click without + * binding another event and having to obtain information manually. + */ + onClick?: (data: OnClickData) => void; + + /** + * callback when mouse enters a bound area. + * + * This function is called when the mouse enters a bound area. + */ + onMouseover?: (data: OnMouseData) => void; + + /** + * callback when mouse leavesd a bound area. + * + * Callback when the mouse leaves a bound area. The data structure + * passed to the callback is the same as onMouseover. + */ + onMouseout?: (data: OnMouseData) => void; + + /** + * a callback on mapster initialization that provides summary data + * about the image map, and expects a jQuery list to be returned. + * + * This callback allows you to dynamically provide a boundList based on + * summary data from the imagemap itself, rather than providing the + * list up front. The event passes an array of AreaData objects + * + * The client should return a jQuery object containing all the elements + * that make up the bound list, the same as if it was assigned + * manually. + */ + onGetList?: (data: OnGetListData) => JQuery; + + /** + * a callback when the mapster has finished initial configuration + * + * This event is fired when the mapster configuration completes. When + * control execution continues after a first-time bind operation, the + * mapster is not guaranteed to be configured, because images are + * loaded asynchronously by web browsers. If a mapster is bound to an + * image that is not yet loaded, it will attempt to rebind every 200 + * milliseconds. This event will be fired when it is eventually + * successful, or the length of time specified by configTimeout is + * exceeded (default of ten seconds). + * + * The altImage option will also increase the time needed to configure, + * because the alternate image is loaded by the client at configure + * time to ensure it is available immediately when needed. + */ + onConfigured?: (success: boolean) => void; + + /** + * callback when area state is changed (either highlight or select). + * + * onStateChange can be used to get more specific information than the + * mouseover or click events. + */ + onStateChange?: (data: OnStateChangeData) => void; + + /** + * callback when a toolTip is created + * + * This can be used to control tooltip closing behavior directly, if + * desired. + */ + onShowToolTip?: (data: OnShowToolTipData) => void; + } +} + +interface JQuery { + + /** + * + * All images in the jQuery object will be bound. The specific example + * above will attempt to bind to all images present on the page. Each image + * must be bound to an image map identified with the usemap attribute. If + * there is no usemap attribute, or it does not refer to a valid map, then + * the image will be ignored. Therefore you can use this syntax to activate + * all imagemaps on a page. Because pages often contain many images, + * though, it will be faster to select just the image you are targeting + * using a more specific selector. + * + * Images are often not completely loaded when script execution begins. + * ImageMapster will ensure that all images are loaded before it permits + * interaction from the client. If an alternate image is specified, this + * will also be preloaded. + * + * Because images are loaded asynchronously, code execution will often + * return to your script before the ImageMapster is available. If you apply + * other methods to it (such as selecting or deselecting areas), these + * commands will be queued until the image has been loaded, and then + * executed automatically. So you don't need to worry about using callbacks + * for initial configuration. You can assign a function to a callback when + * configuration is complete if needed to perform other setup activities on + * the page. + */ + mapster(options?: ImageMapster.Options): JQuery; + + /** + * select: Cause an area to become selected. This is similar to a user + * click, but will not cause a click event to be fired. + * + * Programatically select elements from the image map. The programmatic + * selection/deselection methods will not honor the staticState property. + */ + mapster(method: ImageMapster.Select): void; + + /** + * deselect: Cause an area to become deselected + * + * The opposite of select, this causes an area to become deselected. If it + * was not previously selected, nothing changes. + */ + mapster(method: ImageMapster.Deselect): void; + + /** + * set: select or deselect an area + * + * Select or deselect elements from jQuery objects wrapping "area" tags on + * the map based on truthiness of selected. If the area represents a bound + * area on the imagemap, it will be selected or deselected. The method can + * be called from an AREA, or from a bound image, passing a specific key as + * a 2nd parameter + * + * If the selected parameter is omitted (or anything other than "true" or + * "false") then the state of each area will be toggled. + * + * You can include an object containing rendering options as the last + * parameter. When present, these will supercede the default and + * area-specific rendering options. + */ + mapster(method: ImageMapster.Set, selected: boolean, options: ImageMapster.RenderingOptions): JQuery; + mapster(method: ImageMapster.Set, options: ImageMapster.RenderingOptions): JQuery; + + /** + * get: get keys for all selected areas + * + * When no "key" parameter is included, returns a comma-separated list of + * keys representing the areas currently selected. If specified, returns + * true or false indicating whether the area specified is selected. + */ + mapster(method: ImageMapster.Get, key?: string): string | boolean; + + /** + * highlight: highlight, clear, or return highlight state + * + * This method is used to control or obtain the current highlight state. + * Setting the highlight does not mimic a mouseover, rather, it only sets + * the highlight. Events and tooltips will not be activated. Even using + * these methods, it is not possible to highlight more than one area at a + * time. If another area is highlighted programatically, any existing + * highlight will be removed. + * + * Once set this way, the highlight will be removed when any user-event + * that would normally cause a highlight to be removed occurs (e.g. moving + * the mouse into any area), or it is removed programatically. + */ + mapster(method: ImageMapster.Highlight, flag?: string | boolean): void; + + /** + * unbind: unbind ImageMapster from an image + * + * Removes the ImageMapster binding from an image and restores it to its + * original state. All visible elements (selections, tooltips) will be + * removed. + * + * If the optional "preserveState" parameter is true, the selection overlay + * and any active tooltips will be preserved. Tooltips can still be + * dismissed by a user click, but once unbound, the selection states can no + * longer be controlled either by the user or programatically. To remove + * them, the actual DOM elements must be removed. + * + * Notes: When a mapster is first bound, several things happen. A div + * element is created which wraps the image. A copy is made of the original + * image, and the original image is set be transparent. This allows + * creating visible elements for the selections & highlights without + * interfering with the image map. Additionally, canvas elements are + * created (for HTML5 browsers), or a VML elements are created for Internet + * Explorer, to render the effects. Profile information about each bound + * image map is stored in memory, and finally, event handlers are bound to + * the image map. + * + * The "unbind" method cleans up these resources: it removes the wrapper, + * restores the image to its original visibility state, and releases + * internal resources. When using 'preserveState', the internal resources + * are cleaned up and event handling is disabled, but HTML elements are not + * removed. Each element created by ImageMapster is assigned a class of + * "mapster_el", which can be used to target them for later removal, though + * it is not easy to complete this process manually because of the wrapper + * and styles applied during configuration, which will be left intact when + * using "preserveState." + */ + mapster(method: ImageMapster.Unbind, preserveState?: boolean): JQuery; + + /** + * snapshot: take a "snapshot" of the current selection state, and reset + * ImageMapster + * + * This option is similar to unbind with preserveState. After a snapshot, + * any active selections will still appear as they did at the time of the + * snapshot, but they are no longer part of the ImageMapster. This is + * useful for configuring an initial state, or creating complex + * representations that may not be easily accomplished with area + * configuration options. + * + * For example, you could bind in image with a specific set of options; + * programatically select some areas; and take a snapshot; then set new + * options that cause a different rendering mode. This way you could have + * certain areas appear differently from the selection highlight, but be + * "highlighted again" using the new rendering options. Any effects in + * place at the time of the snapshot essentially become part of the image + * and are not affected by future operations. + */ + mapster(method: ImageMapster.Snapshot): JQuery; + + /** + * rebind: rebind ImageMapster with new options + * + * This method is similar to set_options, in that its purpose is to change + * options for an existing bound map. However, unlike set_options rebind + * will immediately apply all the new options to the existing map. This + * means that rendering options will change areas that are already selected + * to be rendered with the new options. If you pass area-specific options, + * these will also be applied, e.g. you could cause new areas to be + * selected by passing selected: true in an area specific options. + * + * set_options, in contrast only changes the options, and does not apply + * them to any existing data. When using set_options the new options only + * apply to future actions. + */ + mapster(method: ImageMapster.Rebind, options: ImageMapster.Options): JQuery; + + /** + * resize: change the size of the image and map + * + * This will resize the image map to the dimensions specified. Note that + * either width or height should be passed, and the other will be + * calculated in the same aspect ratio as the original image. If you pass + * both, only the width will be used to calculate the new dimensions: the + * proportions must remain the same as the original image. (Though I intend + * to allow scaling without constraining proportions, it will be difficult + * to make work for certain shapes -- e.g. circles, which would have to + * become ovals). + * + * This method will recalculate and re-render the entire imagemap, so it + * will work exactly the same under the new sizing scheme. When the image + * is unbound, the imagemap will be restored to its original condition. + * + * When using HTML5 canvases, any existing selections, etc. will be + * preserved during the animation. VML data cannot be resized dynamically, + * however, so in IE<9 the selections will be erased, then redrawn when the + * animation is complete. + */ + mapster(method: ImageMapster.Resize, width: number, height: number, duration?: number): JQuery; + + /** + * keys: get the primary mapKey (or comma-separated list of keys) for an + * area, set of areas, or key group. Version 1.2.4.050 + * + * This method allows you to obtain the primary mapKey (or keys) associated + * with another key, or one or more areas. If the all parameter is true, + * the method returns all keys or groups that include the area. + * + * When using area groups, it is possible for more than one key to be + * associated with a map area. It's also possible for an area to be + * highlighted from code as part of a group, but be inaccessible to the + * end-user. This is because area groups are separate physical entities + * from the areas defined by their primary key. They can have different + * options, and are highlighted independently. Note: the way area groups + * work is not well documented here yet. I am working on a more + * comprehensive tutorial for the site. In the meantime please see this + * example which describes area groups in detail, and shows how they work + * through an active demonstration. + * + * There are reasons you may want to be able to access the primary keys + * that make up an area group directly. Perhaps you want to select a group + * of areas using the options from a group - but not as a separate group. + * Perhaps you want to be able to compare the area clicked against a group + * you have defined to take some action if the area is a member of a + * certain group. This method provides access to that information. + * + * This method allows working with groups in a variety of ways by providing + * access to a complete list of primary keys in any group, or all keys + * which contain a given primary key. + */ + mapster(method: ImageMapster.Keys, key: string, all?: boolean): string | string[]; + mapster(method: ImageMapster.Keys, all: boolean): string | string[]; + + /** + * set_options: set active options + * + * When called without the "options" parameter, returns an object with all + * active options. When the parameter is included, the active options are + * updated for the imagemap, and any area options are merged with existing + * area options. Unlike "rebind", this will not rebind or reapply any + * options, but only update the state. This may affect future actions, but + * it will not change any existing state information. + */ + mapster(method: ImageMapster.SetOptions, options?: ImageMapster.Options): JQuery; + + /** + * get_options: get active options + * + * When called with no parameters, returns the options that the mapster was + * configured using. When called with a single key it returns the + * area-specific options assigned to that area. The final parameter + * effective determines whether the actual options in effect for this area, + * or the specific options assigned are returned. + * + * Areas inherit the global options assigned, but can be overridden by + * area-specific options. The "effective" options contain all options + * including those that are inherited, as well as any specifically assigned + * to the area. + */ + mapster(method: ImageMapster.GetOptions, key?: string, effective?: boolean): ImageMapster.Options | ImageMapster.AreaRenderingOptions; + + /** + * tooltip: show/hide tooltips from code + * + * See the tooltip options section below for options to control how + * tooltips appear and are dismissed. + * + * This method can be used to manipulate tooltips from code. If the global + * showToolTip option is false, these methods will still work, so you have + * the ability to control tooltips bound to areas completely using your own + * logic, if desired. These methods can also be used to have better control + * over events needed to close the tooltip, e.g. you could have no tooltip + * closing event, but add a "close" button to your contianer that will + * cause the tooltip to close when clicked. + */ + mapster(method: ImageMapster.Tooltip, key?: string): JQuery; +} diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts new file mode 100644 index 0000000000..9b0dff520e --- /dev/null +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -0,0 +1,159 @@ +/// + +import { inject, Kernel } from "inversify"; +import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; + +module decorator { + let kernel = new Kernel(); + let provide = makeProvideDecorator(kernel); + + interface INinja { + fight(): string; + sneak(): string; + } + + interface IKatana { + hit(): string; + } + + interface IShuriken { + throw(): string; + } + + let TYPE = { + IKatana: "IKatana", + INinja: "INinja", + IShuriken: "IShuriken" + }; + + @provide(TYPE.IKatana) + class Katana implements IKatana { + public hit() { + return "cut!"; + } + } + + @provide(TYPE.IShuriken) + class Shuriken implements IShuriken { + public throw() { + return "hit!"; + } + } + + @provide(TYPE.INinja) + class Ninja implements INinja { + + private _katana: IKatana; + private _shuriken: IShuriken; + + public constructor( + @inject("IKatana") katana: IKatana, + @inject("IShuriken") shuriken: IShuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let ninja = kernel.get(TYPE.INinja); + console.log(ninja); + +} + +module fluent_decorator { + let kernel = new Kernel(); + let provide = makeFluentProvideDecorator(kernel); + + let provideSingleton = function(identifier: string) { + return provide(identifier).inSingletonScope().done(); + }; + + let provideTransient = function(identifier: string) { + return provide(identifier).done(); + }; + + interface INinja { + fight(): string; + sneak(): string; + } + + interface IKatana { + hit(): string; + } + + interface IShuriken { + throw(): string; + } + + let TYPE = { + IKatana: "IKatana", + INinja: "INinja", + IShuriken: "IShuriken" + }; + + @provideSingleton(TYPE.IKatana) + class Katana implements IKatana { + private _mark: any; + public constructor() { + this._mark = Math.random(); + } + public hit() { + return "cut! " + this._mark; + } + } + + @provideTransient(TYPE.IShuriken) + class Shuriken implements IShuriken { + private _mark: any; + public constructor() { + this._mark = Math.random(); + } + public throw() { + return "hit! " + this._mark; + } + } + + @provideTransient(TYPE.INinja) + class Ninja implements INinja { + + private _katana: IKatana; + private _shuriken: IShuriken; + + public constructor( + @inject("IKatana") katana: IKatana, + @inject("IShuriken") shuriken: IShuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let ninja = kernel.get(TYPE.INinja); + console.log(ninja); + +} + +module auto_provide { + + let warriors = { + Ninja: class Ninja {}, + Samurai: class Samurai {} + }; + + let weapons = { + Katana: class Katana {}, + Shuriken: class Shuriken {}, + }; + + let kernel = new Kernel(); + autoProvide(kernel, warriors, weapons); + +} diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts new file mode 100644 index 0000000000..623b6c32c7 --- /dev/null +++ b/inversify-binding-decorators/inversify-binding-decorators.d.ts @@ -0,0 +1,55 @@ +// Type definitions for inversify 1.0.0-beta.5 +// Project: https://github.com/inversify/inversify-binding-decorators +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare namespace inversifyBindingDecorators { + + interface IProvideInSyntax extends IProvideDoneSyntax { + inSingletonScope(): IProvideWhenOnSyntax; + } + + interface IProvideDoneSyntax { + done(): (target: any) => any; + } + + interface IProvideOnSyntax extends IProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; + } + + interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + + interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + + interface IProvideWhenSyntax extends IProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + whenTargetNamed(name: string): IProvideOnSyntax; + whenTargetTagged(tag: string, value: any): IProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; + whenParentNamed(name: string): IProvideOnSyntax; + whenParentTagged(tag: string, value: any): IProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; + whenAnyAncestorNamed(name: string): IProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; + whenNoAncestorNamed(name: string): IProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + } + + export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; + + export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): + (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + + export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): + (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; + +} + +declare module "inversify-binding-decorators" { + export = inversifyBindingDecorators; +} diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts new file mode 100644 index 0000000000..1d421e397a --- /dev/null +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -0,0 +1,89 @@ +/// + +import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils"; +import * as express from "express"; +import { Kernel } from "inversify"; + +module server { + let kernel = new Kernel(); + let server = new InversifyExpressServer(kernel); + + server + .setConfig((app) => { + app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { + console.log("hello world"); + next(); + }); + }) + .setErrorConfig((app) => { + app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { + console.error(err.stack); + res.status(500).send("Something broke!"); + }); + }) + .build() + .listen(3000, "localhost"); +} + +module decorators { + + @Controller("/") + class TestController { + + @Get("/") + public testGet() { return "GET"; } + + @All("/") + public testAll() { return "ALL"; } + + @Delete("/") + public testDelete() { return "DELETE"; } + + @Head("/") + public testHead() { return "HEAD"; } + + @Put("/") + public testPut() { return "PUT"; } + + @Patch("/") + public testPatch() { return "PATCH"; } + + @Post("/") + public testPost() { return "POST"; } + + @Method("foo", "/") + public testMethod() { return "METHOD:FOO"; } + } + + function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } + function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } + function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } + + @Controller("/", m1, m2, m3) + class TestMiddlewareController { + + @Get("/", m1, m2, m3) + public testGet() { return "GET"; } + + @All("/", m1, m2, m3) + public testAll() { return "ALL"; } + + @Delete("/", m1, m2, m3) + public testDelete() { return "DELETE"; } + + @Head("/", m1, m2, m3) + public testHead() { return "HEAD"; } + + @Put("/", m1, m2, m3) + public testPut() { return "PUT"; } + + @Patch("/", m1, m2, m3) + public testPatch() { return "PATCH"; } + + @Post("/", m1, m2, m3) + public testPost() { return "POST"; } + + @Method("foo", "/", m1, m2, m3) + public testMethod() { return "METHOD:FOO"; } + } +} diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts new file mode 100644 index 0000000000..aa9a20d23c --- /dev/null +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -0,0 +1,50 @@ +// Type definitions for inversify 1.0.0-alpha.4 +// Project: https://github.com/inversify/inversify-express-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "inversify-express-utils" { + + import * as express from "express"; + import * as inversify from "inversify"; + + interface IInversifyExpressServerConstructor { + new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer; + } + + interface IInversifyExpressServer { + setConfig(fn: IConfigFunction): IInversifyExpressServer; + setErrorConfig(fn: IConfigFunction): IInversifyExpressServer; + build(): express.Application; + } + + interface IConfigFunction { + (app: express.Application): void; + } + + interface IHandlerDecoratorFactory { + (path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator; + } + + interface IHandlerDecorator { + (target: any, key: string, value: any): void; + } + + export interface IController {} + + export var InversifyExpressServer: IInversifyExpressServerConstructor; + + export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void; + + export var All: IHandlerDecoratorFactory; + export var Get: IHandlerDecoratorFactory; + export var Post: IHandlerDecoratorFactory; + export var Put: IHandlerDecoratorFactory; + export var Patch: IHandlerDecoratorFactory; + export var Head: IHandlerDecoratorFactory; + export var Delete: IHandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator; +} diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts new file mode 100644 index 0000000000..c9c7d5c8a8 --- /dev/null +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -0,0 +1,59 @@ +/// + +declare var kernel: inversify.interfaces.Kernel; + +import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; + +interface ILoggerOutput { + entry: T; +} + +let makeStringRenderer = function (loggerOutput: ILoggerOutput) { + return function (entry: inversifyLoggerMiddleware.ILogEntry) { + loggerOutput.entry = textSerializer(entry); + }; +}; + +let makeObjRenderer = function (loggerOutput: ILoggerOutput) { + return function (entry: inversifyLoggerMiddleware.ILogEntry) { + loggerOutput.entry = entry; + }; +}; + +let options: inversifyLoggerMiddleware.ILoggerSettings = { + request: { + bindings: { + activated: true, + cache: true, + constraint: true, + dynamicValue: true, + factory: true, + implementationType: true, + onActivation: true, + provider: true, + scope: true, + serviceIdentifier: true, + type: true + }, + serviceIdentifier: true, + target: { + metadata: true, + name: true, + serviceIdentifier: true + } + }, + time: true +}; + +let logger = makeLoggerMiddleware(); +kernel.applyMiddleware(logger); + +let loggerOutput1: ILoggerOutput = { entry: null }; +let stringRenderer1 = makeStringRenderer(loggerOutput1); +let logger1 = makeLoggerMiddleware(options, stringRenderer1); +kernel.applyMiddleware(logger1); + +let loggerOutput2: ILoggerOutput = { entry: null }; +let objRenderer2 = makeObjRenderer(loggerOutput2); +let logger2 = makeLoggerMiddleware(options, objRenderer2); +kernel.applyMiddleware(logger2); diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts new file mode 100644 index 0000000000..3aa4ccca18 --- /dev/null +++ b/inversify-logger-middleware/inversify-logger-middleware.d.ts @@ -0,0 +1,59 @@ +// Type definitions for inversify 1.0.0-beta.6 +// Project: https://github.com/inversify/inversify-logger-middleware +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare namespace inversifyLoggerMiddleware { + + export interface ILoggerSettings { + request?: IRequestLoggerSettings; + time?: boolean; + } + + export interface IRequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: IBindingLoggerSettings; + target?: ITargetLoggerSettings; + } + + export interface IBindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface ITargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface ILogEntry { + error: boolean; + exception: any; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + + export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware; + export function textSerializer(entry: ILogEntry): string; + +} + +declare module "inversify-logger-middleware" { + export = inversifyLoggerMiddleware; +} diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index c39b231b91..e2ead555d4 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -1,39 +1,65 @@ -/// +/// +/// -namespace global_module_test { +let injectable = inversify.injectable; +let inject = inversify.inject; +let tagged = inversify.tagged; +let named = inversify.named; +let Kernel = inversify.Kernel; +let KernelModule = inversify.KernelModule; +let targetName = inversify.targetName; +let multiInject = inversify.multiInject; +let traverseAncerstors = inversify.traverseAncerstors; +let taggedConstraint = inversify.taggedConstraint; +let namedConstraint = inversify.namedConstraint; +let typeConstraint = inversify.typeConstraint; +let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator; +let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator; +let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator; +let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator; - interface INinja { +module external_module_test { + + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon extends Weapon { throw(): string; } - class Katana implements IKatana { + @injectable() + class Katana implements Weapon { public hit() { return "cut!"; } } - class Shuriken implements IShuriken { + @injectable() + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } + public hit() { + return "hit!"; + } } - @inversify.inject("IKatana", "IShuriken") - class Ninja implements INinja { + @injectable() + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; - public constructor(katana: IKatana, shuriken: IShuriken) { + public constructor( + @inject("Weapon") katana: Weapon, + @inject("ThrowableWeapon") shuriken: ThrowableWeapon + ) { this._katana = katana; this._shuriken = shuriken; } @@ -43,62 +69,73 @@ namespace global_module_test { } - let kernel = new inversify.Kernel(); - kernel.bind("INinja").to(Ninja); - kernel.bind("IKatana").to(Katana); - kernel.bind("IShuriken").to(Shuriken).inSingletonScope(); + let kernel: inversify.interfaces.Kernel = new Kernel(); + kernel.bind("Warrior").to(Ninja); + kernel.bind("Weapon").to(Katana); + kernel.bind("ThrowableWeapon").to(Shuriken).inSingletonScope(); - let ninja = kernel.get("INinja"); + let ninja = kernel.get("Warrior"); console.log(ninja); // Unbind - kernel.unbind("INinja"); + kernel.unbind("Warrior"); kernel.unbindAll(); // Kernel modules - let module: inversify.IKernelModule = (k: inversify.IKernel) => { - k.bind("INinja").to(Ninja); - k.bind("IKatana").to(Katana).inTransientScope(); - k.bind("IShuriken").to(Shuriken).inSingletonScope(); - }; + let warriors: inversify.interfaces.KernelModule = new KernelModule((bind: inversify.interfaces.Bind) => { + bind("Warrior").to(Ninja); + }); - let options: inversify.IKernelOptions = { - middleware: [], - modules: [module] - }; + let weapons: inversify.interfaces.KernelModule = new KernelModule((bind: inversify.interfaces.Bind) => { + bind("Weapon").to(Katana); + bind("ThrowableWeapon").to(Shuriken); + }); - kernel = new inversify.Kernel(options); - let ninja2 = kernel.get("INinja"); + kernel = new Kernel(); + kernel.load(warriors, weapons); + let ninja2 = kernel.get("Warrior"); console.log(ninja2); + // middleware + function logger(planAndResolve: inversify.interfaces.PlanAndResolve): inversify.interfaces.PlanAndResolve { + return (args: inversify.interfaces.PlanAndResolveArgs) => { + let start = new Date().getTime(); + let result = planAndResolve(args); + let end = new Date().getTime(); + console.log(end - start); + return result; + }; + } + + kernel.applyMiddleware(logger, logger); + // binding types - kernel.bind("IKatana").to(Katana); - kernel.bind("IKatana").toValue(new Katana()); + kernel.bind("Weapon").to(Katana); + kernel.bind("Weapon").toConstantValue(new Katana()); + kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); - kernel.bind>("IKatana").toConstructor(Katana); + kernel.bind>("Weapon").toConstructor(Katana); - kernel.bind>("IKatana").toFactory((context) => { + kernel.bind>("Weapon").toFactory((context) => { return () => { - return kernel.get("IKatana"); + return kernel.get("Weapon"); }; }); - kernel.bind>("IKatana").toAutoFactory(); + kernel.bind>("Weapon").toAutoFactory("Weapon"); - kernel.bind>("IKatana").toProvider((context) => { + kernel.bind>("Weapon").toProvider((context) => { return () => { - return new Promise((resolve) => { - let katana = kernel.get("IKatana"); + return new Promise((resolve) => { + let katana = kernel.get("Weapon"); resolve(katana); }); }; }); - kernel.bind("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => { - // BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha - /* + kernel.bind("Weapon").to(Katana).onActivation((context: inversify.interfaces.Context, katanaToBeInjected: Weapon) => { let handler = { - apply: function(target, thisArgument, argumentsList) { + apply: function(target: any, thisArgument: any, argumentsList: any[]) { console.log(`Starting: ${performance.now()}`); let result = target.apply(thisArgument, argumentsList); console.log(`Finished: ${performance.now()}`); @@ -106,88 +143,301 @@ namespace global_module_test { } }; return new Proxy(katanaToBeInjected, handler); - */ - return katanaToBeInjected; }); - interface IWeapon {} - interface ISamurai { - katana: IWeapon; - shuriken: IWeapon; - } - - @inversify.inject("IWeapon", "IWeapon") - class Samurai implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai implements Warrior { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @inversify.tagged("canThrow", false) katana: IWeapon, - @inversify.tagged("canThrow", true) shuriken: IWeapon + @inject("Weapon") @tagged("canThrow", false) katana: Weapon, + @inject("ThrowableWeapon") @tagged("canThrow", true) shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); - kernel.bind("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); - let throwable = inversify.tagged("canThrow", true); - let notThrowable = inversify.tagged("canThrow", false); + let throwable = tagged("canThrow", true); + let notThrowable = tagged("canThrow", false); - @inversify.inject("IWeapon", "IWeapon") - class Samurai2 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai2 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @throwable("canThrow", false) katana: IWeapon, - @notThrowable("canThrow", true) shuriken: IWeapon + @inject("Weapon") @throwable katana: Weapon, + @inject("ThrowableWeapon") @notThrowable shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - @inversify.inject("IWeapon", "IWeapon") - class Samurai3 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai3 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @inversify.named("strong") katana: IWeapon, - @inversify.named("weak") shuriken: IWeapon + @inject("Weapon") @named("strong") katana: Weapon, + @inject("ThrowableWeapon") @named("weak") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai3); - kernel.bind("IWeapon").to(Katana).whenTargetNamed("strong"); - kernel.bind("IWeapon").to(Shuriken).whenTargetNamed("weak"); + kernel.bind("Warrior").to(Samurai3); + kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); - @inversify.inject("IWeapon", "IWeapon") - @inversify.paramNames("katana", "shuriken") - class Samurai4 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai4 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - katana: IWeapon, - shuriken: IWeapon + @inject("Weapon") @targetName("katana") katana: Weapon, + @inject("ThrowableWeapon") @targetName("shuriken") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai4); + kernel.bind("Warrior").to(Samurai4); - kernel.bind("IWeapon").to(Katana).when((request: inversify.IRequest) => { + kernel.bind("Weapon").to(Katana).when((request: inversify.interfaces.Request) => { return request.target.name.equals("katana"); }); - kernel.bind("IWeapon").to(Shuriken).when((request: inversify.IRequest) => { + kernel.bind("Weapon").to(Shuriken).when((request: inversify.interfaces.Request) => { return request.target.name.equals("shuriken"); }); + // custom constraints + let whenParentNamedCanThrowConstraint = (request: inversify.interfaces.Request) => { + return namedConstraint("canThrow")(request.parentRequest); + }; + + let whenAnyAncestorIsConstraint = (request: inversify.interfaces.Request) => { + return traverseAncerstors(request, typeConstraint(Ninja)); + }; + + let whenAnyAncestorTaggedConstraint = (request: inversify.interfaces.Request) => { + return traverseAncerstors(request, taggedConstraint("canThrow")(true)); + }; + + kernel.bind("Weapon").to(Shuriken).when(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorIsConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorTaggedConstraint); + + // Constraint helpers + kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); + kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); + + // multi-injection + @injectable() + class Samurai5 implements Warrior { + public katana: Weapon; + public shuriken: Weapon; + public constructor( + @multiInject("Weapon") wpns: Weapon[] + ) { + this.katana = wpns[0]; + this.shuriken = wpns[1]; + } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.hit(); }; + } + + // symbols + let SYMBOLS = { + ThrowableWeapon: Symbol("ThrowableWeapon"), + Warrior: Symbol("Warrior"), + Weapon: Symbol("Weapon"), + }; + + @injectable() + class Ninja1 implements Warrior { + + private _katana: Weapon; + private _shuriken: ThrowableWeapon; + + public constructor( + @inject(SYMBOLS.Weapon) katana: Weapon, + @inject(SYMBOLS.ThrowableWeapon) shuriken: ThrowableWeapon + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel3 = new Kernel(); + kernel3.bind(SYMBOLS.Warrior).to(Ninja); + kernel3.bind(SYMBOLS.Weapon).to(Katana); + kernel3.bind(SYMBOLS.ThrowableWeapon).to(Shuriken).inSingletonScope(); + + let ninja4 = kernel3.get("Warrior"); + console.log(ninja4); + + // classes + + @injectable() + class Ninja2 implements Warrior { + + private _katana: Katana; + private _shuriken: Shuriken; + + public constructor( + katana: Katana, + shuriken: Shuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel4 = new Kernel(); + kernel4.bind(Ninja).to(Ninja); + kernel4.bind(Katana).to(Katana); + kernel4.bind(Shuriken).to(Shuriken).inSingletonScope(); + + let ninja5 = kernel4.get(Ninja); + console.log(ninja5); + +} + +module property_injection { + + let kernel = new Kernel(); + + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class WarHammer implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); + + class Warrior1 { + @propertyMultiInject(TYPES.Weapon) + public weapons: Weapon[]; + } + + let propertyInject = makePropertyInjectDecorator(kernel); + + interface Service { + count: number; + increment(): void; + } + + @injectable() + class SomeService implements Service { + public count: number; + public constructor() { + this.count = 0; + } + public increment() { + this.count = this.count + 1; + } + } + + class SomeWebComponent { + @propertyInject("Service") + private _service: Service; + public doSomething() { + let count = this._service.count; + this._service.increment(); + return count; + } + } + + let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); + + class Warrior2 { + + @propertyInjectNammed(TYPES.Weapon, "not-throwwable") + @named("not-throwwable") + public primaryWeapon: Weapon; + + @propertyInjectNammed(TYPES.Weapon, "throwwable") + @named("throwwable") + public secondaryWeapon: Weapon; + + } + + let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); + + class Warrior3 { + + @propertyInjectTagged(TYPES.Weapon, "throwwable", false) + @tagged("throwwable", false) + public primaryWeapon: Weapon; + + @propertyInjectTagged(TYPES.Weapon, "throwwable", true) + @tagged("throwwable", true) + public secondaryWeapon: Weapon; + + } + + kernel.snapshot(); + kernel.restore(); + } diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 23af8db21f..9b5de8fa0e 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -1,46 +1,62 @@ -/// +/// +/// import { Kernel, - inject, tagged, named, paramNames, - IKernel, IKernelOptions, INewable, - IKernelModule, IFactory, IProvider, IRequest + injectable, tagged, named, targetName, + inject, multiInject, traverseAncerstors, + taggedConstraint, namedConstraint, typeConstraint, + makePropertyMultiInjectDecorator, + makePropertyInjectTaggedDecorator, + makePropertyInjectNamedDecorator, + makePropertyInjectDecorator, + KernelModule, interfaces } from "inversify"; -namespace external_module_test { +import * as Proxy from "harmony-proxy"; - interface INinja { +module external_module_test { + + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon extends Weapon { throw(): string; } - class Katana implements IKatana { + @injectable() + class Katana implements Weapon { public hit() { return "cut!"; } } - class Shuriken implements IShuriken { + @injectable() + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } + public hit() { + return "hit!"; + } } - @inject("IKatana", "IShuriken") - class Ninja implements INinja { + @injectable() + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; - public constructor(katana: IKatana, shuriken: IShuriken) { + public constructor( + @inject("Weapon") katana: Weapon, + @inject("ThrowableWeapon") shuriken: ThrowableWeapon + ) { this._katana = katana; this._shuriken = shuriken; } @@ -50,62 +66,73 @@ namespace external_module_test { } - let kernel = new Kernel(); - kernel.bind("INinja").to(Ninja); - kernel.bind("IKatana").to(Katana); - kernel.bind("IShuriken").to(Shuriken).inSingletonScope(); + let kernel: interfaces.Kernel = new Kernel(); + kernel.bind("Warrior").to(Ninja); + kernel.bind("Weapon").to(Katana); + kernel.bind("ThrowableWeapon").to(Shuriken).inSingletonScope(); - let ninja = kernel.get("INinja"); + let ninja = kernel.get("Warrior"); console.log(ninja); // Unbind - kernel.unbind("INinja"); + kernel.unbind("Warrior"); kernel.unbindAll(); // Kernel modules - let module: IKernelModule = (k: IKernel) => { - k.bind("INinja").to(Ninja); - k.bind("IKatana").to(Katana).inTransientScope(); - k.bind("IShuriken").to(Shuriken).inSingletonScope(); - }; + let warriors: interfaces.KernelModule = new KernelModule((bind: interfaces.Bind) => { + bind("Warrior").to(Ninja); + }); - let options: IKernelOptions = { - middleware: [], - modules: [module] - }; + let weapons: interfaces.KernelModule = new KernelModule((bind: interfaces.Bind) => { + bind("Weapon").to(Katana); + bind("ThrowableWeapon").to(Shuriken); + }); - kernel = new Kernel(options); - let ninja2 = kernel.get("INinja"); + kernel = new Kernel(); + kernel.load(warriors, weapons); + let ninja2 = kernel.get("Warrior"); console.log(ninja2); + // middleware + function logger(planAndResolve: interfaces.PlanAndResolve): interfaces.PlanAndResolve { + return (args: interfaces.PlanAndResolveArgs) => { + let start = new Date().getTime(); + let result = planAndResolve(args); + let end = new Date().getTime(); + console.log(end - start); + return result; + }; + } + + kernel.applyMiddleware(logger, logger); + // binding types - kernel.bind("IKatana").to(Katana); - kernel.bind("IKatana").toValue(new Katana()); + kernel.bind("Weapon").to(Katana); + kernel.bind("Weapon").toConstantValue(new Katana()); + kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); - kernel.bind>("IKatana").toConstructor(Katana); + kernel.bind>("Weapon").toConstructor(Katana); - kernel.bind>("IKatana").toFactory((context) => { + kernel.bind>("Weapon").toFactory((context) => { return () => { - return kernel.get("IKatana"); + return kernel.get("Weapon"); }; }); - kernel.bind>("IKatana").toAutoFactory(); + kernel.bind>("Weapon").toAutoFactory("Weapon"); - kernel.bind>("IKatana").toProvider((context) => { + kernel.bind>("Weapon").toProvider((context) => { return () => { - return new Promise((resolve) => { - let katana = kernel.get("IKatana"); + return new Promise((resolve) => { + let katana = kernel.get("Weapon"); resolve(katana); }); }; }); - kernel.bind("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => { - // BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha - /* + kernel.bind("Weapon").to(Katana).onActivation((context: interfaces.Context, katanaToBeInjected: Weapon) => { let handler = { - apply: function(target, thisArgument, argumentsList) { + apply: function(target: any, thisArgument: any, argumentsList: any[]) { console.log(`Starting: ${performance.now()}`); let result = target.apply(thisArgument, argumentsList); console.log(`Finished: ${performance.now()}`); @@ -113,88 +140,302 @@ namespace external_module_test { } }; return new Proxy(katanaToBeInjected, handler); - */ - return katanaToBeInjected; }); - interface IWeapon {} - interface ISamurai { - katana: IWeapon; - shuriken: IWeapon; - } - @inject("IWeapon", "IWeapon") - class Samurai implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai implements Warrior { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @tagged("canThrow", false) katana: IWeapon, - @tagged("canThrow", true) shuriken: IWeapon + @inject("Weapon") @tagged("canThrow", false) katana: Weapon, + @inject("ThrowableWeapon") @tagged("canThrow", true) shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); - kernel.bind("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); - @inject("IWeapon", "IWeapon") - class Samurai2 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai2 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @throwable("canThrow", false) katana: IWeapon, - @notThrowable("canThrow", true) shuriken: IWeapon + @inject("Weapon") @throwable katana: Weapon, + @inject("ThrowableWeapon") @notThrowable shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - @inject("IWeapon", "IWeapon") - class Samurai3 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai3 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @named("strong") katana: IWeapon, - @named("weak") shuriken: IWeapon + @inject("Weapon") @named("strong") katana: Weapon, + @inject("ThrowableWeapon") @named("weak") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai3); - kernel.bind("IWeapon").to(Katana).whenTargetNamed("strong"); - kernel.bind("IWeapon").to(Shuriken).whenTargetNamed("weak"); + kernel.bind("Warrior").to(Samurai3); + kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); - @inject("IWeapon", "IWeapon") - @paramNames("katana", "shuriken") - class Samurai4 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai4 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - katana: IWeapon, - shuriken: IWeapon + @inject("Weapon") @targetName("katana") katana: Weapon, + @inject("ThrowableWeapon") @targetName("shuriken") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai4); + kernel.bind("Warrior").to(Samurai4); - kernel.bind("IWeapon").to(Katana).when((request: IRequest) => { + kernel.bind("Weapon").to(Katana).when((request: interfaces.Request) => { return request.target.name.equals("katana"); }); - kernel.bind("IWeapon").to(Shuriken).when((request: IRequest) => { + kernel.bind("Weapon").to(Shuriken).when((request: interfaces.Request) => { return request.target.name.equals("shuriken"); }); + // custom constraints + let whenParentNamedCanThrowConstraint = (request: interfaces.Request) => { + return namedConstraint("canThrow")(request.parentRequest); + }; + + let whenAnyAncestorIsConstraint = (request: interfaces.Request) => { + return traverseAncerstors(request, typeConstraint(Ninja)); + }; + + let whenAnyAncestorTaggedConstraint = (request: interfaces.Request) => { + return traverseAncerstors(request, taggedConstraint("canThrow")(true)); + }; + + kernel.bind("Weapon").to(Shuriken).when(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorIsConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorTaggedConstraint); + + // Constraint helpers + kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); + kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); + + // multi-injection + @injectable() + class Samurai5 implements Warrior { + public katana: Weapon; + public shuriken: Weapon; + public constructor( + @multiInject("Weapon") wpns: Weapon[] + ) { + this.katana = wpns[0]; + this.shuriken = wpns[1]; + } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.hit(); }; + } + + // symbols + let SYMBOLS = { + ThrowableWeapon: Symbol("ThrowableWeapon"), + Warrior: Symbol("Warrior"), + Weapon: Symbol("Weapon"), + }; + + @injectable() + class Ninja1 implements Warrior { + + private _katana: Weapon; + private _shuriken: ThrowableWeapon; + + public constructor( + @inject(SYMBOLS.Weapon) katana: Weapon, + @inject(SYMBOLS.ThrowableWeapon) shuriken: ThrowableWeapon + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel3 = new Kernel(); + kernel3.bind(SYMBOLS.Warrior).to(Ninja); + kernel3.bind(SYMBOLS.Weapon).to(Katana); + kernel3.bind(SYMBOLS.ThrowableWeapon).to(Shuriken).inSingletonScope(); + + let ninja4 = kernel3.get("Warrior"); + console.log(ninja4); + + // classes + + @injectable() + class Ninja2 implements Warrior { + + private _katana: Katana; + private _shuriken: Shuriken; + + public constructor( + katana: Katana, + shuriken: Shuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel4 = new Kernel(); + kernel4.bind(Ninja).to(Ninja); + kernel4.bind(Katana).to(Katana); + kernel4.bind(Shuriken).to(Shuriken).inSingletonScope(); + + let ninja5 = kernel4.get(Ninja); + console.log(ninja5); + +} + +module property_injection { + + let kernel = new Kernel(); + + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class WarHammer implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); + + class Warrior1 { + @propertyMultiInject(TYPES.Weapon) + public weapons: Weapon[]; + } + + let propertyInject = makePropertyInjectDecorator(kernel); + + interface Service { + count: number; + increment(): void; + } + + @injectable() + class SomeService implements Service { + public count: number; + public constructor() { + this.count = 0; + } + public increment() { + this.count = this.count + 1; + } + } + + class SomeWebComponent { + @propertyInject("Service") + private _service: Service; + public doSomething() { + let count = this._service.count; + this._service.increment(); + return count; + } + } + + let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); + + class Warrior2 { + + @propertyInjectNammed(TYPES.Weapon, "not-throwwable") + @named("not-throwwable") + public primaryWeapon: Weapon; + + @propertyInjectNammed(TYPES.Weapon, "throwwable") + @named("throwwable") + public secondaryWeapon: Weapon; + + } + + let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); + + class Warrior3 { + + @propertyInjectTagged(TYPES.Weapon, "throwwable", false) + @tagged("throwwable", false) + public primaryWeapon: Weapon; + + @propertyInjectTagged(TYPES.Weapon, "throwwable", true) + @tagged("throwwable", true) + public secondaryWeapon: Weapon; + + } + + kernel.snapshot(); + kernel.restore(); + } diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 79cd4e3dec..41200ae470 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,141 +1,277 @@ -// Type definitions for inversify 2.0.0-alpha.3 +// Type definitions for inversify 2.0.0-beta.9 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// +interface Symbol { + toString(): string; + valueOf(): Object; +} + +interface SymbolConstructor { + (description?: string|number): Symbol; +} + +declare var Symbol: SymbolConstructor; + declare namespace inversify { - interface IKernelConstructor { - new(options?: IKernelOptions): IKernel; + namespace interfaces { + + export interface KernelConstructor { + new(): Kernel; + } + + export interface KernelModuleConstructor { + new(registry: (bind: Bind) => void): KernelModule; + } + + export interface Newable { + new(...args: any[]): T; + } + + export type ServiceIdentifier = (string|Symbol|Newable); + + export interface Binding extends Clonable> { + guid: string; + moduleId: string; + activated: boolean; + serviceIdentifier: ServiceIdentifier; + implementationType: Newable; + factory: FactoryCreator; + provider: ProviderCreator; + constraint: (request: Request) => boolean; + onActivation: (context: Context, injectable: T) => T; + cache: T; + dynamicValue: () => T; + scope: number; // BindingScope + type: number; // BindingType + } + + export interface Factory extends Function { + (...args: any[]): (((...args: any[]) => T)|T); + } + + export interface FactoryCreator extends Function { + (context: Context): Factory; + } + + export interface Provider extends Function { + (): Promise; + } + + export interface ProviderCreator extends Function { + (context: Context): Provider; + } + + export interface PlanAndResolve { + (args: PlanAndResolveArgs): T[]; + } + + export interface PlanAndResolveArgs { + multiInject: boolean; + serviceIdentifier: ServiceIdentifier; + target: Target; + contextInterceptor: (contexts: Context) => Context; + } + + export interface Middleware extends Function { + (next: PlanAndResolve): PlanAndResolve; + } + + export interface Context { + guid: string; + kernel: Kernel; + plan: Plan; + addPlan(plan: Plan): void; + } + + export interface ReflectResult { + [key: string]: Metadata[]; + } + + export interface Metadata { + key: string; + value: any; + } + + export interface Plan { + parentContext: Context; + rootRequest: Request; + } + + export interface Planner { + createContext(kernel: Kernel): Context; + createPlan(parentContext: Context, binding: Binding, target: Target): Plan; + getBindings(kernel: Kernel, serviceIdentifier: ServiceIdentifier): Binding[]; + getActiveBindings(parentRequest: Request, target: Target): Binding[]; + } + + export interface QueryableString { + startsWith(searchString: string): boolean; + endsWith(searchString: string): boolean; + contains(searchString: string): boolean; + equals(compareString: string): boolean; + value(): string; + } + + export interface Request { + guid: string; + serviceIdentifier: ServiceIdentifier; + parentContext: Context; + parentRequest: Request; + childRequests: Request[]; + target: Target; + bindings: Binding[]; + addChildRequest( + serviceIdentifier: ServiceIdentifier, + bindings: (Binding|Binding[]), + target: Target + ): Request; + } + + export interface Target { + guid: string; + serviceIdentifier: ServiceIdentifier; + name: QueryableString; + metadata: Array; + hasTag(key: string): boolean; + isArray(): boolean; + matchesArray(name: string|Symbol|Newable): boolean; + isNamed(): boolean; + isTagged(): boolean; + matchesNamedTag(name: string): boolean; + matchesTag(key: string): (value: any) => boolean; + } + + export interface Resolver { + resolve(context: Context): T; + } + + export interface Kernel { + guid: string; + bind(serviceIdentifier: ServiceIdentifier): BindingToSyntax; + unbind(serviceIdentifier: ServiceIdentifier): void; + unbindAll(): void; + isBound(serviceIdentifier: ServiceIdentifier): boolean; + get(serviceIdentifier: ServiceIdentifier): T; + getNamed(serviceIdentifier: ServiceIdentifier, named: string): T; + getTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T; + getAll(serviceIdentifier: ServiceIdentifier): T[]; + load(...modules: KernelModule[]): void; + unload(...modules: KernelModule[]): void; + applyMiddleware(...middleware: Middleware[]): void; + getServiceIdentifierAsString(serviceIdentifier: ServiceIdentifier): string; + snapshot(): void; + restore(): void; + } + + export interface Bind extends Function { + (serviceIdentifier: ServiceIdentifier): BindingToSyntax; + } + + export interface KernelModule { + guid: string; + registry: (bind: Bind) => void; + } + + export interface KernelSnapshot { + bindings: Lookup>; + middleware: PlanAndResolve; + } + + export interface Clonable { + clone(): T; + } + + export interface Lookup extends Clonable> { + add(serviceIdentifier: ServiceIdentifier, value: T): void; + get(serviceIdentifier: ServiceIdentifier): Array; + remove(serviceIdentifier: ServiceIdentifier): void; + removeByModuleId(moduleId: string): void; + hasKey(serviceIdentifier: ServiceIdentifier): boolean; + } + + export interface KeyValuePair { + serviceIdentifier: ServiceIdentifier; + value: Array; + } + + export interface BindingInSyntax { + inSingletonScope(): BindingWhenOnSyntax; + } + + export interface BindingInWhenOnSyntax extends BindingInSyntax, BindingWhenOnSyntax {} + + export interface BindingOnSyntax { + onActivation(fn: (context: Context, injectable: T) => T): BindingWhenSyntax; + } + + export interface BindingToSyntax { + to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax; + toConstantValue(value: T): BindingWhenOnSyntax; + toDynamicValue(func: () => T): BindingWhenOnSyntax; + toConstructor(constructor: Newable): BindingWhenOnSyntax; + toFactory(factory: FactoryCreator): BindingWhenOnSyntax; + toFunction(func: T): BindingWhenOnSyntax; + toAutoFactory(serviceIdentifier: ServiceIdentifier): BindingWhenOnSyntax; + toProvider(provider: ProviderCreator): BindingWhenOnSyntax; + } + + export interface BindingWhenOnSyntax extends BindingWhenSyntax, BindingOnSyntax {} + + export interface BindingWhenSyntax { + when(constraint: (request: Request) => boolean): BindingOnSyntax; + whenTargetNamed(name: string): BindingOnSyntax; + whenTargetTagged(tag: string, value: any): BindingOnSyntax; + whenInjectedInto(parent: (Function|string)): BindingOnSyntax; + whenParentNamed(name: string): BindingOnSyntax; + whenParentTagged(tag: string, value: any): BindingOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): BindingOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): BindingOnSyntax; + whenAnyAncestorNamed(name: string): BindingOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): BindingOnSyntax; + whenNoAncestorNamed(name: string): BindingOnSyntax; + whenNoAncestorTagged(tag: string, value: any): BindingOnSyntax; + whenAnyAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; + whenNoAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; + } + } - export interface IKernel { - bind(runtimeIdentifier: string): IBindingToSyntax; - unbind(runtimeIdentifier: string): void; - unbindAll(): void; - get(runtimeIdentifier: string): T; - getAll(runtimeIdentifier: string): T[]; - } + export var Kernel: interfaces.KernelConstructor; + export var KernelModule: interfaces.KernelModuleConstructor; + export var decorate: (decorator: (ClassDecorator|ParameterDecorator), target: any, parameterIndex?: number) => void; + export function injectable(): (typeConstructor: any) => void; + export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any; + export function named(name: string): (target: any, targetKey: string, index?: number) => any; + export function targetName(name: string): (target: any, targetKey: string, index: number) => any; + export function inject(serviceIdentifier: interfaces.ServiceIdentifier): (target: any, targetKey: string, index?: number) => any; - export interface IKernelOptions { - middleware?: IMiddleware[]; - modules?: IKernelModule[]; - } + export function multiInject( + serviceIdentifier: interfaces.ServiceIdentifier + ): (target: any, targetKey: string, index?: number) => any; - interface IMiddleware extends Function { - (...args: any[]): any; - } + export function makePropertyInjectDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - export interface IKernelModule extends Function { - (kernel: IKernel): void; - } + export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable), named: string) => (proto: any, key: string) => void; - interface IBindingToSyntax { - to(constructor: { new(...args: any[]): T; }): IBindingInWhenProxySyntax; - toValue(value: T): IBindingInWhenProxySyntax; - toConstructor(constructor: INewable): IBindingInWhenProxySyntax; - toFactory(factory: IFactoryCreator): IBindingInWhenProxySyntax; - toAutoFactory(): IBindingInWhenProxySyntax; - toProvider(provider: IProviderCreator): IBindingInWhenProxySyntax; - } + export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable), key: string, value: any) => (proto: any, propertyName: string) => void; - interface IBindingInWhenProxySyntax { - inTransientScope(): IBindingInWhenProxySyntax; - inSingletonScope(): IBindingInWhenProxySyntax; - when(constraint: (request: IRequest) => boolean): IBindingInWhenProxySyntax; - whenTargetNamed(name: string): IBindingInWhenProxySyntax; - whenTargetTagged(tag: string, value: any): IBindingInWhenProxySyntax; - proxy(fn: (injectable: T) => T): IBindingInWhenProxySyntax; - } + export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - export interface IFactory extends Function { - (): T; - } + // constraint helpers + export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean; + export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean; + export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean; + export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean; - interface IFactoryCreator extends Function { - (context: IContext): IFactory; - } - - export interface INewable { - new(...args: any[]): T; - } - - export interface IProvider extends Function { - (): Promise; - } - - interface IProviderCreator extends Function { - (context: IContext): IProvider; - } - - export interface IContext { - kernel: IKernel; - plan: IPlan; - addPlan(plan: IPlan): void; - } - - export interface IPlan { - parentContext: IContext; - rootRequest: IRequest; - } - - export interface IRequest { - service: string; - parentContext: IContext; - parentRequest: IRequest; - childRequests: IRequest[]; - target: ITarget; - bindings: IBinding[]; - addChildRequest( - service: string, - bindings: (IBinding|IBinding[]), - target: ITarget): IRequest; - } - - export interface IBinding { - runtimeIdentifier: string; - implementationType: INewable; - factory: IFactoryCreator; - provider: IProviderCreator; - constraint: (request: IRequest) => boolean; - proxyMaker: (injectable: T) => T; - cache: T; - scope: number; // BindingScope - type: number; // BindingType - } - - export interface ITarget { - service: IQueryableString; - name: IQueryableString; - metadata: Array; - isArray(): boolean; - isNamed(): boolean; - isTagged(): boolean; - matchesName(name: string): boolean; - matchesTag(name: IMetadata): boolean; - } - - export interface IQueryableString { - startsWith(searchString: string): boolean; - endsWith(searchString: string): boolean; - contains(searchString: string): boolean; - equals(compareString: string): boolean; - value(): string; - } - - export interface IMetadata { - key: string; - value: any; - } - - export var Kernel: IKernelConstructor; - export var decorate: any; - export function inject(...typeIdentifiers: string[]): (typeConstructor: any) => void; - export var tagged: any; - export var named: any; - export var paramNames: any; } declare module "inversify" { diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 9841a74fc8..538aca3fb6 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -179,6 +179,7 @@ declare namespace jasmine { addCustomEqualityTester(equalityTester: CustomEqualityTester): void; addMatchers(matchers: CustomMatcherFactories): void; specFilter(spec: Spec): boolean; + throwOnExpectationFailure(value: boolean): void; } interface FakeTimer { @@ -301,7 +302,7 @@ declare namespace jasmine { toContain(expected: any, expectationFailOutput?: any): boolean; toBeLessThan(expected: number, expectationFailOutput?: any): boolean; toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean; - toBeCloseTo(expected: number, precision: any, expectationFailOutput?: any): boolean; + toBeCloseTo(expected: number, precision?: any, expectationFailOutput?: any): boolean; toThrow(expected?: any): boolean; toThrowError(message?: string | RegExp): boolean; toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; diff --git a/javascript-obfuscator/javascript-obfuscator-tests.ts b/javascript-obfuscator/javascript-obfuscator-tests.ts index 74d6363ffb..1c0753c3bf 100644 --- a/javascript-obfuscator/javascript-obfuscator-tests.ts +++ b/javascript-obfuscator/javascript-obfuscator-tests.ts @@ -5,11 +5,14 @@ import { JavaScriptObfuscator } from 'javascript-obfuscator'; let sourceCode1: string = JavaScriptObfuscator.obfuscate('var foo = 1;'); let sourceCode2: string = JavaScriptObfuscator.obfuscate('var foo = 1;', { compact: true, - debugProtection: false, - debugProtectionInterval: false, - disableConsoleOutput: true, - encodeUnicodeLiterals: true, - rotateUnicodeArray: true, - unicodeArray: true, - wrapUnicodeArrayCalls: true + debugProtection: false, + debugProtectionInterval: false, + disableConsoleOutput: true, + encodeUnicodeLiterals: false, + reservedNames: ['^foo$'], + rotateUnicodeArray: true, + selfDefending: true, + unicodeArray: true, + unicodeArrayThreshold: 0.8, + wrapUnicodeArrayCalls: true }); diff --git a/javascript-obfuscator/javascript-obfuscator.d.ts b/javascript-obfuscator/javascript-obfuscator.d.ts index 7b7a8438c5..17a91c4925 100644 --- a/javascript-obfuscator/javascript-obfuscator.d.ts +++ b/javascript-obfuscator/javascript-obfuscator.d.ts @@ -10,8 +10,11 @@ declare module 'javascript-obfuscator' { debugProtectionInterval?: boolean; disableConsoleOutput?: boolean; encodeUnicodeLiterals?: boolean; + reservedNames?: string[]; rotateUnicodeArray?: boolean; + selfDefending?: boolean; unicodeArray?: boolean; + unicodeArrayThreshold?: number; wrapUnicodeArrayCalls?: boolean; [id: string]: any; } diff --git a/jquery-truncate-html/jquery-truncate-html-tests.ts b/jquery-truncate-html/jquery-truncate-html-tests.ts new file mode 100644 index 0000000000..e20f9c22ee --- /dev/null +++ b/jquery-truncate-html/jquery-truncate-html-tests.ts @@ -0,0 +1,14 @@ +/// + + +function truncateHtmlString(): string { + return $.truncate('

Stuff and Nonsense

', { + length: 13 + }); +} + +function truncateVirtualElement (): JQuery { + return $('

Stuff and Nonsense

').truncate({ + length: 13 + }); +} diff --git a/jquery-truncate-html/jquery-truncate-html.d.ts b/jquery-truncate-html/jquery-truncate-html.d.ts new file mode 100644 index 0000000000..e410716b0a --- /dev/null +++ b/jquery-truncate-html/jquery-truncate-html.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jQuery-truncate-html.js +// Project: https://github.com/kbwood/timeentry +// Definitions by: Abraão Alves +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface TruncateOptions{ + length?: number; + stripTags?: boolean; + words?: boolean; + noBreaks?: boolean; + ellipsis?: string; +} + +interface JQuery{ + truncate(options: TruncateOptions) : JQuery; +} + +interface JQueryStatic { + truncate(html: string, options: TruncateOptions) : string; +} diff --git a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts index fcc3bac9da..9c13b5a28f 100644 --- a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts @@ -1,5 +1,5 @@ // Type definitions for Microsoft jQuery Unobtrusive Validation v3.2.3 -// Project: http://aspnetwebstack.codeplex.com/ +// Project: https://github.com/aspnet/jquery-validation-unobtrusive // Definitions by: Matt Brooks // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jquery.slimScroll/jquery.SlimScroll-tests.ts b/jquery.slimScroll/jquery.SlimScroll-tests.ts index deb4f2406d..046eda840f 100644 --- a/jquery.slimScroll/jquery.SlimScroll-tests.ts +++ b/jquery.slimScroll/jquery.SlimScroll-tests.ts @@ -41,6 +41,21 @@ $('#slimtest3').slimScroll({ alwaysVisible: true }); +$('#slimtest3').slimScroll({ + color: '#00f', + size: '10px', + height: '180px', + alwaysVisible: true, + destroy: true +}); + $("div").slimScroll().bind('slimscroll', function(e){ console.log("Reached " + e); -}); \ No newline at end of file +}); + +var options : IJQuerySlimScrollOptions = { + destroy: true, + position: 'left' +}; + +$('#slimtest3').slimScroll(options); diff --git a/jquery.slimScroll/jquery.slimScroll.d.ts b/jquery.slimScroll/jquery.slimScroll.d.ts index 4d77d28817..b5d3dab17f 100644 --- a/jquery.slimScroll/jquery.slimScroll.d.ts +++ b/jquery.slimScroll/jquery.slimScroll.d.ts @@ -1,58 +1,110 @@ -// Type definitions for jQuery.slimScroll v1.3.3 +// Type definitions for jQuery.slimScroll v1.3.8 // Project: https://github.com/rochal/jQuery-slimScroll // Definitions by: Chintan Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// interface IJQuerySlimScrollOptions { - // width in pixels of the visible scroll area + /** + * width in pixels of the visible scroll area + */ width? :string; - // height in pixels of the visible scroll area + /** + * height in pixels of the visible scroll area + */ height? :string; - // width in pixels of the scrollbar and rail + /** + * width in pixels of the scrollbar and rail + */ size? :string; - // scrollbar color, accepts any hex/color value + /** + * scrollbar color, accepts any hex/color value + */ color?:string; - // scrollbar position - left/right + /** + * scrollbar position - left/right + */ position?:string; - // distance in pixels between the side edge and the scrollbar + /** + * distance in pixels between the side edge and the scrollbar + */ distance?:string; - // default scroll position on load - top / bottom / $('selector') + /** + * default scroll position on load - top / bottom / $('selector') + */ start?:any; - // sets scrollbar opacity + /** + * sets scrollbar opacity + */ opacity? :number; - // enables always-on mode for the scrollbar + /** + * enables always-on mode for the scrollbar + */ alwaysVisible?: boolean; - // check if we should hide the scrollbar when user is hovering over + /** + * check if we should hide the scrollbar when user is hovering over + */ disableFadeOut?: boolean; - // sets visibility of the rail + /** + * sets visibility of the rail + */ railVisible?: boolean; - // sets rail color + /** + * sets rail color + */ railColor?: string; - // sets rail opacity + /** + * sets rail opacity + */ railOpacity?:number; - // whether we should use jQuery UI Draggable to enable bar dragging + /** + * whether we should use jQuery UI Draggable to enable bar dragging + */ railDraggable?: boolean; - // defautlt CSS class of the slimscroll rail + /** + * default CSS class of the slimscroll rail + */ railClass?: string; - // defautlt CSS class of the slimscroll bar + /** + * default CSS class of the slimscroll bar + */ barClass?: string; - // defautlt CSS class of the slimscroll wrapper + /** + * default CSS class of the slimscroll wrapper + */ wrapperClass?: string; - // check if mousewheel should scroll the window if we reach top/bottom + /** + * check if mousewheel should scroll the window if we reach top/bottom + */ allowPageScroll?: boolean; - // scroll amount applied to each mouse wheel step + /** + * scroll amount applied to each mouse wheel step + */ wheelStep?: number; - // scroll amount applied when user is using gestures + /** + * scroll amount applied when user is using gestures + */ touchScrollStep?: number; - // sets border radius + /** + * sets border radius + */ borderRadius?: string; - // sets border radius of the rail + /** + * sets border radius of the rail + */ railBorderRadius?: string; - // jumps to the specified scroll value + /** + * jumps to the specified scroll value + */ scrollTo?: string; - // increases/decreases current scroll value by specified amount + /** + * increases/decreases current scroll value by specified amount + */ scrollBy?: string; + /** + * release resources held by the plugin + */ + destroy?:boolean; } interface JQuery { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 6478529dad..40ebf2ee6c 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1987,6 +1987,24 @@ interface JQuery { */ click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Trigger the "contextmenu" event on an element. + */ + contextmenu(): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + contextmenu(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + contextmenu(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** * Trigger the "dblclick" event on an element. */ diff --git a/jwt-simple/jwt-simple-0.2.0-tests.ts b/jwt-simple/jwt-simple-0.2.0-tests.ts new file mode 100644 index 0000000000..8a0cc59c52 --- /dev/null +++ b/jwt-simple/jwt-simple-0.2.0-tests.ts @@ -0,0 +1,12 @@ +/// + +import jwt = require('jwt-simple'); +var payload = { foo: 'bar' }; +var secret:string = 'xxx'; + +// encode +var token = jwt.encode(payload, secret); + +// decode +var decoded = jwt.decode(token, secret); +console.log(decoded); //=> { foo: 'bar' } \ No newline at end of file diff --git a/jwt-simple/jwt-simple-0.2.0.d.ts b/jwt-simple/jwt-simple-0.2.0.d.ts new file mode 100644 index 0000000000..0ee3cc6799 --- /dev/null +++ b/jwt-simple/jwt-simple-0.2.0.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jwt-simple v0.2.0 +// Project: https://github.com/hokaccha/node-jwt-simple +// Definitions by: Ken Fukuyama +// Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module "jwt-simple" { + /** + * Decode jwt + * @param token + * @param key + * @param noVerify + * @api public + */ + export function decode(token:any, key:string, noVerify?:boolean):any; + /** + * Encode jwt + * @param payload + * @param key + * @param algorithm default is HS256 + * @api public + */ + export function encode(payload:any, key:string, algorithm?:string):string; +} diff --git a/jwt-simple/jwt-simple.d.ts b/jwt-simple/jwt-simple.d.ts index 208c7e6beb..ea78b13e88 100644 --- a/jwt-simple/jwt-simple.d.ts +++ b/jwt-simple/jwt-simple.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jwt-simple v0.2.0 +// Type definitions for jwt-simple v0.5.0 // Project: https://github.com/hokaccha/node-jwt-simple -// Definitions by: Ken Fukuyama +// Definitions by: Ken Fukuyama , Gael Magnan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "jwt-simple" { /** @@ -8,15 +8,17 @@ declare module "jwt-simple" { * @param token * @param key * @param noVerify + * @param algorithm default is HS256 * @api public */ - export function decode(token:any, key:string, noVerify?:boolean):any; + export function decode(token:any, key:string, noVerify?:boolean, algorithm?:string):any; /** * Encode jwt * @param payload * @param key * @param algorithm default is HS256 + * @param options * @api public */ - export function encode(payload:any, key:string, algorithm?:string):string; + export function encode(payload:any, key:string, algorithm?:string, options?:any):string; } diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index b283f21c14..934a8cd8b1 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -1282,6 +1282,7 @@ declare namespace kendo.data { interface DataSourceRequestStartEvent extends DataSourceEvent { type?: string; + preventDefault(): void; } interface DataSourceRequestEndEvent extends DataSourceEvent { @@ -3334,6 +3335,7 @@ declare namespace kendo.ui { static fn: DropDownList; options: DropDownListOptions; + popup: kendo.ui.Popup; dataSource: kendo.data.DataSource; span: JQuery; diff --git a/kii-cloud-sdk/kii-cloud-sdk-tests.ts b/kii-cloud-sdk/kii-cloud-sdk-tests.ts index a7118d78d3..6ca7d611db 100644 --- a/kii-cloud-sdk/kii-cloud-sdk-tests.ts +++ b/kii-cloud-sdk/kii-cloud-sdk-tests.ts @@ -26,6 +26,9 @@ function main() { endpoint.installationID; }); + user.setLocale("en"); + var locale: string = user.getLocale(); + var anotherUser: KiiUser = KiiUserBuilder .builderWithIdentifier("id", "password") .setEmailAddress("mail@example.org") @@ -67,4 +70,30 @@ function main() { removeMembersArray: KiiUser[]) { } }); + + Kii.authenticateAsThing("thing id", "password", { + success: function (thingAuthContext: KiiThingContext) { + thingAuthContext.bucketWithName(""); + }, + failure: function (error) { + } + }) + .then(function (thingAuthContext: KiiThingContext) { + }); + + Kii.authenticateAsThingWithToken("thing id", "token", { + success: function (thingAuthContext: KiiThingContext) { + thingAuthContext.bucketWithName(""); + }, + failure: function (error) { + } + }) + .then(function (thingAuthContext: KiiThingContext) { + }); + + KiiThing.loadWithVendorThingID("thing ID") + .then(function (thing) { + var isOnline: boolean = thing.isOnline(); + var onlineStatusModifiedAt: Date = thing.getOnlineStatusModifiedAt(); + }); } diff --git a/kii-cloud-sdk/kii-cloud-sdk.d.ts b/kii-cloud-sdk/kii-cloud-sdk.d.ts index 550aa736fa..26decd07a0 100644 --- a/kii-cloud-sdk/kii-cloud-sdk.d.ts +++ b/kii-cloud-sdk/kii-cloud-sdk.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kii Cloud SDK v2.4.4 +// Type definitions for Kii Cloud SDK v2.4.6 // Project: http://en.kii.com/ // Definitions by: Kii Consortium // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,7 +17,8 @@ declare namespace KiiCloud { JP, CN, SG, - CN3 + CN3, + EU } export enum KiiAnalyticsSite { @@ -25,7 +26,8 @@ declare namespace KiiCloud { JP, CN, SG, - CN3 + CN3, + EU } enum KiiSocialNetworkName { @@ -512,6 +514,104 @@ declare namespace KiiCloud { * ); */ static listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Authenticate as Thing. + *

+ * This api is intended to be used in a Thing device, where the user + * credentials or app admin context is not configured. This Thing must be + * already registered in Kii Cloud. + * + * + * @param vendorThingID vendorThingID of a registered Thing. + * @param password password for the registered Thing. + * @param callbacks The callback methods called when authentication succeeded/failed. + * + * @return return promise object. + *
    + *
  • fulfill callback function: function(thingAuthContext). thingAuthContext is a KiiThingContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsThing("vendor thing id", "password of this thing", { + * success: function(thingAuthContext) { + * // thingAuthContext : KiiThingContext instance + * // Operate entities with thingAuthContext. + * }, + * failure: function(error) { + * // Authentication failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsThing("vendor thing id", "password of this thing").then( + * function(thingAuthContext) { // fulfill callback function + * // thingAuthContext : KiiThingContext instance + * // Operate entities with thingAuthContext. + * + * }, + * function(error) { // reject callback function + * // Authentication failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsThing(vendorThingID: string, password: string, callbacks?: { success(thingAuthContext: KiiThingContext): any; failure(error: Error): any; }): Promise; + + /** + * Create a KiiThingContext reference + *

+ * This api is intended to be used in a Thing device, where the user + * credentials or app admin context is not configured. This Thing must be + * already registered in Kii Cloud. + * + * + * @param thingID thingID of a registered Thing. + * @param token token for the registered Thing. + * @param callbacks The callback methods called when creation succeeded/failed. + * + * @return return promise object. + *
    + *
  • fulfill callback function: function(thingContext). thingContext is a KiiThingContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsThingWithToken("thing_id", "thing_token", { + * success: function(thingContext) { + * // thingContext : KiiThingContext instance + * // Operate entities with thingContext. + * }, + * failure: function(error) { + * // Creation failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsThingWithToken("thing_id", "thing_token").then( + * function(thingContext) { // fulfill callback function + * // thingContext : KiiThingContext instance + * // Operate entities with thingContext. + * + * }, + * function(error) { // reject callback function + * // Creation failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsThingWithToken(thingID: string, token: string, callbacks?: { success(thingContext: KiiThingContext): any; failure(error: Error): any; }): Promise; } /** @@ -3744,7 +3844,7 @@ declare namespace KiiCloud { *
  • response.username is username to use for connecting to the MQTT broker.
  • *
  • response.password is assword to use for connecting to the MQTT broker.
  • *
  • response.mqttTopic is topic to subscribe in the MQTT broker.
  • - *
  • response.host is URL of the MQTT broker host to connect.
  • + *
  • response.host is hostname of the MQTT broker.
  • *
  • response.X-MQTT-TTL is the amount of time in seconds that specifies how long the mqttTopic will be valid, after that the client needs to request new MQTT endpoint info.
  • *
  • response.portTCP is port to connect using plain TCP.
  • *
  • response.portSSL is port to connect using SSL/TLS.
  • @@ -4986,6 +5086,20 @@ declare namespace KiiCloud { */ getDisabled(): boolean; + /** + * Get online status of the thing. + * + * @return true if the thing is online, false otherwise. The return value will be null initially until the thing is connected for the first time. + */ + isOnline(): boolean; + + /** + * Get online status modified date of the thing. + * + * @return online status modified time of this thing. The date will be null initially until the thing is connected for the first time. + */ + getOnlineStatusModifiedAt(): Date; + /** * Register thing in KiiCloud.
    * This API doesnt require users login Anonymous user can register thing. @@ -5794,6 +5908,156 @@ declare namespace KiiCloud { pushSubscription(): KiiPushSubscription; } + /** + * represents a KiiThingContext object + */ + export class KiiThingContext { + /** + * Creates a reference to a bucket in App scope operated by thing. + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsThing("vendorThingID", "password", { + * success: function(thingAuthContext) { + * var bucket = thingAuthContext.bucketWithName("myAppBucket"); + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket in App scope operated by thing. + *

    The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsThing("vendorThingID", "password", { + * success: function(thingAuthContext) { + * var bucket = thingAuthContext.encryptedBucketWithName("myAppBucket"); + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to an object operated by thing using object`s URI. + * + * @param object URI. + * + * @return A working KiiObject instance + * + * @throws If the URI is null, empty or does not have correct format. + */ + objectWithURI(object: string): KiiObject; + + /** + * Creates a reference to a topic in App scope operated by thing. + *

    The Topic will be created/accessed within this app's scope + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in app scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have thingAuthContext instance. + * thingAuthContext.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thingAuthContext.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * // Assume you already have thingAuthContext instance. + * thingAuthContext.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thingAuthContext.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Gets authenticated KiiThing instance. + *
    Returned thing instance only have thingID, vendorThingID and accessToken. + * (vendorThingID is not included when you used + * {@link Kii.authenticateAsThingWithToken()} to obtain KiiThingContext.) + *
    Please execute {@link KiiThing#refresh()} to obtain other properties. + * + * @return return authenticated KiiThing instance. + */ + getAuthenticatedThing(): KiiThing; + + /** + * Instantiate push installation for this thing. + * + * @return push installation object. + */ + pushInstallation(): KiiPushInstallation; + } + /** * Represents a Topic object. */ @@ -6106,6 +6370,25 @@ declare namespace KiiCloud { */ setCountry(value: string): void; + /** + * Get the locale associated with this user + * + * @return + */ + getLocale(): string; + + /** + * Set the locale associated with this user + * The locale argument must be BCP 47 language tag. + * Examples: + * "en": English + * "de-AT": German as used in Austria. + * "zh-Hans-CN": Chinese written in simplified characters as used in China. + * + * @param value The locale to set. + */ + setLocale(value: string): void; + /** * Get the server's creation date of this user * @@ -6196,7 +6479,7 @@ declare namespace KiiCloud { /** * Sets a key/value pair to a KiiUser * - *

    If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects. + *

    If the key already exists, its value will be written over. If key is empty or starting with '_', it will do nothing. Accepted types are any JSON-encodable objects. * * @param key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_) * @param value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc) @@ -7826,6 +8109,7 @@ import KiiServerCodeEntry = KiiCloud.KiiServerCodeEntry; import KiiServerCodeExecResult = KiiCloud.KiiServerCodeExecResult; import KiiSocialConnect = KiiCloud.KiiSocialConnect; import KiiThing = KiiCloud.KiiThing; +import KiiThingContext = KiiCloud.KiiThingContext; import KiiTopic = KiiCloud.KiiTopic; import KiiUser = KiiCloud.KiiUser; import KiiUserBuilder = KiiCloud.KiiUserBuilder; diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index 410139f4b6..c01c54691e 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -162,6 +162,8 @@ knex.select('*').from('users').join('accounts', function() { knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin'])); +knex.raw('select * from users where id = :user_id', { user_id: 1 }); + knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); diff --git a/knex/knex.d.ts b/knex/knex.d.ts index c3ede588e8..70d8cce8cb 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -31,6 +31,7 @@ declare module "knex" { migrate: Knex.Migrator; seed: any; fn: any; + on(eventName: string, callback: Function): Knex.QueryBuilder; } function Knex(config: Knex.Config) : Knex; @@ -66,10 +67,14 @@ declare module "knex" { where: Where; andWhere: Where; orWhere: Where; + whereNot: Where; + andWhereNot: Where; + orWhereNot: Where; whereRaw: WhereRaw; + orWhereRaw: WhereRaw; + andWhereRaw: WhereRaw; whereWrapped: WhereWrapped; havingWrapped: WhereWrapped; - orWhereRaw: WhereRaw; whereExists: WhereExists; orWhereExists: WhereExists; whereNotExists: WhereExists; @@ -83,9 +88,11 @@ declare module "knex" { whereNotNull: WhereNull; orWhereNotNull: WhereNull; whereBetween: WhereBetween; - whereNotBetween: WhereBetween; orWhereBetween: WhereBetween; + andWhereBetween: WhereBetween; + whereNotBetween: WhereBetween; orWhereNotBetween: WhereBetween; + andWhereNotBetween: WhereBetween; // Group by groupBy: GroupBy; @@ -101,6 +108,7 @@ declare module "knex" { // Having having: Having; + andHaving: Having; havingRaw: RawQueryBuilder; orHaving: Having; orHavingRaw: RawQueryBuilder; @@ -249,6 +257,7 @@ declare module "knex" { (value: Value): Raw; (sql: string, ...bindings: Value[]): Raw; (sql: string, bindings: Value[]): Raw; + (sql: string, bindings: Object): Raw; } // @@ -301,6 +310,7 @@ declare module "knex" { interface SchemaBuilder extends Promise { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; + createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; renameTable(oldTableName: string, newTableName: string): Promise; dropTable(tableName: string): SchemaBuilder; hasTable(tableName: string): Promise; @@ -312,6 +322,7 @@ declare module "knex" { interface TableBuilder { increments(columnName?: string): ColumnBuilder; + bigIncrements(columnName?: string): ColumnBuilder; dropColumn(columnName: string): TableBuilder; dropColumns(...columnNames: string[]): TableBuilder; renameColumn(from: string, to: string): ColumnBuilder; diff --git a/knockout.kogrid/ko-grid.d.ts b/knockout.kogrid/ko-grid.d.ts index fe9877e038..a8f3984acf 100644 --- a/knockout.kogrid/ko-grid.d.ts +++ b/knockout.kogrid/ko-grid.d.ts @@ -6,192 +6,270 @@ // These are very definitely preliminary. Please feel free to improve. /// +/// declare namespace kg { - interface DomUtilityService { - UpdateGridLayout(grid: Grid): void; - BuildStyles(grid: Grid): void; - } + interface DomUtilityService { + UpdateGridLayout(grid: Grid): void; + BuildStyles(grid: Grid): void; + } - interface Row { - selected: KnockoutObservable; - entity: EntityType; - } + interface Row { + selected: KnockoutObservable; + entity: EntityType; + } - interface RowFactory { - rowCache: Row[]; - } + interface RowFactory { + rowCache: Row[]; + } - interface SelectionService { - setSelection(row: Row, selected: boolean): void; - multi: boolean; - lastClickedRow: Row; - } + interface SelectionService { + setSelection(row: Row, selected: boolean): void; + multi: boolean; + lastClickedRow: Row; + } - interface Grid { - configureColumnWidths(): void; - rowFactory: RowFactory; - config: GridOptions; - $$selectionPhase: boolean; - selectionService: SelectionService; - } + interface Grid { + configureColumnWidths(): void; + rowFactory: RowFactory; + config: GridOptions; + $$selectionPhase: boolean; + selectionService: SelectionService; + } - interface Plugin { - onGridInit(grid: Grid): void; - } + interface Plugin { + onGridInit(grid: Grid): void; + } - interface GridOptions { - /** Callback for when you want to validate something after selection. */ - afterSelectionChange?(row: Row): void; + interface GridOptions { + /** Callback for when you want to validate something after selection. */ + afterSelectionChange?(row: Row): void; - /** Callback if you want to inspect something before selection, - return false if you want to cancel the selection. return true otherwise. - If you need to wait for an async call to proceed with selection you can - use rowItem.changeSelection(event) method after returning false initially. - Note: when shift+ Selecting multiple items in the grid this will only get called - once and the rowItem will be an array of items that are queued to be selected. */ - beforeSelectionChange?: Function; + /** Callback if you want to inspect something before selection, + return false if you want to cancel the selection. return true otherwise. + If you need to wait for an async call to proceed with selection you can + use rowItem.changeSelection(event) method after returning false initially. + Note: when shift+ Selecting multiple items in the grid this will only get called + once and the rowItem will be an array of items that are queued to be selected. */ + beforeSelectionChange?(row: Row): boolean; - /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ - columnDefs?: ColumnDef[]; + /** To be able to have selectable rows in grid. */ + canSelectRows?:boolean; - /** Column width of columns in grid. */ - columnWidth?: number; + /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ + columnDefs?: ColumnDef[] | KnockoutObservable; - /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ - data?: KnockoutObservableArray; + /** Column width of columns in grid. */ + columnWidth?: number; - /** Row selection check boxes appear as the first column. */ - displaySelectionCheckbox: boolean; + /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ + data?: KnockoutObservableArray; - /** Enable or disable resizing of columns */ - enableColumnResize?: boolean; + /** Row selection check boxes appear as the first column. */ + displaySelectionCheckbox: boolean; - /** Enables the server-side paging feature */ - enablePaging?: boolean; + /** Enable or disable resizing of columns */ + enableColumnResize?: boolean; - /** Enable column pinning */ - enablePinning?: boolean; + /** Enables the server-side paging feature */ + enablePaging?: boolean; - /** Enable drag and drop row reordering. Only works in HTML5 compliant browsers. */ - enableRowReordering?: boolean; + /** Enable drag and drop row reordering. Only works in HTML5 compliant browsers. */ + enableRowReordering?: boolean; - /** To be able to have selectable rows in grid. */ - enableRowSelection?: boolean; + /** Enables or disables sorting in grid. */ + enableSorting?: boolean; - /** Enables or disables sorting in grid. */ - enableSorting?: boolean; + /** filterOptions - + filterText: The text bound to the built-in search box. + useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. + */ + filterOptions?: FilterOptions; - /** filterOptions - - filterText: The text bound to the built-in search box. - useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. - */ - filterOptions?: FilterOptions; + /** Defining the height of the footer in pixels. */ + footerRowHeight?: number; - /** Defining the height of the footer in pixels. */ - footerRowHeight?: number; + /** Show or hide the footer alltogether the footer is enabled by default */ + footerVisible?: boolean; - /** Show or hide the footer alltogether the footer is enabled by default */ - footerVisible?: boolean; + /** Initial fields to group data by. Array of field names, not displayName. */ + groups?: string[]; - /** Initial fields to group data by. Array of field names, not displayName. */ - groups?: string[]; + /** The height of the header row in pixels. */ + headerRowHeight?: number; - /** The height of the header row in pixels. */ - headerRowHeight?: number; + /** Define a header row template for further customization. See github wiki for more details. */ + headerRowTemplate?: string | JQueryGenericPromise; - /** Define a header row template for further customization. See github wiki for more details. */ - headerRowTemplate?: any; + /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. + Useful if you want drag + drop but your users insist on crappy browsers. */ + jqueryUIDraggable?: boolean; - /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. - Useful if you want drag + drop but your users insist on crappy browsers. */ - jqueryUIDraggable?: boolean; + /** Enable the use jqueryUIThemes */ + jqueryUITheme?: boolean; - /** Enable the use jqueryUIThemes */ - jqueryUITheme?: boolean; + /** Prevent unselections when in single selection mode. */ + keepLastSelected?: boolean; - /** Prevent unselections when in single selection mode. */ - keepLastSelected?: boolean; + /** Maintains the column widths while resizing. + Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ + maintainColumnRatios?: any; - /** Maintains the column widths while resizing. - Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ - maintainColumnRatios?: any; + /** Set this to false if you only want one item selected at a time */ + multiSelect?: boolean; - /** Set this to false if you only want one item selected at a time */ - multiSelect?: boolean; + /** pagingOptions - */ + pagingOptions?: PagingOptions; - /** pagingOptions - */ - pagingOptions?: PagingOptions; + /** Array of plugin functions to register in ng-grid */ + plugins?: Plugin[]; - /** Array of plugin functions to register in ng-grid */ - plugins?: Plugin[]; + /** Row height of rows in grid. */ + rowHeight?: number; - /** Row height of rows in grid. */ - rowHeight?: number; + /** Define a row template to customize output. See github wiki for more details. */ + rowTemplate?: string | JQueryGenericPromise; - /** Define a row template to customize output. See github wiki for more details. */ - rowTemplate?: any; + /** Defines the binding to select all at once */ + selectAllState?: KnockoutObservable; - /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ - selectedItems?: KnockoutObservableArray; + /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ + selectedItems?: KnockoutObservableArray; - /** Disable row selections by clicking on the row and only when the checkbox is clicked. */ - selectWithCheckboxOnly?: boolean; + /** Disable row selections by clicking on the row and only when the checkbox is clicked. */ + selectWithCheckboxOnly?: boolean; - /** Enables menu to choose which columns to display and group by. - If both showColumnMenu and showFilter are false the menu button will not display.*/ - showColumnMenu?: boolean; + /** Enables menu to choose which columns to display and group by. + If both showColumnMenu and showFilter are false the menu button will not display.*/ + showColumnMenu?: boolean; - /** Enables display of the filterbox in the column menu. - If both showColumnMenu and showFilter are false the menu button will not display.*/ - showFilter?: boolean; + /** Enables display of the filterbox in the column menu. + If both showColumnMenu and showFilter are false the menu button will not display.*/ + showFilter?: boolean; - /** Show the dropzone for drag and drop grouping */ - showGroupPanel?: boolean; + /** Show the dropzone for drag and drop grouping */ + showGroupPanel?: boolean; - /** Define a sortInfo object to specify a default sorting state. - You can also observe this variable to utilize server-side sorting (see useExternalSorting). - Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/ - sortInfo?: any; + /** Define a sortInfo object to specify a default sorting state. + You can also observe this variable to utilize server-side sorting (see useExternalSorting). + Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/ + sortInfo?: SortInfo | KnockoutObservable; - /** Set the tab index of the Vieport. */ - tabIndex?: number; + /** Set the tab index of the Vieport. */ + tabIndex?: number; - /** Prevents the internal sorting from executing. - The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/ - useExternalSorting?: boolean; - } + /** Prevents the internal sorting from executing. + The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/ + useExternalSorting?: boolean; + } - interface ColumnDef { - /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ - field: string; + type Direction = "asc" | "desc"; - /** Sets the pretty display name of the column. default is the field given */ - displayName?: string; + interface SortInfo { + /** Which column to sort */ + column: SortColumn; - /** Sets the width of the column. Can be a fixed width in pixels as an int (42), string px('42px'), percentage string ('42%'), weighted asterisks (width divided by total number of *'s is all column definition widths) See github wiki for more details. */ - width?: string; - } + /** Which direction to sort */ + direction: Direction; + } + + interface SortColumn { + /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ + field: string; - interface FilterOptions { - filterText?: string; - useExternalFilter?: boolean; - } + /** Sets the sort function for the column. Useful when you have data that is formatted in an unusal way or if you want to sort on an underlying data type. Example: function(a,b){return a > b} */ + sortingAlgorithm?: ((a:any, b:any) => number); + } - interface PagingOptions { - /** pageSizes: list of available page sizes. */ - pageSizes?: number[]; - /** pageSize: currently selected page size. */ - pageSize?: number; - /** totalServerItems: Total items are on the server. */ - totalServerItems?: number; - /** currentPage: the uhm... current page. */ - currentPage?: number; - } + interface ColumnDef { + /** Appends a css class for the column cells */ + cellClass?:string; + + /** + * A function which takes the value of the cell and returns the display value. Useful when your data model has an underlying value which you need to convert to a human readable format. + * @param val + * @returns the display value + * @example function(unixTimeTicks) { return new Date(unixTimeTicks); } + */ + cellFormatter?(val:any): string; + + /**Sets the cell template for the column. See github wiki for more details.*/ + cellTemplate?: string | JQueryGenericPromise; + + /** Sets the pretty display name of the column. default is the field given */ + displayName?: string; + + /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ + field: string; + + /** Sets the template for the column header cell. See github wiki for more details. */ + headerCellTemplate?: string | JQueryGenericPromise; + + /** Appends a css class for the column header. */ + headerClass?: string; + + /**Sets the maximum width of the column.*/ + maxWidth?: number; + + /**Whether or not column is resizable. */ + resizable?: boolean; + + /**Whether or not column is sortable. */ + sortable?: boolean; + + /** Sets the sort function for the column. Useful when you have data that is formatted in an unusal way or if you want to sort on an underlying data type. Example: function(a,b){return a > b} */ + sortFn?: ((a: any, b: any) => number); + + /** Sets the width of the column. Can be a fixed width in pixels as an int (42), string px('42px'), percentage string ('42%'), weighted asterisks (width divided by total number of *'s is all column definition widths) See github wiki for more details. */ + width?: string; + } + + interface FilterOptions { + /** Variable to contain the current search filter */ + filterText?: KnockoutObservable; + + /** Is the filtering internal or does it require a server visit. You should subscribe to filterText to refresh */ + useExternalFilter?: boolean; + + /** Number of seconds to throttle before reapplying search */ + filterThrottle?: number; + } + + interface PagingOptions { + /** pageSizes: list of available page sizes. */ + pageSizes?: KnockoutObservableArray; + + /** pageSize: currently selected page size. */ + pageSize?: KnockoutObservable; + + /** totalServerItems: Total items are on the server. */ + totalServerItems?: KnockoutObservable; + + /** currentPage: the uhm... current page. */ + currentPage?: KnockoutObservable; + } } interface IKg { domUtilityService: kg.DomUtilityService; + + /** Default grid template */ + defaultGridTemplate():string; + + /** Default row template. Can be overriden in GridOptions.rowTemplate */ + defaultRowTemplate(): string; + + /** Default cell template. Can be overriden in GridOptions.cellTemplate */ + defaultCellTemplate(): string; + + /** Default aggregate template */ + aggregateTemplate(): string; + + /** Default headerrow template. Can be overriden in GridOptions.headerRowTemplate */ + defaultHeaderRowTemplate(): string; + + /** Default headercell template. Can be overriden in GridOptions.headerCellTemplate */ + defaultHeaderCellTemplate():string; } declare var kg: IKg; @@ -199,4 +277,3 @@ declare var kg: IKg; declare module "kg" { export = kg; } - diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6e53ac2e25..6321cff0a5 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -523,8 +523,26 @@ interface KnockoutStatic { renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; expressionRewriting: { - bindingRewriteValidators: any; - parseObjectLiteral: { (objectLiteralString: string): any[] } + bindingRewriteValidators: any[]; + twoWayBindings: any; + parseObjectLiteral: (objectLiteralString: string) => any[]; + + /** + Internal, private KO utility for updating model properties from within bindings + property: If the property being updated is (or might be) an observable, pass it here + If it turns out to be a writable observable, it will be written to directly + allBindings: An object with a get method to retrieve bindings in the current execution context. + This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable + (See note below) + key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus' + value: The value to be written + checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if + it is !== existing value on that writable observable + + Note that if you need to write to the viewModel without an observable property, + you need to set ko.expressionRewriting.twoWayBindings[key] = true; *before* the binding evaluation. + */ + writeValueToProperty: (property: KnockoutObservable | any, allBindings: KnockoutAllBindingsAccessor, key: string, value: any, checkIfDifferent?: boolean) => void; }; ///////////////////////////////// diff --git a/koa-compress/koa-compress-tests.ts b/koa-compress/koa-compress-tests.ts new file mode 100644 index 0000000000..564fd53e2c --- /dev/null +++ b/koa-compress/koa-compress-tests.ts @@ -0,0 +1,16 @@ +/// +/// + +import * as Koa from "koa"; +import compress = require("koa-compress"); + +const app = new Koa(); + +app.use(compress({ + filter: (ctype) => { + return /text/i.test(ctype) + }, + threshold: 2048 +})); + +app.listen(80) \ No newline at end of file diff --git a/koa-compress/koa-compress.d.ts b/koa-compress/koa-compress.d.ts new file mode 100644 index 0000000000..c4cd2af582 --- /dev/null +++ b/koa-compress/koa-compress.d.ts @@ -0,0 +1,41 @@ +// Type definitions for koa-compress v2.x +// Project: https://github.com/koajs/compress +// Definitions by: Jerry Chin +// Definitions: https://github.com/hellopao/DefinitelyTyped + +/* =================== USAGE =================== + + import compress = require("koa-compress"); + var Koa = require('koa'); + + var app = new Koa(); + app.use(compress()); + + =============================================== */ +/// +/// + +declare module "koa-compress" { + + import * as Koa from "koa"; + import * as zlib from "zlib"; + + interface CompressOptions extends zlib.ZlibOptions { + /** + * An optional function that checks the response content type to decide whether to compress. By default, it uses compressible. + */ + filter?: (content_type: string) => boolean; + + /** + * Minimum response size in bytes to compress. Default 1024 bytes or 1kb. + */ + threshold?: number + } + + /** + * Compress middleware for Koa + */ + function compress(options?: CompressOptions): { (ctx: Koa.Context, next?: () => any): any }; + + export = compress; +} diff --git a/koa/koa-tests.ts b/koa/koa-tests.ts index e984364973..71814fe4fc 100644 --- a/koa/koa-tests.ts +++ b/koa/koa-tests.ts @@ -9,6 +9,7 @@ app.use((ctx, next) => { const end: any = new Date(); const ms = end - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); + ctx.assert(true, 404, 'Yep!'); }); }); diff --git a/koa/koa.d.ts b/koa/koa.d.ts index 922b243511..b005067b1f 100644 --- a/koa/koa.d.ts +++ b/koa/koa.d.ts @@ -38,7 +38,7 @@ declare module "koa" { toJSON(): any; inspect(): any; throw(code?: any, message?: any): void; - assert(): void; + assert(test: any, status: number, message: string): void; } export interface Request { diff --git a/leaflet-markercluster/leaflet-markercluster.d.ts b/leaflet-markercluster/leaflet-markercluster.d.ts index c9a3140fda..7d8757be03 100644 --- a/leaflet-markercluster/leaflet-markercluster.d.ts +++ b/leaflet-markercluster/leaflet-markercluster.d.ts @@ -51,9 +51,10 @@ declare namespace L { /* * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * Decreasing will make more, smaller clusters. + * Decreasing will make more, smaller clusters. You can also use a function that accepts + * the current map zoom and returns the maximum cluster radius in pixels */ - maxClusterRadius?: number; + maxClusterRadius?: number | ((zoom: number) => number); /* * Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. @@ -82,11 +83,21 @@ declare namespace L { * Function used to create the cluster icon */ iconCreateFunction?: any; + + /* + * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. + */ + chunkedLoading?: boolean; + + /* + * Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms. + */ + chunkDelay?: number; } export class MarkerClusterGroup extends FeatureGroup { - initialize(): void; - initialize(options: MarkerClusterGroupOptions): void; + constructor(); + constructor(options: MarkerClusterGroupOptions); /* * Bulk methods for adding and removing markers and should be favoured over the @@ -121,5 +132,11 @@ declare namespace L { * Returns the array of total markers contained within that cluster. */ getAllChildMarkers(): Marker[]; + + /* + * Zooms to show the given marker (spiderfying if required), + * calls the callback when the marker is visible on the map. + */ + zoomToShowLayer(layer: any, callback: () => void): void; } } diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 04e8a44a36..94cbe8499a 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,11 +1,14 @@ -// Type definitions for Leaflet.js 0.7.3 +// Type definitions for Leaflet.js 1.0.0 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Vladimir Zotov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare namespace L { type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; + type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; } declare namespace L { @@ -16,7 +19,7 @@ declare namespace L { * The position of the control (one of the map corners). See control positions. * Default value: 'bottomright'. */ - position?: string; + position?: PositionString; /** * The HTML text shown before the attributions. Pass false to disable. @@ -219,7 +222,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -254,11 +257,6 @@ declare namespace L { * Sets the radius of a circle marker. Units are in pixels. */ setRadius(radius: number): CircleMarker; - - /** - * Returns a GeoJSON representation of the circle marker (GeoJSON Point Feature). - */ - toGeoJSON(): any; } } @@ -343,12 +341,12 @@ declare namespace L { /** * Sets the position of the control. See control positions. */ - setPosition(position: string): Control; + setPosition(position: PositionString): Control; /** * Returns the current position of the control. */ - getPosition(): string; + getPosition(): PositionString; /** * Adds the control to the map. @@ -400,7 +398,7 @@ declare namespace L { * * Default value: 'topright'. */ - position?: string; // 'topleft' | 'topright' | 'bottomleft' | 'bottomright' + position?: PositionString; /** * The text set on the zoom in button. @@ -550,7 +548,7 @@ declare namespace L { * positions. * Default value: 'topright'. */ - position?: string; + position?: PositionString; } } @@ -1709,8 +1707,9 @@ declare namespace L { /** * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; //////////// //////////// @@ -1739,7 +1738,7 @@ declare namespace L { * * Default value: 'topright'. */ - position?: string; + position?: PositionString; /** * If true, the control will be collapsed into an icon and expanded on mouse hover @@ -2000,7 +1999,7 @@ declare namespace L { export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; /** - * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show + * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show * polyline points that are on the screen or near, increasing performance. Returns * either false or a length-2 array of clipped points. */ @@ -2734,6 +2733,22 @@ declare namespace L.Map { * If true, it will delay moveend event so that it doesn't happen many times in a row. */ debounceMoveend?: boolean; + + /** + * Duration of animated panning, in seconds. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). + * 1.0 means linear animation, the less the more bowed the curve. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + */ + noMoveStart?: boolean; } export interface FitBoundsOptions extends ZoomPanOptions { @@ -2921,7 +2936,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; /** * Marker dragging handler (by both mouse and touch). @@ -3081,7 +3096,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3122,7 +3137,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3384,7 +3399,7 @@ declare namespace L { className?: string; /** - * Sets the radius of a circle marker. + * Sets the radius of a circle marker. */ radius?: number; @@ -3543,7 +3558,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3858,7 +3873,7 @@ declare namespace L { * The position of the control (one of the map corners). See control positions. * Default value: 'bottomleft'. */ - position?: string; + position?: PositionString; /** * Maximum width of the control in pixels. The width is set dynamically to show diff --git a/linq/linq-tests.ts b/linq/linq-tests.ts index fb9c3f3d6e..d30ccc8f8c 100644 --- a/linq/linq-tests.ts +++ b/linq/linq-tests.ts @@ -30,7 +30,7 @@ describe("Linq.js tests", function () { it("Grouping Methods", function () { expect(Enumerable.From(["a","aa","aaa","a","a","aaa"]) .GroupBy((item:string) => item.length) - .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) + .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) .OrderBy(g => g.key) .Select(g => g.key+":"+g.count) .ToString(",")).toBe("1:3,2:1,3:2"); diff --git a/linq/linq.d.ts b/linq/linq.d.ts index facd5d5901..f7417fc8da 100644 --- a/linq/linq.d.ts +++ b/linq/linq.d.ts @@ -49,8 +49,10 @@ declare namespace linq { Scan(seed: any, func: string, resultSelector?: string): Enumerable; Select(selector: ($: T, i: number) => TResult): Enumerable; Select(selector: string): Enumerable; - SelectMany(collectionSelector: ($: any, i: number) => any[], resultSelector?: ($: any, item: any) => any): Enumerable; - SelectMany(collectionSelector: ($: any, i: number) => Enumerable, resultSelector?: ($: any, item: any) => any): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => TResult[]): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => Enumerable): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => TCollectionItem[], resultSelector: ($: T, item: TCollectionItem) => TResult): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => Enumerable, resultSelector: ($: T, item: TCollectionItem) => TResult): Enumerable; SelectMany(collectionSelector: string, resultSelector?: string): Enumerable; Where(predicate: ($ : T, i: number) => boolean): Enumerable; Where(predicate: string): Enumerable; @@ -170,12 +172,12 @@ declare namespace linq { LastIndexOf(item: T): number; // Convert Methods ToArray(): T[]; - ToLookup(keySelector: ($: T) => any, elementSelector?: ($: T) => any, compareSelector?: (key: any) => any): Lookup; - ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; + ToLookup(keySelector: ($: T) => TKey, elementSelector?: ($: T) => TValue, compareSelector?: (key: TKey) => any): Lookup; + ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; ToObject(keySelector: ($: T) => string, elementSelector: ($: T) => any): any; ToObject(keySelector: string, elementSelector: string): any; - ToDictionary(keySelector: ($: T) => any, elementSelector: ($: T) => any, compareSelector?: (key: T) => any): Dictionary; - ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; + ToDictionary(keySelector: ($: T) => TKey, elementSelector: ($: T) => TValue, compareSelector?: (key: TKey) => any): Dictionary; + ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; ToJSON(replacer?: (key: any, value: any) => any, space?: number): string; ToJSON(replacer?: string, space?: number): string; ToString(separator?: string, selector?: ($: T) =>any): string; @@ -211,26 +213,26 @@ declare namespace linq { ThenByDescending(keySelector: string): OrderedEnumerable; } - interface Grouping extends Enumerable { - Key(): any; + interface Grouping extends Enumerable { + Key(): TKey; } - interface Lookup { + interface Lookup { Count(): number; - Get(key: any): Enumerable; - Contains(key: any): boolean; - ToEnumerable(): Enumerable; + Get(key: TKey): Enumerable; + Contains(key: TKey): boolean; + ToEnumerable(): Enumerable>; } - interface Dictionary { - Add(key: any, value: TValue): void; - Get(key: any): any; - Set(key: any, value: TValue): boolean; - Contains(key: any): boolean; + interface Dictionary { + Add(key: TKey, value: TValue): void; + Get(key: TKey): TValue; + Set(key: TKey, value: TValue): boolean; + Contains(key: TKey): boolean; Clear(): void; - Remove(key: any): void; + Remove(key: TKey): void; Count(): number; - ToEnumerable(): Enumerable; + ToEnumerable(): Enumerable>; } interface KeyValuePair { diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index b92de15c89..3948215468 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -7732,6 +7732,53 @@ declare module _ { thisArg?: any): TResult; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + inject( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + inject( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + foldl( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + foldl( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + } + //_.reduceRight interface LoDashStatic { /** diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 115cc4a1e6..f1772191cd 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -8547,6 +8547,21 @@ declare module _ { callback: MemoIterator): TResult; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + accumulator: TResult): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator): LoDashExplicitObjectWrapper; + } + //_.reduceRight interface LoDashStatic { /** diff --git a/mCustomScrollbar/mCustomScrollbar-tests.ts b/mCustomScrollbar/mCustomScrollbar-tests.ts index 7dcf793564..9c5f030679 100644 --- a/mCustomScrollbar/mCustomScrollbar-tests.ts +++ b/mCustomScrollbar/mCustomScrollbar-tests.ts @@ -9,7 +9,8 @@ class SimpleTest { this.element.mCustomScrollbar({ scrollButtons: { - enable: true + enable: true, + scrollAmount: 2 } }); } @@ -22,38 +23,78 @@ class SimpleTestAllParams { this.element = $(".content"); this.element.mCustomScrollbar({ - setWidth: false, - setHeight: false, + setWidth: 22, + setHeight: "40%", + setTop: 0, + setLeft: 22, axis: "y", + scrollbarPosition: "inside", scrollInertia: 950, - mouseWheel: true, - mouseWheelPixels: "auto", autoDraggerLength: true, autoHideScrollbar: false, + autoExpandScrollbar: false, + alwaysShowScrollbar: 0, + snapAmount: [3,3], + snapOffset: 3, + mouseWheel: { + enable: true, + scrollAmount: 1, + axis:"x", + preventDefault: false, + deltaFactor:12, + normalizeDelta:true, + invert: false, + disableOver: ["select","option"] + + }, scrollButtons: { enable: false, - scrollType: "continuous", - scrollSpeed: "auto", - scrollAmount: 40 + scrollType: "stepped", + scrollAmount: 40, + tabindex: 33, + }, + keyboard:{ + enable: true, + scrollAmount:5, + scrollType:"stepless" }, advanced: { updateOnBrowserResize: true, updateOnContentResize: false, + updateOnImageLoad: true, + updateOnSelectorChange: "ul li", + extraDraggableSelectors: ".myClass", + releaseDraggableSelectors: ".myClass", + autoUpdateTimeout:60, autoExpandHorizontalScroll: false, - autoScrollOnFocus: true, - normalizeMouseWheelDelta: false + autoScrollOnFocus: "input", }, contentTouchScroll: true, + documentTouchScroll: false, + callbacks: { + onCreate: () => { }, + onInit: () => { }, onScrollStart: () => { }, onScroll: () => { }, onTotalScroll: () => { }, onTotalScrollBack: () => { }, onTotalScrollOffset: 0, onTotalScrollBackOffset: 0, - whileScrolling: () => { } + whileScrolling: () => { }, + alwaysTriggerOffsets: false, + onOverflowY: () => { }, + onOverflowX: () => { }, + onOverflowYNone: () => {}, + onOverflowXNone: () => {}, + onBeforeUpdate: () => {}, + onUpdate: () => {}, + onImageLoad: () => {}, + onSelectorChange: () => {}, }, - theme: "light" + theme: "light", + live: true, + liveSelector: ".myClass" }); } } diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 08e532d7bf..aa088d6f5c 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -10,16 +10,35 @@ declare namespace MCustomScrollbar { /** * Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string) */ - setWidth?: any; + setWidth?: boolean|number|string; /** * Set the height of your content (overwirtes CSS height), value in pixels (integer) or percentage (string) */ - setHeight?: any; + setHeight?: boolean|number|string; + /** + * Set the initial css top property of content, accepts string values (css top position). + * Example: setTop: "-100px". + */ + setTop? : number|string; + /** + * Set the initial css top property of content, accepts string values (css top position). + * Example: setTop: "-100px". + */ + setLeft? : number|string; /** * Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal). - * Available values: "y", "x", "yx". y -vertical, x - horizontal + * Available values: "y", "x", "yx". y -vertical, x - horizontal, yx - vertical and horizontal */ - axis?: string; + axis?: "x"|"y"|"yx"; + /** + * Set the position of scrollbar in relation to content. + * Available values: "inside", "outside". + * Setting scrollbarPosition: "inside" (default) makes scrollbar appear inside the element. + * Setting scrollbarPosition: "outside" makes scrollbar appear outside the element. + * Note that setting the value to "outside" requires your element (or parent elements) + * to have CSS position: relative (otherwise the scrollbar will be positioned in relation to document’s root element). + */ + scrollbarPosition?: "inside"|"outside"; /** * Always keep scrollbar(s) visible, even when there’s nothing to scroll. * 0 – disable (default) @@ -28,6 +47,18 @@ declare namespace MCustomScrollbar { */ alwaysShowScrollbar?: number; /** + * Make scrolling snap to a multiple of a fixed number of pixels. Useful in cases like scrolling tabular data, + * image thumbnails or slides and you need to prevent scrolling from stopping half-way your elements. + * Note that your elements must be of equal width or height in order for this to work properly. + * To set different values for vertical and horizontal scrolling, use an array: [y,x] + */ + snapAmount?: number|[number,number]; + /** + * Set an offset (in pixels) for the snapAmount option. Useful when for example you need to offset the + * snap amount of table rows by the table header. + */ + snapOffset?: number; + /** * Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar. */ autoExpandScrollbar?: boolean; @@ -47,7 +78,7 @@ declare namespace MCustomScrollbar { * Set the mouse-wheel scrolling amount (in pixels). * The default value "auto" adjusts scrolling amount according to scrollable content length. */ - scrollAmount?: number; + scrollAmount?: "auto"|number; /** * Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present. * Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling. @@ -76,7 +107,27 @@ declare namespace MCustomScrollbar { * Set the tags that disable mouse-wheel when cursor is over them. * Default value: ["select","option","keygen","datalist","textarea"] */ - disableOver?: string[] + disableOver?: string[]; + } + /** + * Keyboard support + */ + keyboard?:{ + /** + * Enable or disable content scrolling via keyboard. + */ + enable?: boolean; + /** + * Set the keyboard arrows scrolling amount (in pixels). + * The default value "auto" adjusts scrolling amount according to scrollable content length. + */ + scrollAmount?: "auto"|number; + /** + * Define the buttons scrolling type/behavior. + * scrollType: "stepless" – continuously scroll content while pressing the button (default) + * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) + */ + scrollType?: "stepless"|"stepped"; } /** * Mouse wheel scrolling pixels amount, value in pixels (integer) or "auto" (script calculates and sets pixels amount according to content length) @@ -96,19 +147,21 @@ declare namespace MCustomScrollbar { */ enable?: boolean; /** - * Scroll buttons scroll type, values: "continuous" (scroll continuously while pressing the button), "pixels" (scrolls by a fixed number of pixels on each click") + * Define the buttons scrolling type/behavior. + * scrollType: "stepless" – continuously scroll content while pressing the button (default) + * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) */ - scrollType?: string; + scrollType?: "stepless"|"stepped"; /** - * Scroll buttons continuous scrolling speed, integer value or "auto" (script calculates and sets the speed according to content length) + * Set a tabindex value for the buttons. */ - scrollSpeed?: number | string; + tabindex?: number; /** * Scroll buttons pixels scrolling amount, value in pixels or "auto" */ - scrollAmount?: number | string; + scrollAmount?: "auto"|number ; } - advanced?: { + advanced?: { /** * Update scrollbars on browser resize (for fluid content blocks and layouts based on percentages), values: true, false. Set to false only when you content has fixed dimensions */ @@ -119,27 +172,75 @@ declare namespace MCustomScrollbar { */ updateOnContentResize?: boolean; /** + * Update scrollbar(s) automatically each time an image inside the element is fully loaded. + * Default value is auto which triggers the function only on "x" and "yx" axis (if needed). + * The value should be true when your content contains images and you need the function to trigger on any axis. + */ + updateOnImageLoad?: "auto"|boolean; + /** + * Add extra selector(s) that’ll release scrollbar dragging upon mouseup, pointerup, touchend etc. + * Example: extraDraggableSelectors: ".myClass, #myID" + */ + extraDraggableSelectors?: string; + /** + * Add extra selector(s) that’ll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc. + * Example: releaseDraggableSelectors: ".myClass, #myID" + */ + releaseDraggableSelectors?: string; + /** + * Set the auto-update timeout in milliseconds. + * Default timeout: 60 + */ + autoUpdateTimeout?: number; + /** + * Update scrollbar(s) automatically when the amount and size of specific selectors changes. + * Useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size. + * For example, setting updateOnSelectorChange: "ul li" will update scrollbars each time list-items inside the element are changed. + * Setting the value to true, will update scrollbars each time any element is changed. + * To disable (default) set to false. + */ + updateOnSelectorChange?: string|boolean; + /** * Auto-expanding content's width on horizontal scrollbars, values: true, false. Set to true if you have horizontal scrollbr on content that change on-the-fly. Demo contains * blocks with images and horizontal scrollbars that use this option parameter */ autoExpandHorizontalScroll?: boolean; /** - * Auto-scrolling on elements that have focus (e.g. scrollbar automatically scrolls to form text fields when the TAB key is pressed), values: true, false + * Set the list of elements/selectors that will auto-scroll content to their position when focused. + * For example, when pressing TAB key to focus input fields, if the field is out of the viewable area the content + * will scroll to its top/left position (same bahavior with browser’s native scrollbar). + * To completely disable this functionality, set autoScrollOnFocus: false. + * Default: + * "input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']" */ - autoScrollOnFocus?: boolean; + autoScrollOnFocus?: boolean|string; /** * Normalize mouse wheel delta (-1/1), values: true, false */ normalizeMouseWheelDelta?: boolean; } - /** - * Additional scrolling method by touch-swipe content (for touch enabled devices), value: true, false - */ - contentTouchScroll?: boolean; + /** + * Enable or disable content touch-swipe scrolling for touch-enabled devices. + * To completely disable, set contentTouchScroll: false. + * Integer values define the axis-specific minimum amount required for scrolling momentum (default: 25). + */ + contentTouchScroll?: boolean|number; + /** + * Enable or disable document touch-swipe scrolling for touch-enabled devices. + */ + documentTouchScroll?: boolean; /** * All of the following callbacks option have examples in the callback demo - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/callbacks_example.html */ callbacks?: { + /** + * A function to call when plugin markup is created. + */ + onCreate?: () => void; + /** + * A function to call when scrollbars have initialized + */ + onInit?: () => void; /** * User defined callback function, triggered on scroll start event. You can call your own function(s) each time a scroll event begins */ @@ -176,11 +277,56 @@ declare namespace MCustomScrollbar { * Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached. */ alwaysTriggerOffsets?: boolean; + /** + * A function to call when content becomes long enough and vertical scrollbar is added. + */ + onOverflowY?: () => void; + /** + * A function to call when content becomes wide enough and horizontal scrollbar is added. + */ + onOverflowX?: () => void; + /** + * A function to call when content becomes short enough and vertical scrollbar is removed. + */ + onOverflowYNone?: () => void; + /** + * A function to call when content becomes narrow enough and horizontal scrollbar is removed. + */ + onOverflowXNone?: () => void; + /** + * A function to call right before scrollbar(s) are updated. + */ + onBeforeUpdate?: () => void; + /** + * A function to call when scrollbar(s) are updated. + */ + onUpdate?: () => void; + /** + * A function to call each time an image inside the element is fully loaded and scrollbar(s) are updated. + */ + onImageLoad?: () => void; + /** + * A function to call each time a type of element is added, removed or changes its size and scrollbar(s) are updated. + */ + onSelectorChange?: () => void; } - /** - * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html - */ - theme?: string; + /** + * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html + */ + theme?: string; + /** + * Enable or disable applying scrollbar(s) on all elements matching the current selector, now and in the future. + * Set live: true when you need to add scrollbar(s) on elements that do not yet exist in the page. + * These could be elements added by other scripts or plugins after some action by the user takes place (e.g. lightbox markup may not exist untill the user clicks a link). + * If you need at any time to disable or enable the live option, set live: "off" and "on" respectively. + * You can also tell the script to disable live option after the first invocation by setting live: "once". + */ + live?: string|boolean; + /** + * Set the matching set of elements (instead of the current selector) to add scrollbar(s), now and in the future. + */ + liveSelector?: string; + } interface ScrollToParameterOptions { diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 198f49f7bc..367aae4e11 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -641,6 +641,7 @@ declare namespace __MaterialUI { touchRippleColor?: string; touchRippleOpacity?: number; type?: string; + containerElement?: React.ReactNode | string; } interface EnhancedButtonProps extends React.HTMLAttributes, SharedEnhancedButtonProps { diff --git a/mdns/mdns.d.ts b/mdns/mdns.d.ts index d159ee7dba..63e1e7b72a 100644 --- a/mdns/mdns.d.ts +++ b/mdns/mdns.d.ts @@ -49,6 +49,9 @@ declare namespace MDNS { interface Browser extends NodeJS.EventEmitter { start():any; stop():any; + on(event:string, listener:Function):this; + on(event:'serviceUp', listener:(info:Service)=>void):this; + on(event:'serviceDown', listener:(info:Service)=>void):this; } interface BrowserStatic { diff --git a/meteor/README.md b/meteor/README.md index d9d7898ffb..7c8aa5cb1d 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -1,4 +1,13 @@ -# Meteor Type Definitions +# Meteor Type Definitions [DEPRECATED] + +## Deprecated + +These definitions for Meteor are now deprecated. They should still work for versions of Meteor up to 1.2.1. + +The canonical TypeScript definitions for Meteor can now be found using the NPM [Typings definition manager](https://www.npmjs.com/package/typings). If you prefer to view the definitions directly, or contribute to them, they can be found here: . + + +## Description These are the definitions for version 1.3 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index bc877bdea0..4b5a154794 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -650,16 +650,16 @@ Accounts.emailTemplates.siteName = "AwesomeSite"; Accounts.emailTemplates.from = "AwesomeSite Admin "; Accounts.emailTemplates.headers = { asdf: 'asdf', qwer: 'qwer' }; -Accounts.emailTemplates.enrollAccount.subject = function (user) { +Accounts.emailTemplates.enrollAccount.subject = function (user: Meteor.User) { return "Welcome to Awesome Town, " + user.profile.name; }; -Accounts.emailTemplates.enrollAccount.html = function (user, url) { +Accounts.emailTemplates.enrollAccount.html = function (user: Meteor.User, url: string) { return "

    Some html here

    "; }; Accounts.emailTemplates.enrollAccount.from = function() { return "asdf@asdf.com"; }; -Accounts.emailTemplates.enrollAccount.text = function (user, url) { +Accounts.emailTemplates.enrollAccount.text = function (user: Meteor.User, url: string) { return "You have been selected to participate in building a better future!" + " To activate your account, simply click the link below:\n\n" + url; diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index d0108263ec..c6185aa32b 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -66,6 +66,21 @@ function test_test() { }); } +function test_specify() { + + specify('does something', () => { }); + + specify('does something', (done) => { done(); }); + + specify.only('does something', () => { }); + + specify.skip('does something', () => { }); + + specify('does something', function () { + this.timeout(2000); + }); +} + function test_before() { before(() => { }); diff --git a/mocha/mocha.d.ts b/mocha/mocha.d.ts index 56c6cdba82..eb167c83c9 100644 --- a/mocha/mocha.d.ts +++ b/mocha/mocha.d.ts @@ -44,6 +44,7 @@ declare var it: Mocha.ITestDefinition; declare var xit: Mocha.ITestDefinition; // alias for `it` declare var test: Mocha.ITestDefinition; +declare var specify: Mocha.ITestDefinition; declare function before(action: () => void): void; diff --git a/node-fetch/node-fetch-tests.ts b/node-fetch/node-fetch-tests.ts new file mode 100644 index 0000000000..28d7ff7766 --- /dev/null +++ b/node-fetch/node-fetch-tests.ts @@ -0,0 +1,60 @@ +/// + +import fetch = require('node-fetch'); + +function test_fetchUrlWithOptions() { + var headers = new _fetch.Headers(); + headers.append("Content-Type", "application/json"); + var requestOptions: _fetch.RequestInit = { + method: "POST", + headers: headers, + mode: 'same-origin', + credentials: 'omit', + cache: 'default', + redirect: 'manual' + }; + handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); +} + +function test_fetchUrlWithHeadersObject() { + var requestOptions: _fetch.RequestInit = { + method: "POST", + headers: { + 'Content-Type': 'application/json' + } + }; + handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); +} + +function test_fetchUrl() { + handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php")); +} + +function test_fetchUrlWithRequestObject() { + var requestOptions: _fetch.RequestInit = { + method: "POST", + headers: { + 'Content-Type': 'application/json' + } + }; + var request: _fetch.Request = new _fetch.Request("http://www.andlabs.net/html5/uCOR.php", requestOptions); + handlePromise(fetch(request)); +} + +function test_globalFetchVar() { + fetch('http://test.com', {}) + .then(response => { + // for test only + }); +} + +function handlePromise(promise: Promise<_fetch.Response>) { + promise.then((response) => { + if (response.type === 'basic') { + // for test only + } + return response.text(); + }).then((text) => { + console.log(text); + }); +} diff --git a/node-fetch/node-fetch.d.ts b/node-fetch/node-fetch.d.ts new file mode 100644 index 0000000000..5cf41ea992 --- /dev/null +++ b/node-fetch/node-fetch.d.ts @@ -0,0 +1,95 @@ +// Type definitions for node-fetch based on whatwg-fetch +// Project: https://github.com/bitinn/node-fetch +// Definitions by: Torsten Werner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module _fetch { + + class Request extends Body { + constructor(input: string | Request, init?: RequestInit); + method: string; + url: string; + headers: Headers; + context: RequestContext; + referrer: string; + mode: RequestMode; + redirect: RequestRedirect; + credentials: RequestCredentials; + cache: RequestCache; + } + + interface RequestInit { + method?: string; + headers?: HeaderInit | { [index: string]: string }; + body?: BodyInit; + mode?: RequestMode; + redirect?: RequestRedirect; + credentials?: RequestCredentials; + cache?: RequestCache; + } + + type RequestContext = + "audio" | "beacon" | "cspreport" | "download" | "embed" | + "eventsource" | "favicon" | "fetch" | "font" | "form" | "frame" | + "hyperlink" | "iframe" | "image" | "imageset" | "import" | + "internal" | "location" | "manifest" | "object" | "ping" | "plugin" | + "prefetch" | "script" | "serviceworker" | "sharedworker" | + "subresource" | "style" | "track" | "video" | "worker" | + "xmlhttprequest" | "xslt"; + type RequestMode = "same-origin" | "no-cors" | "cors"; + type RequestRedirect = "follow" | "error" | "manual"; + type RequestCredentials = "omit" | "same-origin" | "include"; + type RequestCache = + "default" | "no-store" | "reload" | "no-cache" | + "force-cache" | "only-if-cached"; + + class Headers { + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string; + getAll(name: string): Array; + has(name: string): boolean; + set(name: string, value: string): void; + forEach(callback: (value: string, name: string) => void): void; + } + + class Body { + bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + json(): Promise; + text(): Promise; + } + class Response extends Body { + constructor(body?: BodyInit, init?: ResponseInit); + static error(): Response; + static redirect(url: string, status: number): Response; + type: ResponseType; + url: string; + status: number; + ok: boolean; + statusText: string; + headers: Headers; + clone(): Response; + } + + type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + + interface ResponseInit { + status: number; + statusText?: string; + headers?: HeaderInit; + } + + type HeaderInit = Headers | Array; + type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; + type RequestInfo = Request | string; + + function fetch(url: string | Request, init?: RequestInit): Promise; +} + +declare module "node-fetch" { + export = _fetch.fetch; +} diff --git a/node/node.d.ts b/node/node.d.ts index bffb007c4b..a8b7f2fd20 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1399,6 +1399,7 @@ declare module "fs" { export interface ReadStream extends stream.Readable { close(): void; + destroy(): void; } export interface WriteStream extends stream.Writable { close(): void; @@ -1827,7 +1828,147 @@ declare module "tls" { var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; + + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + export interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + export class TLSSocket extends stream.Duplex { + /** + * Returns the bound address, the address family name and port of the underlying socket as reported by + * the operating system. + * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + */ + address(): { port: number; family: string; address: string }; + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param {boolean} detailed - If true; the full chain with issuer property will be returned. + * @returns {any} - An object representing the peer's certificate. + */ + getPeerCertificate(detailed?: boolean): { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: any; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + }; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns {any} - TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * The string representation of the local IP address. + */ + localAddress: string; + /** + * The numeric representation of the local port. + */ + localPort: string; + /** + * The string representation of the remote IP address. + * For example, '74.125.127.100' or '2001:4860:a005::68'. + */ + remoteAddress: string; + /** + * The string representation of the remote IP family. 'IPv4' or 'IPv6'. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: TlsOptions, callback: (err: Error) => any): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns {boolean} - Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + } + export interface TlsOptions { host?: string; port?: number; diff --git a/node_zeromq/zmq-tests.ts b/node_zeromq/zmq-tests.ts index a62d97a6ca..0c7e031a12 100644 --- a/node_zeromq/zmq-tests.ts +++ b/node_zeromq/zmq-tests.ts @@ -42,3 +42,12 @@ function test5() { sock.monitor(); sock.monitor(10); } + +function test6() { + var sock = zmq.socket(zmq.types.dealer); + sock.bind('tcp://127.0.0.1', err => { + sock.send("some work"); + }); + sock.pause(); + sock.resume(); +} diff --git a/node_zeromq/zmq.d.ts b/node_zeromq/zmq.d.ts index 636a014aa6..838c3c6cd4 100644 --- a/node_zeromq/zmq.d.ts +++ b/node_zeromq/zmq.d.ts @@ -184,6 +184,19 @@ declare module 'zmq' { */ on(eventName: string, callback: (...buffer: Buffer[]) => void): void; + /** + * Set socket to pause mode + * no data will be emit until resume() is called + * all send() calls will be queued + */ + pause(): void; + + /** + * Set a socket back to normal work mode + * triggers a _flushReads and _flushWrites + */ + resume(): void; + // Socket Options _fd: any; _ioevents: any; diff --git a/nw.js/nw.js-tests.ts b/nw.js/nw.js-tests.ts new file mode 100644 index 0000000000..585b7ebe3c --- /dev/null +++ b/nw.js/nw.js-tests.ts @@ -0,0 +1,352 @@ +/// +/* + * nw.App Tests + */ +var argv = nw.App.argv; +var fullArgv = nw.App.fullArgv; +var filteredArgv = nw.App.filteredArgv; +var dataPath = nw.App.dataPath; +var manifest = nw.App.manifest; + +nw.App.clearCache(); +nw.App.closeAllWindows(); +nw.App.crashBrowser(); +nw.App.crashRenderer(); +nw.App.getProxyForURL( 'https://github.com/alirdn' ); +nw.App.setProxyConfig( 'http=foopy:80;ftp=foopy2' ); +nw.App.quit(); +nw.App.addOriginAccessWhitelistEntry( 'http://github.com/', 'chrome-extension', location.host, true ); +nw.App.removeOriginAccessWhitelistEntry( 'http://github.com/', 'chrome-extension', location.host, true ); + +/* + * Note: + * nw.App.registerGlobalHotKey() tested in Shortcut Tests + * nw.App.unregisterGlobalHotKey() tested in Shortcut Tests + * */ + +nw.App.on( 'open', function ( args ) { + console.log( args ); +}); + +nw.App.on( 'reopen', function () { + console.log( 'reopened' ); +}); + +/** + * nw.Clipboard Tests + */ +// get the system clipboard +var clipboard = nw.Clipboard.get(); +// Read from clipboard +var text = clipboard.get( 'text' ); +console.log( text ); + +// Or write something +clipboard.set( 'I love NW.js :)', 'text' ); + +// And clear it! +clipboard.clear(); + +/** + * nw.Menu Tests + */ +// Create an empty context menu +var menu = new nw.Menu(); + +// Add some items +menu.append( new nw.MenuItem( { label: 'Item A' }) ); +menu.append( new nw.MenuItem( { label: 'Item B' }) ); +menu.append( new nw.MenuItem( { type: 'separator' }) ); +menu.append( new nw.MenuItem( { label: 'Item C' }) ); + +// Remove one item +menu.removeAt( 1 ); + +// Popup as context menu +menu.popup( 10, 10 ); + +// Iterate menu's items +for ( var i = 0; i < menu.items.length; ++i ) { + console.log( menu.items[i] ); +} +// Create an empty menubar +var menu = new nw.Menu( { type: 'menubar' }); + +// Create a submenu as the 2nd level menu +var submenu = new nw.Menu(); +submenu.append( new nw.MenuItem( { label: 'Item A' }) ); +submenu.append( new nw.MenuItem( { label: 'Item B' }) ); + +// Create and append the 1st level menu to the menubar +menu.append( new nw.MenuItem( { + label: 'First Menu', + submenu: submenu +}) ); + +// Assign it to `window.menu` to get the menu displayed +nw.Window.get().menu = menu; + +/** + * nw.MenuItem Tests + */ +var item: any; + +// Create a separator +item = new nw.MenuItem( { type: 'separator' }); + +// Create a normal item with label and icon +item = new nw.MenuItem( { + type: "normal", + label: "I'm a menu item", + icon: "img/icon.png" +}); + +// Or you can omit the 'type' field for normal items +item = new nw.MenuItem( { label: 'Simple item' }); + +// Bind a callback to item +item = new nw.MenuItem( { + label: "Click me", + click: function () { + console.log( "I'm clicked" ); + }, + key: "s", + modifiers: "ctrl+alt", +}); + +// You can have submenu! +var submenu = new nw.Menu(); +submenu.append( new nw.MenuItem( { label: 'Item 1' }) ); +submenu.append( new nw.MenuItem( { label: 'Item 2' }) ); +submenu.append( new nw.MenuItem( { label: 'Item 3' }) ); +item.submenu = submenu; + +// And everything can be changed at runtime +item.label = 'New label'; +item.click = function () { + console.log( 'New click callback' ); +}; + +/** + * nw.Screen Tests + */ +//init must be called once during startup, before any function to nw.Screen can be called +nw.Screen.Init(); + +var screenCB = { + onDisplayBoundsChanged: function ( screen: any ) { + console.log( 'displayBoundsChanged', screen ); + }, + + onDisplayAdded: function ( screen: any ) { + console.log( 'displayAdded', screen ); + }, + + onDisplayRemoved: function ( screen: any ) { + console.log( 'displayRemoved', screen ) + } +}; + +// listen to screen events +nw.Screen.on( 'displayBoundsChanged', screenCB.onDisplayBoundsChanged ); +nw.Screen.on( 'displayAdded', screenCB.onDisplayAdded ); +nw.Screen.on( 'displayRemoved', screenCB.onDisplayRemoved ); + +/** + * nw.Screen.chooseDesktopMedia() Tests + */ +nw.Screen.Init(); // you only need to call this once +nw.Screen.chooseDesktopMedia( ["window", "screen"], + function ( streamId ) { + var vid_constraint = { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: streamId, + maxWidth: 1920, + maxHeight: 1080 + }, + optional: [] + }; + //navigator.webkitGetUserMedia( { audio: false, video: constraint }, success_func, fallback_func ); + } +); + +/** + * nw.Screen.DesktopCaptureMonitor Tests + */ +var dcm = nw.Screen.DesktopCaptureMonitor; +nw.Screen.Init(); +dcm.on( "added", function ( id, name, order, type ) { + //select first stream and shutdown + var constraints = { + audio: { + mandatory: { + chromeMediaSource: "system", + chromeMediaSourceId: dcm.registerStream( id ) + } + }, + video: { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: dcm.registerStream( id ) + } + } + }; + + // TODO: call getUserMedia with contraints + + dcm.stop(); +}); + +dcm.on( "removed", function ( id ) { +}); +dcm.on( "orderchanged", function ( id, new_order, old_order ) { +}); +dcm.on( "namechanged", function ( id, name ) { +}); +dcm.on( "thumbnailchanged", function ( id, thumbnail ) { +}); +dcm.start( true, true ); + +/** + * nw.Shell Tests + */ +// Open URL with default browser. +nw.Shell.openExternal( 'https://github.com/nwjs/nw.js' ); + +// Open a text file with default text editor. +nw.Shell.openItem( 'test.txt' ); + +// Show a file in parent folder with file manager. +nw.Shell.showItemInFolder( 'test.txt' ); + +/** + * nw.Shortcut Tests + */ +var option = { + key: "Ctrl+Shift+A", + active: function () { + console.log( "Global desktop keyboard shortcut: " + this.key + " active." ); + }, + failed: function ( msg: any ) { + // :(, fail to register the |key| or couldn't parse the |key|. + console.log( msg ); + } +}; + +// Create a shortcut with |option|. +var shortcut = new nw.Shortcut( option ); + +// Register global desktop shortcut, which can work without focus. +nw.App.registerGlobalHotKey( shortcut ); + +// If register |shortcut| successfully and user struck "Ctrl+Shift+A", |shortcut| +// will get an "active" event. + +// You can also add listener to shortcut's active and failed event. +shortcut.on( 'active', function () { + console.log( "Global desktop keyboard shortcut: " + this.key + " active." ); +}); + +shortcut.on( 'failed', function ( msg: any ) { + console.log( msg ); +}); + +// Unregister the global desktop shortcut. +nw.App.unregisterGlobalHotKey( shortcut ); + +/** + * nw.Tray Tests + */ +// Create a tray icon +var tray = new nw.Tray( { title: 'Tray', icon: 'img/icon.png' }); + +// Give it a menu +var menu = new nw.Menu(); +menu.append( new nw.MenuItem( { type: 'checkbox', label: 'box1' }) ); +tray.menu = menu; + +// Remove the tray +tray.remove(); +tray = null; + +/** + * nw.Window Tests + */ +// Get the current window +var win = nw.Window.get(); + +// Listen to the minimize event +win.on( 'minimize', function () { + console.log( 'Window is minimized' ); +}); + +// Minimize the window +win.minimize(); + +// Unlisten the minimize event +win.removeAllListeners( 'minimize' ); + +// Create a new window and get it +nw.Window.open( 'https://github.com', {}, function ( new_win ) { + // And listen to new window's focus event + new_win.on( 'focus', function () { + console.log( 'New window is focused' ); + }); +}); + +// Get the current window +var win = nw.Window.get(); + +// Create a new window and get it +nw.Window.open( 'https://github.com/nwjs/nw.js', {}, function ( new_win ) { + // do something with the newly created window +}); + +win.on( 'close', function () { + this.hide(); // Pretend to be closed already + console.log( "We're closing..." ); + this.close( true ); // then close it forcely +}); + +win.close(); + +// png as base64string +win.capturePage( function ( base64string ) { + // do something with the base64string +}, { format: 'png', datatype: 'raw' }); + +// png as node buffer +win.capturePage( function ( buffer ) { + // do something with the buffer +}, { format: 'png', datatype: 'buffer' }); + +// Open a new window. +nw.Window.open( 'popup.html', {}, function ( win ) { + + // Release the 'win' object here after the new window is closed. + win.on( 'closed', function () { + win = null; + }); + + // Listen to main window's close event + nw.Window.get().on( 'close', function () { + // Hide the window to give user the feeling of closing immediately + this.hide(); + + // If the new window is still open then close it. + if ( win != null ) + win.close( true ); + + // After closing the new window, close the main window. + this.close( true ); + }); + +}); + +nw.Window.get().on( 'new-win-policy', function ( frame, url, policy ) { + // do not open the window + policy.ignore(); + // and open it in external browser + nw.Shell.openExternal( url ); +}); diff --git a/nw.js/nw.js.d.ts b/nw.js/nw.js.d.ts new file mode 100644 index 0000000000..6ae2582e50 --- /dev/null +++ b/nw.js/nw.js.d.ts @@ -0,0 +1,1883 @@ +// Type definitions for nw.js v0.13.x and later +// Project: http://nwjs.io +// Definitions by: Alireza Dabiri Nejad +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Helpers class and interfaces defined here, to make `nw` module cleaner. + */ +declare module NWJS_Helpers { + + /** + * Node.js v6.x EventEmitter Class + */ + class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + + static listenerCount( emitter: EventEmitter, event: string ): number; // deprecated + static defaultMaxListeners: number; + + addListener( event: string, listener: Function ): this; + + on( event: string, listener: Function ): this; + + once( event: string, listener: Function ): this; + + removeListener( event: string, listener: Function ): this; + + removeAllListeners( event?: string ): this; + + setMaxListeners( n: number ): this; + + getMaxListeners(): number; + + listeners( event: string ): Function[]; + + emit( event: string, ...args: any[] ): boolean; + + listenerCount( type: string ): number; + } + + /** + * The clipboard object. + */ + interface clip { + + /** + * Write `data` of `type` to the clipboard. + * + * @param data {string} the data to write to the clipboard + * @param type {string} (Optional) the type of the data. Support text, png, jpeg, html and rtf. By default, type is set to "text". + * @param raw {boolean} (Optional) requiring raw image data. This option is only valid if type is png or jpeg. By default, raw is set to false. + */ + set( data: string, type?: string, raw?: boolean ): void; + + /** + * Get the data of `type` from clipboard. + * + * @param type {string} (Optional) the type of the data. Support text, png, jpeg, html and rtf. By default, type is set to "text". + * @param raw {boolean} (Optional) requiring raw image data. This option is only valid if type is png or jpeg. + * @returns {string} the data retrieved from the clipboard. + */ + get( type?: string, raw?: boolean ): string; + + /** + * Get an array contains list of available types of data in clipboard currenly. + * You can use the returned list as a suggestion to get the right data from clipboard. + * + * @returns {string[]} List of available types of data in clipboard currenly. + */ + readAvailableTypes(): string[]; + + /** + * Clear the clipboard. + */ + clear(): void; + } + + /** + * Object that contains options to use while creation of nw.Menu. example: new nw.Menu(MenuOption) + */ + interface MenuOption { + /** + * {string} (Optional) two types are accepted by this method: "menubar" or "contextmenu". The value is set to "contextmenu" by default. + */ + type: string; + } + + /** + * Options to modify default `edit` and `window` MenuItems in Mac. + */ + interface CreateMacBuiltinOption { + + /** + * {Boolean} (Optional) do not populate the Edit menu + */ + hideEdit?: boolean; + + /** + * {Boolean} (Optional) do not populate the Window menu + */ + hideWindow?: boolean; + } + + /** + * Options for MenuItem. + */ + interface MenuItemOption { + + /** + * {string} (Optional) Label for normal item or checkbox + */ + label?: string; + + /** + * {string} (Optional) Icon for normal item or checkbox + */ + icon?: string; + + /** + * {string} (Optional) Tooltip for normal item or checkbox + */ + tooltip?: string; + + /** + * {string} (Optional) The type of the item. Three types are accepted: normal, checkbox, separator + */ + type?: string | "normal" | "checkbox" | "separator"; + + /** + * {Function} (Optional) The callback function when item is triggered by mouse click or keyboard shortcut + */ + click?: Function; + + /** + * {boolean} (Optional) Whether the item is enabled or disabled. It"s set to true by default. + */ + enabled?: boolean; + + /** + * {boolean} (Optional) Whether the checkbox is checked or not. It"s set to false by default. + */ + checked?: boolean; + + /** + * {nw.Menu} (Optional) A submenu + */ + submenu?: nw.Menu; + + /** + * {string} (Optional) The key of the shortcut + */ + key?: string; + + /** + * {string} (Optional) The modifiers of the shortcut + */ + modifiers?: string; + } + + /** + * nw.Screen screen object + */ + interface screen { + + /** + * Unique id for a screen + */ + id: number, + + /** + * Physical screen resolution, can be negative, not necessarily start from 0,depending on screen arrangement + */ + bounds: { + x: number, + y: number, + width: number, + height: number + }, + + /** + * Useable area within the screen bound + */ + work_area: { + x: number, + y: number, + width: number, + height: number + }, + + scaleFactor: number, + + isBuiltIn: boolean, + + rotation: number, + + touchSupport: number + } + + /** + * This API behaves similar functions as Screen.chooseDesktopMedia. But it doesn"t have GUI. + */ + interface DesktopCaptureMonitor extends EventEmitter { + + /** + * Boolean of whether the DesktopCaptureMonitor is started. + */ + started: boolean; + + /** + * The DesktopCaptureMonitor will start monitoring the system and trigger the the events. + * + * @param should_include_screens {boolean} Whether should include screens + * @param should_include_windows {boolean} Whether should include windows + */ + start( should_include_screens: boolean, should_include_windows: boolean ): void; + + /** + * The DesktopCaptureMonitor will stop monitoring the system. + */ + stop(): void; + + /** + * Register and return a valid stream id passed into chromeMediaSourceId in getUserMedia constraints. + * + * @param id {string} valid stream id. + */ + registerStream( id: string ): void; + + on( event: string, listener: Function ): this; + + /** + * Emit when a new source was added. + * + * @param event {string} Event name + * @param listener {Function(id?,name?,order?,type?,primary?)} The callback that handles the `added` event. + * - (optional) id {string} Is the media id. + * - (optional) name {string} Is the title of the window or screen. + * - (optional) order {number} Is the z-order of the windows, if screens are selected they will appear first. + * - (optional) type {string} Type of the stream: "screen", "window", "other" or "unknown". + * - (optional) primary {boolean} This will be true if the source is the primary monitor. (Windows OS only) + */ + on( event: 'added', listener: ( id?: string, name?: string, order?: number, type?: string, primary?: boolean ) => any ): this; + + /** + * Emit when a source was removed. + * + * @param event {string} Event name + * @param listener {Function(order?)} The callback that handles the `remove` event. + * - (optional) order {number} Is the order of the media source that is no longer capturable. + */ + on( event: 'removed', listener: ( order?: number ) => any ): this; + + /** + * Emit when the Z-order of a source changed (this may change for windows as others are focused). + * + * @param event {string} Event name + * @param listener {Function(id?,new_order?,old_order?)} The callback that handles the `orderchanged` event. + * - (optional) id {string} Is the media id of the screen or window that has changed z-order. + * - (optional) new_order {number} Is the new z-order. + * - (optional) old_order {number} Is the old z-order. + */ + on( event: 'orderchanged', listener: ( id?: string, new_order?: number, old_order?: number ) => any ): this; + + /** + * Emit when the name of the source has changed. This can happen when a window changes title. + * + * @param event {string} Event name + * @param listener {Function(id?,new_order?,old_order?)} The callback that handles the `namechanged ` event. + * - (optional) id {string} Is the media id of the screen or window that has a name changed. + * - (optional) name {string} Is the new name of the screen or window. + */ + on( event: 'namechanged', listener: ( id?: string, name?: string ) => any ): this; + + /** + * Emit when the thumbnail of a source changed. + * + * @param event {string} Event name + * @param listener {Function(id?,new_order?,old_order?)} The callback that handles the `thumbnailchanged ` event. + * - (optional) id {string} Is the media id of the screen or window that has an updated thumbnail. + * - (optional) name {string} Is the base64 encoded png of the thumbnail. + */ + on( event: 'thumbnailchanged', listener: ( id?: string, thumbnail?: string ) => any ): this; + } + + /** + * Shortcut option is an object contains initial settings for the Shortcut. + */ + interface ShortcutOption { + + /** + * {Function} (Optional) A callback when the hotkey is triggered. + */ + active: Function; + + /** + * {Function} (Optional) A callback when failed to register the hotkey. + * + * @param msg {string} Failure message + */ + failed: ( msg?: string ) => any; + + /** + * {string} Key combinations of the shortcut, such as "ctrl+shift+a". + */ + key: string; + } + + /** + * Option for tray that contains initial settings for the Tray. + */ + interface TrayOption { + + /** + * {string} title + */ + title?: string; + + /** + * {string} tooltip + */ + tooltip?: string; + + /** + * {string} icon + */ + icon?: string; + + /** + * {string} alternate + */ + alticon?: string; + + /** + * {boolean} whether icons are templates + */ + iconsAreTemplates?: boolean; + + /** + * {Menu} popup menu + */ + menu?: nw.Menu; + } + + /** + * Options for nw.Window.get().print(). + */ + interface PrintOption { + + /** + * The device name of the printer + */ + printer: string; + + /** + * The path of the output PDF when printing to PDF + */ + pdf_path: string; + + /** + * Whether to enable header and footer + */ + headerFooterEnabled: boolean; + + /** + * Whether to use landscape or portrait + */ + landscape: boolean; + + /** + * The paper size spec + * example: 'mediaSize':{'name': 'CUSTOM', 'width_microns': 279400, 'height_microns': 215900, 'custom_display_name':'Letter', 'is_default': true} + */ + mediaSize: JSON; + + /** + * Whether to print CSS backgrounds + */ + shouldPrintBackgrounds: boolean; + } + + /** + * Config for nw.Window.get().capturePage(). + */ + interface CapturePageConfig { + + /** + * (Optional) The image format used to generate the image. It supports two formats: "png" and "jpeg". If ignored, it’s "jpeg" by default. + */ + format?: string + + /** + * (Optional) It supports three types: "raw", "buffer" and "datauri". If ignored, it’s "datauri" by default. + */ + datatype?: string + } + + /** + * This includes multiple functions to manipulate the cookies. + */ + interface Cookies { + + /** + * Retrieves information about a single cookie. + * + * @param details {Objet} Details to identify the cookie being retrieved. + * @param callback {function(cookie?)} The callback when cookie retrieved. + * - (Optional) cookie {Cookie} Contains details about the cookie. This parameter is null if no such cookie was found. + */ + get( details: CookiesGetDetails, callback: ( cookie?: Cookie ) => void ): void; + + /** + * Retrieves all cookies from a single cookie store that match the given information. + * + * @param details {Objet} Information to filter the cookies being retrieved. + * @param callback {function(cookies?)} The callback when cookies retrieved. + * - (Optional) cookies {Cookie[]} All the existing, unexpired cookies that match the given cookie info. + */ + getAll( details: CookiesGetAllDetails, callback: ( cookies?: Cookie[] ) => void ): void; + + /** + * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. + * + * @param details {Objet} Details about the cookie being set. + * @param callback {function(cookie?)} The callback when cookie has been set. + * - (Optional) cookie {Cookie} Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. + */ + set( details: CookiesSetDetails, callback: ( cookie?: Cookie ) => void ): void; + + /** + * Deletes a cookie by name. + * + * @param details {Objet} Information to identify the cookie to remove. + * @param callback {function(cookie?)} The callback when cookie has been set. + * - (Optional) details {Objet} Contains details about the cookie that's been removed. If removal failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. + */ + remove( details: CookiesRemoveDetails, callback: ( details?: CookiesRemovedDetails ) => void ): void; + + /** + * Fired when a cookie is set or removed. + */ + onChanged: { + /** + * Add a new listener for onChanged event. + * + * @param callback {function(changeInfo?)} The callback when cookie has been changed. + * - (Optional) changeInfo {Objet} Contains details about the cookie that's been changed. + */ + addListener( callback: ( changeInfo: CookiesOnChangedCallbackChangeInfo ) => void ): void; + } + } + + /** + * Represents information about an HTTP cookie. + */ + interface Cookie { + + /** + * The name of the cookie. + */ + name: string; + + /** + * The value of the cookie. + */ + value: string; + + /** + * The domain of the cookie (e.g. "www.google.com", "example.com"). + */ + domain: string; + + /** + * True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie). + */ + hostOnly: boolean; + + /** + * The path of the cookie. + */ + path: string; + + /** + * True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS). + */ + secure: boolean; + + /** + * True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts). + */ + httpOnly: boolean; + + /** + * The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests). + */ + sameSite: string | "no_restriction" | "lax" | "strict"; + + /** + * True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date. + */ + session: boolean; + + /** + * (Optional) The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies. + */ + expirationDate?: number; + + /** + * The ID of the cookie store containing this cookie. + */ + storeId: string; + } + + /** + * Coockies.get() details argument object + */ + interface CookiesGetDetails { + + /** + * The URL with which the cookie to retrieve is associated. + */ + url: string; + + /** + * The name of the cookie to retrieve. + */ + name: string; + + /** + * The ID of the cookie store in which to look for the cookie. + */ + storeId: string; + } + + /** + * Coockies.getAll() details argument object + */ + interface CookiesGetAllDetails { + + /** + * Restricts the retrieved cookies to those that would match the given URL. + */ + url?: string; + + /** + * Filters the cookies by name. + */ + name?: string; + + /** + * Restricts the retrieved cookies to those whose domains match or are subdomains of this one. + */ + domain?: string; + + /** + * Restricts the retrieved cookies to those whose path exactly matches this string. + */ + path?: string; + + /** + * Filters the cookies by their Secure property. + */ + secure?: boolean; + + /** + * Filters out session vs. persistent cookies. + */ + session: boolean; + + /** + * The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. + */ + storeId?: string; + } + + /** + * Coockies.set() details argument object + */ + interface CookiesSetDetails { + + /** + * The request-URI to associate with the setting of the cookie. + */ + url: string; + + /** + * The name of the cookie. Empty by default if omitted. + */ + name?: string; + + /** + * The value of the cookie. Empty by default if omitted. + */ + value?: string; + + /** + * The domain of the cookie. If omitted, the cookie becomes a host-only cookie. + */ + domain?: string; + + /** + * The path of the cookie. Defaults to the path portion of the url parameter. + */ + path?: string; + + /** + * Whether the cookie should be marked as Secure. Defaults to false. + */ + secure?: boolean; + + /** + * Whether the cookie should be marked as HttpOnly. Defaults to false. + */ + httpOnly?: boolean; + + /** + * The cookie's same-site status: defaults to 'no_restriction'. + */ + sameSite?: string | "no_restriction" | "lax" | "strict"; + + /** + * The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie. + */ + expirationDate?: number; + + /** + * The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store. + */ + storeId?: string; + } + + /** + * Coockies.remove() details argument object + */ + interface CookiesRemoveDetails { + + /** + * The URL associated with the cookie. + */ + url: string; + + /** + * The name of the cookie to remove. + */ + name: string; + + /** + * The ID of the cookie store to look in for the cookie. + */ + storeId: string; + } + + /** + * Coockies.remove() callback details argument object + */ + interface CookiesRemovedDetails { + + /** + * The URL associated with the cookie that's been removed. + */ + url: string; + + /** + * The name of the cookie that's been removed. + */ + name: string; + + /** + * The ID of the cookie store from which the cookie was removed. + */ + storeId: string; + } + + /** + * Coockies.onChanged.addListener() callback details argument object + */ + interface CookiesOnChangedCallbackChangeInfo { + + /** + * True if a cookie was removed. + */ + removed: boolean; + + /** + * Information about the cookie that was set or removed. + */ + cookie: Cookie; + + /** + * The underlying reason behind the cookie's change. + */ + cause: string | "evicted" | "expired" | "explicit" | "expired_overwrite" | "overwrite" + } + + /** + * nw.Window.get().on('new-win-policy') callback policy argument object + */ + interface WinPolicy { + + /** + * Ignore the request, navigation won’t happen. + */ + ignore(): void; + + /** + * Force the link to be opened in the same frame + */ + forceCurrent(): void; + + /** + * Force the link to be a downloadable, or open by external program + */ + forceDownload(): void; + + /** + * Force the link to be opened in a new window + */ + forceNewWindow(): void; + + /** + * Force the link to be opened in a new popup window + */ + forceNewPopup(): void; + + /** + * Control the options for the new popup window. + * + *@param m {Object} The object is in the same format as the Window subfields in manifest format. + */ + setNewWindowManifest( m: WindowOption ): void; + } + + /** + * nw.Window Option that is in the same format as the Window subfields in manifest format. + */ + interface WindowOption { + + /** + * The id used to identify the window. + */ + id?: string; + + /** + * The default title of window created by NW.js + */ + title?: string; + + /** + * The initial width of the main window. + */ + width?: number; + + /** + * The initial height of the main window. + */ + height?: number; + + /** + * Path to window’s icon + */ + icon?: string; + + /** + * Controls where window will be put, be `null` or `center` or `mouse` + */ + position?: string; + + /** + * Minimum width of window + */ + min_width?: number; + + /** + * Minimum height of window + */ + min_height?: number; + + /** + * Maximum width of window + */ + max_width?: number; + + /** + * Maximum height of window + */ + max_height?: number; + + /** + * Show as desktop background window under X11 environment + */ + as_desktop?: boolean; + + /** + * Whether window is resizable + */ + resizable?: boolean; + + /** + * Whether the window should always stay on top of other windows. + */ + always_on_top?: boolean; + + /** + * Whether the window should be visible on all workspaces simultaneously (on platforms that support multiple workspaces, currently Mac OS X and Linux). + */ + visible_on_all_workspaces?: boolean; + + /** + * Whether window is fullscreen + */ + fullscreen?: boolean; + + /** + * Whether the window is shown in taskbar or dock. The default is true. + */ + show_in_taskbar?: boolean; + + /** + * Specify it to false to make the window frameless + */ + frame?: boolean; + + /** + * Specify it to false if you want your app to be hidden on startup + */ + show?: boolean; + + /** + * Whether to use Kiosk mode. + */ + kiosk?: boolean; + + /** + * Whether to turn on transparent window mode. + */ + transparent?: boolean; + } + + interface WindowOpenOption extends WindowOption { + + /** + * (Optional) Whether to open a new window in a separate render process. + */ + new_instance?: boolean; + + /** + * (Optional) The script to be injected before document loaded. + */ + inject_js_start?: string; + + /** + * (Optional) The script to be injected before document unloaded. + */ + inject_js_end?: string; + + /** + * (Optional) The id used to identify the window. + */ + id?: string; + } + + /** + * nw.Window.get().on('navigation') callback policy argument object + */ + interface WinNavigationPolicy { + + /** + * Ignore the request, navigation won’t happen. + */ + ignore(): void; + } + + interface win extends EventEmitter { + + /** + * Get the corresponding DOM window object of the native window. + */ + window: Object; + + /** + * Get or set left offset from window to screen. + */ + x: number; + + /** + * Get or set top offset from window to screen. + */ + y: number; + + /** + * Get or set window's width. + */ + width: number; + + /** + * Get or set window's height. + */ + height: number; + + /** + * Get or set window's title. + */ + title: string; + + /** + * Get or set window's menubar. + */ + menu: nw.Menu; + + /** + * Get whether we're in fullscreen mode. + */ + isFullscreen: boolean; + + /** + * Get whether transparency is turned on + */ + isTransparent: boolean; + + /** + * Get whether we're in kiosk mode. + */ + isKioskMode: boolean; + + /** + * Get or set the page zoom. + */ + zoomLevel: number; + + /** + * This includes multiple functions to manipulate the cookies. + */ + cookies: Cookies; + + /** + * Moves a window's left and top edge to the specified coordinates. + * + * @param x {Integer} Offset to the left of the screen + * @param y {Integer} Offset to the top of the screen + */ + moveTo( x: number, y: number ): void; + + /** + * Moves a window a specified number of pixels relative to its current coordinates. + * + * @param x {Integer} Horizontal offset + * @param y {Integer} Vertical offset + */ + moveBy( x: number, y: number ): void; + + /** + * Resizes a window to the specified width and height. + * + * @param width {Integer} The width of the window + * @param height {Integer} The height of the window + */ + resizeTo( width: number, height: number ): void; + + /** + * Resizes a window by the specified amount. + * + * @param width {Integer} The offset width of the window + * @param height {Integer} The offset height of the window + */ + resizeBy( width: number, height: number ): void; + + /** + * Focus on the window. + */ + focus(): void; + + /** + * Move focus away. + */ + blur(): void; + + /** + * Show the window if it's not shown. + * + * @param is_show {boolean} (Optional) Specify whether the window should be shown or hidden. It's set to true by default. + */ + show( is_show?: boolean ): void; + + /** + * Hide the window. + */ + hide(): void; + + /** + * Close current window. + * + * @param force {boolean} (Optional) Specify whether to close the window forcely and bypass close event. + */ + close( force?: boolean ): void; + + /** + * Reloads the current window. + */ + reload(): void; + + /** + * Reloads the current page by starting a new renderer process from scratch. + */ + reloadDev(): void; + + /** + * Like reload(), but don't use caches (aka 'shift-reload'). + */ + reloadIgnoringCache(): void; + + /** + * Maximize the window on GTK and Windows, and zoom the window on Mac OS X. + */ + maximize(): void; + + /** + * Minimize the window to task bar on Windows, iconify the window on GTK, and miniaturize the window on Mac OS X. + */ + minimize(): void; + + /** + * Restore window to previous state after the window is minimized. + */ + restore(): void; + + /** + * Make the window fullscreen. + */ + enterFullscreen(): void; + + /** + * Leave the fullscreen mode. + */ + leaveFullscreen(): void; + + /** + * Toggle the fullscreen mode. + */ + toggleFullscreen(): void; + + /** + * Enter the Kiosk mode. + */ + enterKioskMode(): void; + + /** + * Leave the Kiosk mode. + */ + leaveKioskMode(): void; + + /** + * Toggle the kiosk mode. + */ + toggleKioskMode(): void; + + /** + * Open the devtools to inspect the window. + * + * @param iframe {Integer} (Optional) the id or the element of the